From eece174ad00f11db8688a36f7c7ef57c9ced98db Mon Sep 17 00:00:00 2001
From: klu2 <klu2@6f19259b-4bc3-4df7-8a09-765794883524>
Date: Sat, 29 Jul 2006 14:29:59 +0000
Subject: [PATCH] 1, Fix EDKT141 2, Code clean up for PCD building tools.

git-svn-id: https://edk2.svn.sourceforge.net/svnroot/edk2/trunk/edk2@1150 6f19259b-4bc3-4df7-8a09-765794883524
---
 .../org/tianocore/build/autogen/AutoGen.java  |  55 +--
 .../tianocore/build/global/GlobalData.java    |  17 +-
 .../build/pcd/action/CollectPCDAction.java    | 240 ++++++-----
 .../build/pcd/action/PCDAutoGenAction.java    | 394 ++++--------------
 .../build/pcd/entity/DynamicTokenValue.java   |  20 -
 .../pcd/entity/MemoryDatabaseManager.java     |  39 +-
 .../org/tianocore/build/pcd/entity/Token.java | 170 ++++----
 .../build/pcd/entity/UsageInstance.java       | 201 ++++-----
 8 files changed, 460 insertions(+), 676 deletions(-)

diff --git a/Tools/Source/GenBuild/org/tianocore/build/autogen/AutoGen.java b/Tools/Source/GenBuild/org/tianocore/build/autogen/AutoGen.java
index 366e0ac59d..a8ec270355 100644
--- a/Tools/Source/GenBuild/org/tianocore/build/autogen/AutoGen.java
+++ b/Tools/Source/GenBuild/org/tianocore/build/autogen/AutoGen.java
@@ -456,25 +456,18 @@ public class AutoGen {
 		GuidGuidToAutogenC(fileBuffer);
 
 		//
-		// Call pcd autogen. PCDAutoGenAction tool only need module name and
-		// isPcdEmulatedDriver as parameter. Library inherits PCD and module's
-		// PCD information has been collected in FPDParser task by
-		// CollectPCDAction.
-		// Note : when PCD image tool ready,
-		// isPCDEmulatedDriver parameter will be removed.
+		// Call pcd autogen. 
 		//
-		 try {
-//		 this.myPcdAutogen = new PCDAutoGenAction(moduleId.getName(),
-//		 moduleId.getGuid(), moduleId.getPackage().getName(), moduleId.getPackage().getGuid(),this.arch,moduleId.getVersion(),false, null);
-         this.myPcdAutogen = new PCDAutoGenAction(moduleId.getName(),null,null,null, this.arch,null,false, null);
-		 this.myPcdAutogen.execute();
-		 } catch (Exception e) {
-		 throw new BuildException("PCD Autogen failed:" + e.getMessage());
-		 }
+                this.myPcdAutogen = new PCDAutoGenAction(moduleId, this.arch, false, null);
+                try {
+                    this.myPcdAutogen.execute();
+                } catch (Exception exp) {
+                    throw new BuildException (exp.getMessage());
+                }
 		
 		if (this.myPcdAutogen != null) {
-            fileBuffer.append("\r\n");
-			fileBuffer.append(this.myPcdAutogen.OutputC());
+                    fileBuffer.append("\r\n");
+                    fileBuffer.append(this.myPcdAutogen.OutputC());
 		}
 
 		if (!saveFile(outputPath + File.separatorChar + "AutoGen.c", fileBuffer)) {
@@ -613,33 +606,21 @@ public class AutoGen {
 		fileBuffer.append("\r\n");
 
 		//
-		// Call pcd autogen. PCDAutoGenAction tool only need module name and
-		// isPcdEmulatedDriver as parameter. Library inherit PCD and module's
-		// PCD information has been collected in FPDParser task by
-		// CollectPCDAction.
-		// Note : when PCD image tool ready,
-		// isPCDEmulatedDriver parameter will be removed.
+		// Call pcd autogen. 
 		//
+                this.myPcdAutogen = new PCDAutoGenAction(this.moduleId,
+                                                         this.arch,
+                                                         true, 
+                                                         SurfaceAreaQuery.getModulePcdEntryNameArray());
 		try {
-//			 this.myPcdAutogen = new PCDAutoGenAction(this.moduleId.getName(),
-//			 this.moduleId.getGuid(),moduleId.getPackage().getName(),moduleId.getPackage().getGuid(), this.arch, moduleId.getVersion(),true, SurfaceAreaQuery.getModulePcdEntryNameArray());
-            this.myPcdAutogen = new PCDAutoGenAction(this.moduleId.getName(),
-                                                     null,
-                                                     null,
-                                                     null,
-                                                     this.arch,
-                                                     null,
-                                                     true, 
-                                                     SurfaceAreaQuery.getModulePcdEntryNameArray());
-                     
-			this.myPcdAutogen.execute();
+                    this.myPcdAutogen.execute();
 		} catch (Exception e) {
-			throw new BuildException(e.getMessage());
+                    throw new BuildException(e.getMessage());
 		}
 
 		if (this.myPcdAutogen != null) {
-            fileBuffer.append("\r\n");
-			fileBuffer.append(this.myPcdAutogen.OutputC());
+                    fileBuffer.append("\r\n");
+                    fileBuffer.append(this.myPcdAutogen.OutputC());
 		}
 
 		if (!saveFile(outputPath + File.separatorChar + "AutoGen.c", fileBuffer)) {
diff --git a/Tools/Source/GenBuild/org/tianocore/build/global/GlobalData.java b/Tools/Source/GenBuild/org/tianocore/build/global/GlobalData.java
index 18b766dc42..a769816720 100644
--- a/Tools/Source/GenBuild/org/tianocore/build/global/GlobalData.java
+++ b/Tools/Source/GenBuild/org/tianocore/build/global/GlobalData.java
@@ -807,8 +807,8 @@ public class GlobalData {
     //
     // For PCD
     //
-    public synchronized static Map<FpdModuleIdentification, XmlObject> getFpdModuleSaXmlObject(
-            String xmlObjectName) {
+    public synchronized static Map<FpdModuleIdentification, XmlObject> 
+                               getFpdModuleSaXmlObject(String xmlObjectName) {
         Set<FpdModuleIdentification> fpdModuleSASet = fpdModuleSA.keySet();
         Iterator item = fpdModuleSASet.iterator();
         
@@ -823,17 +823,20 @@ public class GlobalData {
             try{
                 if (SANode.get(xmlObjectName)!= null){
                     SAPcdBuildDef.put(moduleId,
-                            (XmlObject) SANode
-                                    .get(xmlObjectName));
+                            (XmlObject) SANode.get(xmlObjectName));
 
                 }
-                            
-                
             } catch (Exception e){
                 EdkLog.log(EdkLog.EDK_INFO, e.getMessage());
             }
-            }
+        }
         return SAPcdBuildDef;
     }
+
+    public synchronized static Map<FpdModuleIdentification,XmlObject> getFpdPcdBuildDefinitions() {
+        Map<FpdModuleIdentification,XmlObject> pcdBuildDef = getFpdModuleSaXmlObject ("PcdBuildDefinition");
+
+        return pcdBuildDef;
+    }
 }
 
diff --git a/Tools/Source/GenBuild/org/tianocore/build/pcd/action/CollectPCDAction.java b/Tools/Source/GenBuild/org/tianocore/build/pcd/action/CollectPCDAction.java
index 4d3aadd961..8242a4c87c 100644
--- a/Tools/Source/GenBuild/org/tianocore/build/pcd/action/CollectPCDAction.java
+++ b/Tools/Source/GenBuild/org/tianocore/build/pcd/action/CollectPCDAction.java
@@ -1124,7 +1124,7 @@ class PcdDatabase {
             if (t.isDynamicEx()) {
                 exMapTable.add((int)t.tokenNumber, 
                                 t.dynamicExTokenNumber, 
-                                guidTable.add(t.tokenSpaceName, t.getPrimaryKeyString()), 
+                                guidTable.add(translateSchemaStringToUUID(t.tokenSpaceName), t.getPrimaryKeyString()), 
                                 t.getPrimaryKeyString()
                                 );
             }
@@ -1387,7 +1387,7 @@ class PcdDatabase {
     }
     
     private String getDataTypeDeclarationForVariableDefault (Token token, String cName, int skuId) 
-    throws EntityException {
+        throws EntityException {
 
         String typeStr;
 
@@ -1565,28 +1565,119 @@ class PcdDatabase {
         return retStr;
     }
 
+    /**
+       Translate the schema string to UUID instance.
+       
+       In schema, the string of UUID is defined as following two types string:
+        1) GuidArrayType: pattern = 0x[a-fA-F0-9]{1,8},( )*0x[a-fA-F0-9]{1,4},(
+        )*0x[a-fA-F0-9]{1,4}(,( )*\{)?(,?( )*0x[a-fA-F0-9]{1,2}){8}( )*(\})?
+       
+        2) GuidNamingConvention: pattern =
+        [a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}
+       
+       This function will convert string and create uuid instance.
+       
+       @param uuidString    UUID string in XML file
+       
+       @return UUID         UUID instance
+    **/
+    private UUID translateSchemaStringToUUID(String uuidString) 
+        throws EntityException {
+        String      temp;
+        String[]    splitStringArray;
+        int         index;
+        int         chIndex;
+        int         chLen;
+
+        if (uuidString == null) {
+            return null;
+        }
+
+        if (uuidString.length() == 0) {
+            return null;
+        }
+
+        if (uuidString.equals("0") ||
+            uuidString.equalsIgnoreCase("0x0")) {
+            return new UUID(0, 0);
+        }
+
+        uuidString = uuidString.replaceAll("\\{", "");
+        uuidString = uuidString.replaceAll("\\}", "");
+
+        //
+        // If the UUID schema string is GuidArrayType type then need translate 
+        // to GuidNamingConvention type at first.
+        // 
+        if ((uuidString.charAt(0) == '0') && ((uuidString.charAt(1) == 'x') || (uuidString.charAt(1) == 'X'))) {
+            splitStringArray = uuidString.split("," );
+            if (splitStringArray.length != 11) {
+                throw new EntityException ("[FPD file error] Wrong format for UUID string: " + uuidString);
+            }
+
+            //
+            // Remove blank space from these string and remove header string "0x"
+            // 
+            for (index = 0; index < 11; index ++) {
+                splitStringArray[index] = splitStringArray[index].trim();
+                splitStringArray[index] = splitStringArray[index].substring(2, splitStringArray[index].length());
+            }
+
+            //
+            // Add heading '0' to normalize the string length
+            // 
+            for (index = 3; index < 11; index ++) {
+                chLen = splitStringArray[index].length();
+                for (chIndex = 0; chIndex < 2 - chLen; chIndex ++) {
+                    splitStringArray[index] = "0" + splitStringArray[index];
+                }
+            }
+
+            //
+            // construct the final GuidNamingConvention string
+            // 
+            temp = String.format("%s-%s-%s-%s%s-%s%s%s%s%s%s",
+                                 splitStringArray[0],
+                                 splitStringArray[1],
+                                 splitStringArray[2],
+                                 splitStringArray[3],
+                                 splitStringArray[4],
+                                 splitStringArray[5],
+                                 splitStringArray[6],
+                                 splitStringArray[7],
+                                 splitStringArray[8],
+                                 splitStringArray[9],
+                                 splitStringArray[10]);
+            uuidString = temp;
+        }
+
+        return UUID.fromString(uuidString);
+    }
 }
 
+/** Module Info class is the data structure to hold information got from GlobalData.
+*/
 class ModuleInfo {
-    private String                  type;
-    private FpdModuleIdentification moduleId;
+    ///
+    /// Module's ID for a <ModuleSA>
+    /// 
+    private FpdModuleIdentification                       moduleId;
+    ///
+    /// <PcdBuildDefinition> xmlobject in FPD file for a <ModuleSA>
+    /// 
     private PcdBuildDefinitionDocument.PcdBuildDefinition pcdBuildDef;
-    
-    
 
-    public ModuleInfo (FpdModuleIdentification moduleId, String type, XmlObject pcdDef) {
-        this.moduleId = moduleId;
-        this.type   = type;
-        this.pcdBuildDef = ((PcdBuildDefinitionDocument)pcdDef).getPcdBuildDefinition();
-    }
-    public String getModuleType (){
-    	return this.type;
+    public ModuleInfo (FpdModuleIdentification moduleId, XmlObject pcdDef) {
+        this.moduleId       = moduleId;
+        this.pcdBuildDef    = ((PcdBuildDefinitionDocument)pcdDef).getPcdBuildDefinition();
     }
+
     public FpdModuleIdentification getModuleId (){
-    	return this.moduleId;
+    	return moduleId;
     }
+
     public PcdBuildDefinitionDocument.PcdBuildDefinition getPcdBuildDef(){
-    	return this.pcdBuildDef;
+    	return pcdBuildDef;
     }
 }
 
@@ -1595,22 +1686,29 @@ class ModuleInfo {
     from buildAction or UIAction.
 **/
 public class CollectPCDAction {
+    ///
     /// memoryDatabase hold all PCD information collected from SPD, MSA, FPD.
+    /// 
     private MemoryDatabaseManager dbManager;
-
+    ///
     /// Workspacepath hold the workspace information.
+    /// 
     private String                workspacePath;
-
+    ///
     /// FPD file is the root file. 
+    /// 
     private String                fpdFilePath;
-
+    ///
     /// Message level for CollectPCDAction.
+    /// 
     private int                   originalMessageLevel;
-
+    ///
     /// Cache the fpd docment instance for private usage.
+    /// 
     private PlatformSurfaceAreaDocument fpdDocInstance;
-    
+    ///
     /// xmlObject name
+    /// 
     private static String xmlObjectName = "PcdBuildDefinition"; 
     	
     /**
@@ -1697,8 +1795,7 @@ public class CollectPCDAction {
         createTokenInDBFromFPD();
         
         //
-        // Call Private function genPcdDatabaseSourceCode (void); ComponentTypeBsDriver
-        // 1) Generate for PEI, DXE PCD DATABASE's definition and initialization.
+        // Generate for PEI, DXE PCD DATABASE's definition and initialization.
         //
         genPcdDatabaseSourceCode ();
         
@@ -1713,7 +1810,7 @@ public class CollectPCDAction {
     **/
     private void genPcdDatabaseSourceCode()
         throws EntityException {
-        String PcdCommonHeaderString = PcdDatabase.getPcdDatabaseCommonDefinitions ();
+        String PcdCommonHeaderString = PcdDatabase.getPcdDatabaseCommonDefinitions();
 
         ArrayList<Token> alPei = new ArrayList<Token> ();
         ArrayList<Token> alDxe = new ArrayList<Token> ();
@@ -1721,17 +1818,14 @@ public class CollectPCDAction {
         dbManager.getTwoPhaseDynamicRecordArray(alPei, alDxe);
         PcdDatabase pcdPeiDatabase = new PcdDatabase (alPei, "PEI", 0);
         pcdPeiDatabase.genCode();
-        MemoryDatabaseManager.PcdPeimHString        = PcdCommonHeaderString + pcdPeiDatabase.getHString()
-                                            + PcdDatabase.getPcdPeiDatabaseDefinitions();
+        MemoryDatabaseManager.PcdPeimHString        = PcdCommonHeaderString + pcdPeiDatabase.getHString() + 
+                                                      PcdDatabase.getPcdPeiDatabaseDefinitions();
         MemoryDatabaseManager.PcdPeimCString        = pcdPeiDatabase.getCString();
 
-        PcdDatabase pcdDxeDatabase = new PcdDatabase (alDxe, 
-                                                      "DXE",
-                                                      alPei.size()
-                                                      );
+        PcdDatabase pcdDxeDatabase = new PcdDatabase(alDxe, "DXE", alPei.size());
         pcdDxeDatabase.genCode();
-        MemoryDatabaseManager.PcdDxeHString   = MemoryDatabaseManager.PcdPeimHString + pcdDxeDatabase.getHString()
-                                      + PcdDatabase.getPcdDxeDatabaseDefinitions();
+        MemoryDatabaseManager.PcdDxeHString   = MemoryDatabaseManager.PcdPeimHString + pcdDxeDatabase.getHString() + 
+                                                PcdDatabase.getPcdDxeDatabaseDefinitions();
         MemoryDatabaseManager.PcdDxeCString   = pcdDxeDatabase.getCString();
     }
 
@@ -1745,30 +1839,23 @@ public class CollectPCDAction {
      */
     private List<ModuleInfo> getComponentsFromFPD() 
         throws EntityException {
-        List<ModuleInfo>            allModules  = new ArrayList<ModuleInfo>();
-        ModuleInfo                  current     = null;
-        int                         index       = 0;
-        FrameworkModulesDocument.FrameworkModules fModules = null;
-        ModuleSADocument.ModuleSA[]               modules  = null;
-        HashMap<String, XmlObject>                map      = new HashMap<String, XmlObject>();
-
-        if (fpdDocInstance == null) {
-            try {
-                fpdDocInstance = (PlatformSurfaceAreaDocument)XmlObject.Factory.parse(new File(fpdFilePath));
-            } catch(IOException ioE) {
-                throw new EntityException("File IO error for xml file:" + fpdFilePath + "\n" + ioE.getMessage());
-            } catch(XmlException xmlE) {
-                throw new EntityException("Can't parse the FPD xml fle:" + fpdFilePath + "\n" + xmlE.getMessage());
-            }
+        List<ModuleInfo>                            allModules          = new ArrayList<ModuleInfo>();
+        FrameworkModulesDocument.FrameworkModules   fModules            = null;
+        ModuleSADocument.ModuleSA[]                 modules             = null;
+        Map<FpdModuleIdentification, XmlObject>     pcdBuildDefinitions = null;
 
+        pcdBuildDefinitions = GlobalData.getFpdPcdBuildDefinitions();
+        if (pcdBuildDefinitions == null) {
+            return null;
         }
 
-        Map<FpdModuleIdentification,XmlObject>pcdBuildDef = GlobalData.getFpdModuleSaXmlObject(CollectPCDAction.xmlObjectName);
-        Set<FpdModuleIdentification> pcdBuildKeySet = pcdBuildDef.keySet();
-        Iterator item = pcdBuildKeySet.iterator();
+        //
+        // Loop map to retrieve all PCD build definition and Module id 
+        // 
+        Iterator item = pcdBuildDefinitions.keySet().iterator();
         while (item.hasNext()){
-            FpdModuleIdentification id = (FpdModuleIdentification)item.next();
-            allModules.add(new ModuleInfo(id, id.getModule().getModuleType(),pcdBuildDef.get(id)));    
+            FpdModuleIdentification id = (FpdModuleIdentification) item.next();
+            allModules.add(new ModuleInfo(id, pcdBuildDefinitions.get(id)));    
         }
         
         return allModules;
@@ -1824,34 +1911,6 @@ public class CollectPCDAction {
         // -------------------------------------------------------------------
         // 
         for (index = 0; index < modules.size(); index ++) {
-            isDuplicate =  false;
-            for (index2 = 0; index2 < index; index2 ++) {
-                //
-                // BUGBUG: For transition schema, we can *not* get module's version from 
-                // <ModuleSAs>, It is work around code.
-                // 
-                primaryKey1 = UsageInstance.getPrimaryKey(modules.get(index).getModuleId().getModule().getName(), 
-                                                          null,
-                                                          null,
-                                                          null, 
-                                                          modules.get(index).getModuleId().getArch(),
-                                                          null);
-                primaryKey2 = UsageInstance.getPrimaryKey(modules.get(index2).getModuleId().getModule().getName(), 
-                                                          null, 
-                                                          null, 
-                                                          null, 
-                                                          modules.get(index2).getModuleId().getArch(), 
-                                                          null);
-                if (primaryKey1.equalsIgnoreCase(primaryKey2)) {
-                    isDuplicate = true;
-                    break;
-                }
-            }
-
-            if (isDuplicate) {
-                continue;
-            }
-
     	    //
     	    // It is legal for a module does not contains ANY pcd build definitions.
     	    // 
@@ -1881,8 +1940,7 @@ public class CollectPCDAction {
                     throw new EntityException ("Fail to get Token space guid for token" + pcdBuildData.getCName());
                 } 
 
-                primaryKey   = Token.getPrimaryKeyString(pcdBuildData.getCName(),
-                                                         translateSchemaStringToUUID(tokenSpaceStrRet[1]));
+                primaryKey   = Token.getPrimaryKeyString(pcdBuildData.getCName(), tokenSpaceStrRet[1]);
                 pcdType      = Token.getpcdTypeFromString(pcdBuildData.getItemType().toString());
                 datumType    = Token.getdatumTypeFromString(pcdBuildData.getDatumType().toString());
                 tokenNumber  = Long.decode(pcdBuildData.getToken().toString());
@@ -2021,8 +2079,7 @@ public class CollectPCDAction {
                         throw new EntityException("Fail to get token space guid for token " + token.cName);
                     }
 
-                    token = new Token(pcdBuildData.getCName(), 
-                                      translateSchemaStringToUUID(tokenSpaceStrRet[1]));
+                    token = new Token(pcdBuildData.getCName(), tokenSpaceStrRet[1]);
     
                     token.datumType     = datumType;
                     token.tokenNumber   = tokenNumber;
@@ -2056,14 +2113,9 @@ public class CollectPCDAction {
                 // ------------------------------------------------
                 // 
                 usageInstance = new UsageInstance(token, 
-                                                  moduleName, 
-                                                  null,
-                                                  null,
-                                                  null,
-                                                  CommonDefinition.getModuleType(modules.get(index).getModuleType()), 
+                                                  modules.get(index).getModuleId().getModule(), 
                                                   pcdType,
                                                   modules.get(index).getModuleId().getArch(), 
-                                                  null,
                                                   datum,
                                                   maxDatumSize);
                 token.addUsageInstance(usageInstance);
@@ -2103,7 +2155,8 @@ public class CollectPCDAction {
         String  variableGuidString[];
 
         //
-        // If FPD document is not be opened, open and initialize it.
+        // Open fpd document to get <DynamicPcdBuildDefinition> Section.
+        // BUGBUG: the function should be move GlobalData in furture.
         // 
         if (fpdDocInstance == null) {
             try {
@@ -2134,7 +2187,7 @@ public class CollectPCDAction {
             } 
 
             primaryKey = Token.getPrimaryKeyString(pcdBuildData.getCName(),
-                                                   translateSchemaStringToUUID(tokenSpaceStrRet[1]));
+                                                   tokenSpaceStrRet[1]);
 
             if (dbManager.isTokenInDatabase(primaryKey)) {
                 continue;
@@ -2149,7 +2202,7 @@ public class CollectPCDAction {
             //
             // Create new token for unreference dynamic PCD token
             // 
-            token           = new Token(pcdBuildData.getCName(), translateSchemaStringToUUID(tokenSpaceStrRet[1]));
+            token           = new Token(pcdBuildData.getCName(), tokenSpaceStrRet[1]);
             token.datumSize = pcdBuildData.getMaxDatumSize();
             
 
@@ -2662,6 +2715,7 @@ public class CollectPCDAction {
 
         //
         // If FPD document is not be opened, open and initialize it.
+        // BUGBUG: The code should be moved into GlobalData in future.
         // 
         if (fpdDocInstance == null) {
             try {
@@ -2697,7 +2751,7 @@ public class CollectPCDAction {
             }
 
             dynamicPrimaryKey = Token.getPrimaryKeyString(dynamicPcdBuildDataArray.get(index).getCName(),
-                                                          translateSchemaStringToUUID(tokenSpaceStrRet[1]));
+                                                          tokenSpaceStrRet[1]);
             if (dynamicPrimaryKey.equalsIgnoreCase(token.getPrimaryKeyString())) {
                 return dynamicPcdBuildDataArray.get(index);
             }
diff --git a/Tools/Source/GenBuild/org/tianocore/build/pcd/action/PCDAutoGenAction.java b/Tools/Source/GenBuild/org/tianocore/build/pcd/action/PCDAutoGenAction.java
index ad4ebe78af..2707c5d1a8 100644
--- a/Tools/Source/GenBuild/org/tianocore/build/pcd/action/PCDAutoGenAction.java
+++ b/Tools/Source/GenBuild/org/tianocore/build/pcd/action/PCDAutoGenAction.java
@@ -28,6 +28,7 @@ import java.util.regex.Pattern;
 import org.apache.xmlbeans.XmlObject;
 import org.tianocore.build.global.GlobalData;
 import org.tianocore.build.global.SurfaceAreaQuery;
+import org.tianocore.build.id.ModuleIdentification;
 import org.tianocore.build.pcd.entity.MemoryDatabaseManager;
 import org.tianocore.build.pcd.entity.Token;
 import org.tianocore.build.pcd.entity.UsageInstance;
@@ -43,30 +44,14 @@ public class PCDAutoGenAction extends BuildAction {
     ///
     private MemoryDatabaseManager dbManager;
     ///
-    /// The name of module which is analysised currently.
-    ///
-    private String                moduleName;
-    ///
-    /// The Guid of module which is analyzed currently.
+    /// The identification for a module.
     /// 
-    private UUID                  moduleGuid;
-    ///
-    /// The name of package whose module is analysized currently.
-    /// 
-    private String                packageName;
-    ///
-    /// The Guid of package whose module is analyszed curretnly.
-    /// 
-    private UUID                  packageGuid;
+    private ModuleIdentification  moduleId;
     ///
     /// The arch of current module
     /// 
     private String                arch;
     ///
-    /// The version of current module
-    /// 
-    private String                version;
-    ///
     /// Whether current autogen is for building library used by current module.
     /// 
     private boolean               isBuildUsedLibrary;
@@ -81,41 +66,14 @@ public class PCDAutoGenAction extends BuildAction {
     ///
     /// The name array of <PcdCoded> in a module.
     /// 
-    private String[]              pcdNameArray;
+    private String[]              pcdNameArrayInMsa;
     /**
-      Set parameter ModuleName
+      Set parameter moduleId
   
       @param moduleName   the module name parameter.
     **/
-    public void setModuleName(String moduleName) {
-        this.moduleName = moduleName;
-    }
-
-    /**
-       set the moduleGuid parameter.
-       
-       @param moduleGuid
-    **/
-    public void setModuleGuid(UUID moduleGuid) {
-        this.moduleGuid = moduleGuid;
-    }
-
-    /**
-       set packageName parameter.
-       
-       @param packageName
-    **/
-    public void setPackageName(String packageName) {
-        this.packageName = packageName;
-    }
-
-    /**
-        set packageGuid parameter.
-       
-       @param packageGuid
-    **/
-    public void setPackageGuid(UUID packageGuid) {
-        this.packageGuid = packageGuid;
+    public void setModuleId(ModuleIdentification moduleId) {
+        this.moduleId = moduleId;
     }
 
     /**
@@ -127,30 +85,22 @@ public class PCDAutoGenAction extends BuildAction {
         this.arch = arch;
     }
 
-    /**
-       set version parameter
-       
-       @param version
-     */
-    public void setVersion(String version) {
-        this.version = version;
-    }
-
     /**
        set isBuildUsedLibrary parameter.
        
        @param isBuildUsedLibrary
-     */
+    **/
     public void setIsBuildUsedLibrary(boolean isBuildUsedLibrary) {
         this.isBuildUsedLibrary = isBuildUsedLibrary;
     }
+
     /**
-       set pcdNameArray parameter.
+       set pcdNameArrayInMsa parameter.
        
-       @param pcdNameArray
+       @param pcdNameArrayInMsa
      */
-    public void setPcdNameArray(String[] pcdNameArray) {
-        this.pcdNameArray = pcdNameArray;
+    public void setPcdNameArrayInMsa(String[] pcdNameArrayInMsa) {
+        this.pcdNameArrayInMsa = pcdNameArrayInMsa;
     }
 
     /**
@@ -171,160 +121,31 @@ public class PCDAutoGenAction extends BuildAction {
         return cAutoGenString;
     }
 
-//    /**
-//      Construct function
-//  
-//      This function mainly initialize some member variable.
-//     
-//      @param moduleName            Parameter of this action class.
-//      @param isEmulatedPCDDriver   Parameter of this action class.
-//    **/
-//    public PCDAutoGenAction(String   moduleName, 
-//                            UUID     moduleGuid, 
-//                            String   packageName,
-//                            UUID     packageGuid,
-//                            String   arch,
-//                            String   version,
-//                            boolean  isBuildUsedLibrary,
-//                            String[] pcdNameArray) {
-//        dbManager       = null;
-//        hAutoGenString  = "";
-//        cAutoGenString  = "";
-//
-//        setModuleName(moduleName);
-//        setModuleGuid(moduleGuid);
-//        setPackageName(packageName);
-//        setPackageGuid(packageGuid);
-//        setPcdNameArray(pcdNameArray);
-//        setArch(arch);
-//        setVersion(version);
-//        setIsBuildUsedLibrary(isBuildUsedLibrary);
-//    }
-
-    
-    /**
-    Construct function
-
-    This function mainly initialize some member variable.
    
-    @param moduleName            Parameter of this action class.
-    @param isEmulatedPCDDriver   Parameter of this action class.
-  **/
-  public PCDAutoGenAction(String   moduleName, 
-                          String   moduleGuidString, 
-                          String   packageName,
-                          String   packageGuidString,
-                          String   arch,
-                          String   version,
-                          boolean  isBuildUsedLibrary,
-                          String[] pcdNameArray) 
-  	throws BuildActionException {
-      dbManager       = null;
-      hAutoGenString  = "";
-      cAutoGenString  = "";
-      try {
-          setModuleName(moduleName);
-          setModuleGuid(translateSchemaStringToUUID(moduleGuidString));
-          setPackageName(packageName);
-          setPackageGuid(translateSchemaStringToUUID(packageGuidString));
-          setPcdNameArray(pcdNameArray);
-          setArch(arch);
-          setVersion(version);
-          setIsBuildUsedLibrary(isBuildUsedLibrary);
-      } catch (EntityException e){
-    	  throw new BuildActionException(e.getMessage());
-      }
-  }
+    /**
+        Construct function
 
-  /**
-  Translate the schema string to UUID instance.
-  
-  In schema, the string of UUID is defined as following two types string:
-   1) GuidArrayType: pattern = 0x[a-fA-F0-9]{1,8},( )*0x[a-fA-F0-9]{1,4},(
-   )*0x[a-fA-F0-9]{1,4}(,( )*\{)?(,?( )*0x[a-fA-F0-9]{1,2}){8}( )*(\})?
-  
-   2) GuidNamingConvention: pattern =
-   [a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}
-  
-  This function will convert string and create uuid instance.
-  
-  @param uuidString    UUID string in XML file
-  
-  @return UUID         UUID instance
-**/
-private UUID translateSchemaStringToUUID(String uuidString) 
-   throws EntityException {
-   String      temp;
-   String[]    splitStringArray;
-   int         index;
-   int         chIndex;
-   int         chLen;
+        This function mainly initialize some member variable.
+   
+        @param moduleId             the identification for module
+        @param arch                 the architecture for module
+        @param isBuildUsedLibary    Is the current module library.
+        @param pcdNameArrayInMsa    the pcd name array got from MSA file.
+    **/
+    public PCDAutoGenAction(ModuleIdentification moduleId, 
+                            String               arch,
+                            boolean              isBuildUsedLibrary,
+                            String[]             pcdNameArrayInMsa) {
+        dbManager       = null;
+        hAutoGenString  = "";
+        cAutoGenString  = "";
 
-   if (uuidString == null) {
-       return null;
-   }
+        setModuleId(moduleId);
+        setArch(arch);
+        setIsBuildUsedLibrary(isBuildUsedLibrary);
+        setPcdNameArrayInMsa(pcdNameArrayInMsa);
+    }
 
-   if (uuidString.length() == 0) {
-       return null;
-   }
-
-   if (uuidString.equals("0") ||
-       uuidString.equalsIgnoreCase("0x0")) {
-       return new UUID(0, 0);
-   }
-
-   uuidString = uuidString.replaceAll("\\{", "");
-   uuidString = uuidString.replaceAll("\\}", "");
-
-   //
-   // If the UUID schema string is GuidArrayType type then need translate 
-   // to GuidNamingConvention type at first.
-   // 
-   if ((uuidString.charAt(0) == '0') && ((uuidString.charAt(1) == 'x') || (uuidString.charAt(1) == 'X'))) {
-       splitStringArray = uuidString.split("," );
-       if (splitStringArray.length != 11) {
-           throw new EntityException ("[FPD file error] Wrong format for UUID string: " + uuidString);
-       }
-
-       //
-       // Remove blank space from these string and remove header string "0x"
-       // 
-       for (index = 0; index < 11; index ++) {
-           splitStringArray[index] = splitStringArray[index].trim();
-           splitStringArray[index] = splitStringArray[index].substring(2, splitStringArray[index].length());
-       }
-
-       //
-       // Add heading '0' to normalize the string length
-       // 
-       for (index = 3; index < 11; index ++) {
-           chLen = splitStringArray[index].length();
-           for (chIndex = 0; chIndex < 2 - chLen; chIndex ++) {
-               splitStringArray[index] = "0" + splitStringArray[index];
-           }
-       }
-
-       //
-       // construct the final GuidNamingConvention string
-       // 
-       temp = String.format("%s-%s-%s-%s%s-%s%s%s%s%s%s",
-                            splitStringArray[0],
-                            splitStringArray[1],
-                            splitStringArray[2],
-                            splitStringArray[3],
-                            splitStringArray[4],
-                            splitStringArray[5],
-                            splitStringArray[6],
-                            splitStringArray[7],
-                            splitStringArray[8],
-                            splitStringArray[9],
-                            splitStringArray[10]);
-       uuidString = temp;
-   }
-
-   return UUID.fromString(uuidString);
-	}
-  
     /**
       check the parameter for action class.
       
@@ -363,8 +184,6 @@ private UUID translateSchemaStringToUUID(String uuidString)
         ActionMessage.debug(this,
                             "PCD memory database contains " + dbManager.getDBSize() + " PCD tokens");
 
-
-
         generateAutogenForModule();
     }
 
@@ -381,32 +200,23 @@ private UUID translateSchemaStringToUUID(String uuidString)
         String[]              guidStringArray = null;
         String                guidStringCName = null;
         String                guidString      = null;
+        String                moduleName      = moduleId.getName();
         UsageInstance         usageInstance   = null;
         boolean               found           = false;
 
         usageInstanceArray = null;
         if (!isBuildUsedLibrary) {
-            usageInstanceArray  = dbManager.getUsageInstanceArrayByModuleName(moduleName,
-                                                                              moduleGuid,
-                                                                              packageName,
-                                                                              packageGuid,
-                                                                              arch,
-                                                                              version);
+            usageInstanceArray  = dbManager.getUsageInstanceArrayByModuleName(moduleId, arch);
             dbManager.UsageInstanceContext = usageInstanceArray;
             dbManager.CurrentModuleName    = moduleName; 
-        } else if ((pcdNameArray != null) && (pcdNameArray.length > 0)) {
+        } else if ((pcdNameArrayInMsa != null) && (pcdNameArrayInMsa.length > 0)) {
             usageContext = dbManager.UsageInstanceContext;
             //
             // For building library package, although all module are library, but PCD entries of 
             // these library should be used to autogen.
             // 
             if (usageContext == null) {
-                usageInstanceArray  = dbManager.getUsageInstanceArrayByModuleName(moduleName,
-                                                                                  moduleGuid,
-                                                                                  packageName,
-                                                                                  packageGuid,
-                                                                                  arch,
-                                                                                  version);
+                usageInstanceArray  = dbManager.getUsageInstanceArrayByModuleName(moduleId, arch);
             } else {
                 usageInstanceArray = new ArrayList<UsageInstance>();
 
@@ -414,10 +224,10 @@ private UUID translateSchemaStringToUUID(String uuidString)
                 // Try to find all PCD defined in library's PCD in all <PcdEntry> in module's 
                 // <ModuleSA> in FPD file.
                 // 
-                for (index = 0; index < pcdNameArray.length; index++) {
+                for (index = 0; index < pcdNameArrayInMsa.length; index++) {
                     found = false;
                     for (index2 = 0; index2 < usageContext.size(); index2 ++) {
-                        if (pcdNameArray[index].equalsIgnoreCase(usageContext.get(index2).parentToken.cName)) {
+                        if (pcdNameArrayInMsa[index].equalsIgnoreCase(usageContext.get(index2).parentToken.cName)) {
                             usageInstanceArray.add(usageContext.get(index2));
                             found = true;
                             break;
@@ -434,7 +244,7 @@ private UUID translateSchemaStringToUUID(String uuidString)
                                                                       "it in the %s's <ModuleSA> in FPD file!",
                                                                       dbManager.CurrentModuleName,
                                                                       moduleName,
-                                                                      pcdNameArray[index],
+                                                                      pcdNameArrayInMsa[index],
                                                                       dbManager.CurrentModuleName
                                                                       ));
                     }
@@ -450,63 +260,55 @@ private UUID translateSchemaStringToUUID(String uuidString)
         // Generate all PCD entry for a module.
         // 
         for(index = 0; index < usageInstanceArray.size(); index ++) {
-            ActionMessage.debug(this,
-                                "Module " + moduleName + "'s PCD [" + Integer.toHexString(index) + 
-                                "]: " + usageInstanceArray.get(index).parentToken.cName);
-            try {
-                usageInstance = usageInstanceArray.get(index);
+            usageInstance = usageInstanceArray.get(index);
+            //
+            // Before generate any PCD information into autogen.h/autogen.c for a module,
+            // generate TokenSpaceGuid array variable firstly. For every dynamicEx type
+            // PCD in this module the token, they are all reference to TokenSpaceGuid 
+            // array.
+            // 
+            if (usageInstanceArray.get(index).modulePcdType == Token.PCD_TYPE.DYNAMIC_EX) {
+                guidStringArray = usageInstance.parentToken.tokenSpaceName.split("-");
+                guidStringCName = "_gPcd_TokenSpaceGuid_" + 
+                                  usageInstance.parentToken.tokenSpaceName.replaceAll("-", "_");
+                guidString      = String.format("{ 0x%s, 0x%s, 0x%s, {0x%s, 0x%s, 0x%s, 0x%s, 0x%s, 0x%s, 0x%s, 0x%s}}",
+                                                guidStringArray[0],
+                                                guidStringArray[1],
+                                                guidStringArray[2],
+                                                (guidStringArray[3].substring(0, 2)),
+                                                (guidStringArray[3].substring(2, 4)),
+                                                (guidStringArray[4].substring(0, 2)),
+                                                (guidStringArray[4].substring(2, 4)),
+                                                (guidStringArray[4].substring(4, 6)),
+                                                (guidStringArray[4].substring(6, 8)),
+                                                (guidStringArray[4].substring(8, 10)),
+                                                (guidStringArray[4].substring(10, 12)));
+                
+                Pattern pattern = Pattern.compile("(" + guidStringCName + ")+?");
+                Matcher matcher = pattern.matcher(cAutoGenString + " ");
                 //
-                // Before generate any PCD information into autogen.h/autogen.c for a module,
-                // generate TokenSpaceGuid array variable firstly. For every dynamicEx type
-                // PCD in this module the token, they are all reference to TokenSpaceGuid 
-                // array.
+                // Find whether this guid array variable has been generated into autogen.c
+                // For different DyanmicEx pcd token who use same token space guid, the token space
+                // guid array should be only generated once.
                 // 
-                if (usageInstanceArray.get(index).modulePcdType == Token.PCD_TYPE.DYNAMIC_EX) {
-                    guidStringArray = usageInstance.parentToken.tokenSpaceName.toString().split("-");
-                    guidStringCName = "_gPcd_TokenSpaceGuid_" + 
-                                      usageInstance.parentToken.tokenSpaceName.toString().replaceAll("-", "_");
-                    guidString      = String.format("{ 0x%s, 0x%s, 0x%s, {0x%s, 0x%s, 0x%s, 0x%s, 0x%s, 0x%s, 0x%s, 0x%s}}",
-                                                    guidStringArray[0],
-                                                    guidStringArray[1],
-                                                    guidStringArray[2],
-                                                    (guidStringArray[3].substring(0, 2)),
-                                                    (guidStringArray[3].substring(2, 4)),
-                                                    (guidStringArray[4].substring(0, 2)),
-                                                    (guidStringArray[4].substring(2, 4)),
-                                                    (guidStringArray[4].substring(4, 6)),
-                                                    (guidStringArray[4].substring(6, 8)),
-                                                    (guidStringArray[4].substring(8, 10)),
-                                                    (guidStringArray[4].substring(10, 12)));
-                    
-                    Pattern pattern = Pattern.compile("(" + guidStringCName + ")+?");
-                    Matcher matcher = pattern.matcher(cAutoGenString + " ");
-                    //
-                    // Find whether this guid array variable has been generated into autogen.c
-                    // For different DyanmicEx pcd token who use same token space guid, the token space
-                    // guid array should be only generated once.
-                    // 
-                    if (!matcher.find()) {
-                        hAutoGenString += String.format("extern EFI_GUID %s;\r\n",
-                                                        guidStringCName);
-                        if (!isBuildUsedLibrary) {
-                            cAutoGenString += String.format("GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID %s = %s;\r\n",
-                                                            guidStringCName,
-                                                            guidString);
-                        } 
-                    }
+                if (!matcher.find()) {
+                    hAutoGenString += String.format("extern EFI_GUID %s;\r\n",
+                                                    guidStringCName);
+                    if (!isBuildUsedLibrary) {
+                        cAutoGenString += String.format("GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID %s = %s;\r\n",
+                                                        guidStringCName,
+                                                        guidString);
+                    } 
                 }
-
-                usageInstance.generateAutoGen(isBuildUsedLibrary);
-                //
-                // For every PCD entry for this module(usage instance), autogen string would
-                // be appand.
-                // 
-                hAutoGenString += usageInstance.getHAutogenStr() + "\r\n";
-                cAutoGenString += usageInstance.getCAutogenStr();
-
-            } catch(EntityException exp) {
-                throw new BuildActionException("[PCD Autogen Error]: " + exp.getMessage());
             }
+
+            usageInstance.generateAutoGen(isBuildUsedLibrary);
+            //
+            // For every PCD entry for this module(usage instance), autogen string would
+            // be appand.
+            // 
+            hAutoGenString += usageInstance.getHAutogenStr() + "\r\n";
+            cAutoGenString += usageInstance.getCAutogenStr();
         }
 
         //
@@ -520,13 +322,6 @@ private UUID translateSchemaStringToUUID(String uuidString)
             hAutoGenString += dbManager.PcdDxeHString;
             cAutoGenString += dbManager.PcdDxeCString;
         }
-
-        ActionMessage.debug(this,
-                            "Module " + moduleName + "'s PCD header file:\r\n" + hAutoGenString + "\r\n"
-                           );
-        ActionMessage.debug(this,
-                             "Module " + moduleName + "'s PCD C file:\r\n" + cAutoGenString + "\r\n"
-                            );
     }
 
     /**
@@ -555,22 +350,5 @@ private UUID translateSchemaStringToUUID(String uuidString)
         } catch(Exception e) {
             e.printStackTrace();
         }
-
-        //
-        // Then execute the PCDAuotoGenAction to get generated Autogen.h and Autogen.c
-        //
-//        PCDAutoGenAction autogenAction = new PCDAutoGenAction("MonoStatusCode",
-//                                                              null,
-//                                                              null,
-//                                                              null,
-//                                                              "IA32",
-//                                                              null,
-//                                                              false,
-//                                                              nameArray);
-//        autogenAction.execute();
-//
-//        System.out.println(autogenAction.OutputH());
-//        System.out.println("WQWQWQWQWQ");
-//        System.out.println(autogenAction.OutputC());
     }
 }
diff --git a/Tools/Source/GenBuild/org/tianocore/build/pcd/entity/DynamicTokenValue.java b/Tools/Source/GenBuild/org/tianocore/build/pcd/entity/DynamicTokenValue.java
index 65c15a5eb5..533bd51920 100644
--- a/Tools/Source/GenBuild/org/tianocore/build/pcd/entity/DynamicTokenValue.java
+++ b/Tools/Source/GenBuild/org/tianocore/build/pcd/entity/DynamicTokenValue.java
@@ -133,26 +133,6 @@ public class DynamicTokenValue {
         return str;
     }
 
-    /**
-       Get UINT16 array which use string to express a number.
-       
-       @return String
-     */
-    public String getStringArrayOfVariableName() {
-        String  strArray;
-        int     index;
-
-        strArray =  "{";
-        for (index = 0; index < variableName.size(); index ++) {
-            strArray += variableName.get(index).toString();
-            if (index != (variableName.size() - 1)) {
-                strArray += ",";
-            }
-        }
-        strArray += "}";
-        return strArray;
-    }
-
     /**
        Set Vpd case data.
        
diff --git a/Tools/Source/GenBuild/org/tianocore/build/pcd/entity/MemoryDatabaseManager.java b/Tools/Source/GenBuild/org/tianocore/build/pcd/entity/MemoryDatabaseManager.java
index 2e29106323..636be3adaf 100644
--- a/Tools/Source/GenBuild/org/tianocore/build/pcd/entity/MemoryDatabaseManager.java
+++ b/Tools/Source/GenBuild/org/tianocore/build/pcd/entity/MemoryDatabaseManager.java
@@ -21,6 +21,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.UUID;
 
+import org.tianocore.build.id.ModuleIdentification;
 import org.tianocore.build.pcd.exception.EntityException;
 
 /** Database hold all PCD information comes from SPD, MSA, FPD file in memory.
@@ -38,14 +39,20 @@ public class MemoryDatabaseManager {
     /// context of building libary.
     /// 
     public static List<UsageInstance> UsageInstanceContext = null;
+
     ///
-    /// 
+    /// Current module name, if now is buiding library, this value indicate this library
+    /// is for building what module.
     /// 
     public static String CurrentModuleName                 = null;
-    public static String PcdPeimHString       = "";
-    public static String PcdPeimCString       = "";
-    public static String PcdDxeHString        = "";
-    public static String PcdDxeCString        = "";
+
+    ///
+    /// String for PCD PEIM and DXE autogen file
+    /// 
+    public static String PcdPeimHString                    = "";
+    public static String PcdPeimCString                    = "";
+    public static String PcdDxeHString                     = "";
+    public static String PcdDxeCString                     = "";
 
     /**
       Constructure function
@@ -151,7 +158,7 @@ public class MemoryDatabaseManager {
           The output array is sorted based on descending order of the size of alignment for each feilds.
 
       @return the token record array contained all PCD token referenced in PEI phase.
-     * @throws EntityException 
+      @throws EntityException
     **/
     public void getTwoPhaseDynamicRecordArray(ArrayList<Token> pei, ArrayList<Token> dxe) 
         throws EntityException {
@@ -204,7 +211,7 @@ public class MemoryDatabaseManager {
                         // We only support Dynamice(EX) type for PEI and DXE phase.
                         // If it is not referenced in either PEI or DXE, throw exception now.
                         //
-                        throw new EntityException("Dynamic(EX) PCD Entries are referenced in module that is not in PEI phase nor in DXE phase.");
+                        throw new EntityException("[PCD tool Internal Error] Dynamic(EX) PCD Entries are referenced in module that is not in PEI phase nor in DXE phase.");
                     }
                 }
             }
@@ -217,23 +224,15 @@ public class MemoryDatabaseManager {
       Get all PCD record for a module according to module's name, module's GUID,
       package name, package GUID, arch, version information.
      
-      @param moduleName  the name of module.
+      @param moduleId  the id of module.
+      @param arch      the architecture
       
       @return  all usage instance for this module in memory database.
     **/
-    public List<UsageInstance> getUsageInstanceArrayByModuleName(String moduleName,
-                                                                 UUID   moduleGuid,
-                                                                 String packageName,
-                                                                 UUID   packageGuid,
-                                                                 String arch,
-                                                                 String version) {
+    public List<UsageInstance> getUsageInstanceArrayByModuleName(ModuleIdentification  moduleId,
+                                                                 String                arch) {
 
-        String primaryKey = UsageInstance.getPrimaryKey(moduleName, 
-                                                        moduleGuid,
-                                                        packageName,
-                                                        packageGuid,
-                                                        arch,
-                                                        version);
+        String primaryKey = UsageInstance.getPrimaryKey(moduleId, arch);
 
         return getUsageInstanceArrayByKeyString(primaryKey);
     }
diff --git a/Tools/Source/GenBuild/org/tianocore/build/pcd/entity/Token.java b/Tools/Source/GenBuild/org/tianocore/build/pcd/entity/Token.java
index 8a492256c4..20b4f4e01a 100644
--- a/Tools/Source/GenBuild/org/tianocore/build/pcd/entity/Token.java
+++ b/Tools/Source/GenBuild/org/tianocore/build/pcd/entity/Token.java
@@ -22,6 +22,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.UUID;
 
+import org.tianocore.build.id.ModuleIdentification;
 import org.tianocore.build.pcd.exception.EntityException;
 
 /** This class is to descript a PCD token object. The information of a token mainly 
@@ -60,19 +61,19 @@ public class Token {
     /// assignedtokenSpaceName as follows.
     /// tokenSpaceName is defined in MSA, SPD, FPD, can be regarded as primary key with cName.
     ///
-    public UUID             tokenSpaceName;
+    public String           tokenSpaceName;
 
     ///
     /// tokenNumber is allocated by platform. tokenNumber indicate an index for this token in
     /// platform token space. For Dynamic, dynamicEx type, this number will be re-adjust by
     /// PCD run-time database autogen tools.
     ///
-    public long              tokenNumber;
+    public long             tokenNumber;
 
     ///
     /// This token number is retrieved from FPD file for DynamicEx type. 
     /// 
-    public long              dynamicExTokenNumber;
+    public long             dynamicExTokenNumber;
 
     ///
     /// All supported PCD type, this value can be retrieved from SPD
@@ -110,11 +111,17 @@ public class Token {
     ///
     public Map<String, UsageInstance>  consumers;
 
-    public Token(String cName, UUID tokenSpaceName) {
+    /**
+       Constructure function for Token class
+       
+       @param cName             The name of token
+       @param tokenSpaceName    The name of token space, it is a guid string
+    **/
+    public Token(String cName, String tokenSpaceName) {
         UUID    nullUUID = new UUID(0, 0);
 
         this.cName                  = cName;
-        this.tokenSpaceName         = (tokenSpaceName == null) ? nullUUID : tokenSpaceName;
+        this.tokenSpaceName         = tokenSpaceName;
         this.tokenNumber            = 0;
         this.datumType              = DATUM_TYPE.UNKNOWN;
         this.datumSize              = -1;
@@ -133,24 +140,23 @@ public class Token {
       @param pcdType    new PCD type found in FPD file for this token.
     **/
     public void updateSupportPcdType(PCD_TYPE pcdType) {
-        int     index = 0;
-        boolean found = false;
-        for (index = 0; index < this.supportedPcdType.size(); index ++) {
-            if (this.supportedPcdType.get(index) == pcdType) {
-                found = true;
-                break;
+        for (int index = 0; index < this.supportedPcdType.size(); index ++) {
+            if (supportedPcdType.get(index) == pcdType) {
+                return;
             }
         }
-        if (!found) {
-            this.supportedPcdType.add(pcdType);
-        }
+
+        //
+        // If not found, add the pcd type to member variable supportedPcdType
+        // 
+        supportedPcdType.add(pcdType);
     }
 
     /**
        Judge whether pcdType is belong to dynamic type. Dynamic type includes
        DYNAMIC and DYNAMIC_EX.
        
-       @param pcdType
+       @param pcdType       the judged pcd type
        
        @return boolean
      */
@@ -164,7 +170,6 @@ public class Token {
     }
 
     public boolean isDynamicEx() {
-        
         for (int i = 0; i < supportedPcdType.size(); i++) {
             if (supportedPcdType.get(i) == PCD_TYPE.DYNAMIC_EX) {
                 return true;
@@ -178,16 +183,13 @@ public class Token {
       Use "TokencName + "-" + SpaceTokenName" as primary key when adding token into database
       
       @param   cName                     Token name.
-      @param   tokenSpaceName            The token space guid defined in MSA or SPD
-      @param   platformtokenSpaceName    The token space guid for current platform token space,
+      @param   tokenSpaceName            The token space guid string defined in MSA or SPD
       
-      @return  primary key for this token in token database.
+      @retval  primary key for this token in token database.
     **/
-    public static String getPrimaryKeyString(String cName, UUID tokenSpaceName) {
-        UUID  nullUUID = new UUID(0, 0);
-
+    public static String getPrimaryKeyString(String cName, String tokenSpaceName) {
         if (tokenSpaceName == null) {
-            return cName + "_" + nullUUID.toString().replace('-', '_');
+            return cName + "_nullTokenSpaceGuid";
         } else {
             return cName + "_" + tokenSpaceName.toString().replace('-', '_');
         }
@@ -196,7 +198,7 @@ public class Token {
     /**
        If skudata list contains more than one data, then Sku mechanism is enable.
        
-       @return boolean
+       @retval boolean  if the number of sku data exceed to 1
      */
     public boolean isSkuEnable() {
         if (this.skuData.size() > 1) {
@@ -204,7 +206,12 @@ public class Token {
         }
         return false;
     }
-    
+
+    /**
+       If Hii type for value of token
+       
+       @return boolean
+    **/
     public boolean isHiiEnable() {
         if (getDefaultSku().type == DynamicTokenValue.VALUE_TYPE.HII_TYPE) {
             return true;
@@ -212,6 +219,11 @@ public class Token {
         return false;
     }
 
+    /**
+       If Vpd type for value of token
+       
+       @return boolean
+    **/
     public boolean isVpdEnable() {
         if (getDefaultSku().type == DynamicTokenValue.VALUE_TYPE.VPD_TYPE) {
             return true;
@@ -268,52 +280,38 @@ public class Token {
       @retval TRUE  - Success to add usage instance.
       @retval FALSE - Fail to add usage instance
     **/
-    public boolean addUsageInstance(UsageInstance usageInstance) 
-        throws EntityException {
+    public boolean addUsageInstance(UsageInstance usageInstance) throws EntityException {
         String exceptionStr;
 
-        if (isUsageInstanceExist(usageInstance.moduleName,
-                                 usageInstance.moduleGUID,
-                                 usageInstance.packageName,
-                                 usageInstance.packageGUID,
-                                 usageInstance.arch,
-                                 usageInstance.version)) {
-            exceptionStr = String.format("PCD %s for module %s has already exist in database, Please check all PCD build entries "+
-                                         "in modules %s in <ModuleSA> to make sure no duplicated definitions!",
+        if (isUsageInstanceExist(usageInstance.moduleId, usageInstance.arch)) {
+            exceptionStr = String.format("[PCD Collection Tool Exception] PCD %s for module %s has already exist in database, Please check all PCD build entries "+
+                                         "in modules %s in <ModuleSA> to make sure no duplicated definitions in FPD file!",
                                          usageInstance.parentToken.cName,
-                                         usageInstance.moduleName,
-                                         usageInstance.moduleName);
+                                         usageInstance.moduleId.getName(),
+                                         usageInstance.moduleId.getName());
             throw new EntityException(exceptionStr);
         }
 
+        //
+        // Put usage instance into usage instance database of this PCD token.
+        // 
         consumers.put(usageInstance.getPrimaryKey(), usageInstance);
+
         return true;
     }
 
     /**
        Judge whether exist an usage instance for this token
        
-       @param moduleName    the name of module
-       @param moduleGuid    the GUID name of modules
-       @param packageName   the name of package contains this module
-       @param packageGuid   the GUID name of package contains this module
+       @param moduleId      The module identification for usage instance
        @param arch          the architecture string
-       @param version       the version string
        
        @return boolean      whether exist an usage instance for this token.
      */
-    public boolean isUsageInstanceExist(String moduleName,
-                                        UUID   moduleGuid,
-                                        String packageName,
-                                        UUID   packageGuid,
-                                        String arch,
-                                        String version) {
-        String keyStr = UsageInstance.getPrimaryKey(moduleName, 
-                                                    moduleGuid, 
-                                                    packageName, 
-                                                    packageGuid, 
-                                                    arch, 
-                                                    version);
+    public boolean isUsageInstanceExist(ModuleIdentification moduleId,
+                                        String               arch) {
+        String keyStr = UsageInstance.getPrimaryKey(moduleId, arch);
+
         return (consumers.get(keyStr) != null);
     }
 
@@ -542,27 +540,14 @@ public class Token {
     }
 
     /**
-      UUID defined in Schems is object, this function is to tranlate this object 
-      to UUID data.
-      
-      @param uuidObj The object comes from schema.
-      
-      @return The traslated UUID instance.
+       Get the sku data who id is 0.
+       
+       @retval DynamicTokenValue    the value of this dyanmic token.
     **/
-    public static UUID getGUIDFromSchemaObject(Object uuidObj) {
-        UUID uuid;
-        if (uuidObj.toString().equalsIgnoreCase("0")) {
-            uuid = new UUID(0,0);
-        } else {
-            uuid = UUID.fromString(uuidObj.toString());
-        }
-
-        return uuid;
-    }
-
     public DynamicTokenValue getDefaultSku() {
         DynamicTokenValue dynamicData;
         int               index;
+
         for (index = 0; index < this.skuData.size(); index ++) {
             if (skuData.get(index).id == 0) {
                 return skuData.get(index).value;
@@ -571,11 +556,22 @@ public class Token {
 
         return null;
     }
-    
+
+    /**
+       Get the number of Sku data for this token
+       
+       @retval int the number of sku data
+    **/
     public int getSkuIdCount () {
         return this.skuData.size();
     }
 
+    /**
+       Get the size of PCD value, this PCD is POINTER type.
+       
+       @param str   the string of the value
+       @param al    
+    **/
     private void getCurrentSizeFromDefaultValue (String str, ArrayList<Integer> al) {
         if (isValidNullValue(str)) {
             al.add(new Integer(0));
@@ -616,10 +612,11 @@ public class Token {
             }
         }
     }
-    //
-    // This method can be used to get the MAX and current size
-    // for pointer type dynamic(ex) PCD entry
-    //
+
+    /**
+       This method can be used to get the MAX and current size
+       for pointer type dynamic(ex) PCD entry
+    **/ 
     public ArrayList<Integer> getPointerTypeSize () {
         ArrayList<Integer> al = new ArrayList<Integer>();
         
@@ -695,6 +692,13 @@ public class Token {
         return false;
     }
 
+    /**
+       Judge the value is NULL value. NULL value means the value is uninitialized value
+       
+       @param judgedValue
+       
+       @return boolean
+     */
     public boolean isValidNullValue(String judgedValue) {
         String      subStr;
         BigInteger  bigIntValue;
@@ -756,7 +760,12 @@ public class Token {
         }
         return false;
     }
-    
+
+    /**
+       Is the string value in Unicode
+       
+       @return boolean
+    **/
     public boolean isHiiDefaultValueUnicodeStringType() {
         DynamicTokenValue dynamicData = getDefaultSku();
         
@@ -766,7 +775,12 @@ public class Token {
         return dynamicData.hiiDefaultValue.startsWith("L\"")
                 && dynamicData.hiiDefaultValue.endsWith("\"");
     }
-    
+
+    /**
+       Is the string value in ANSCI
+       
+       @return boolean
+    **/
     public boolean isHiiDefaultValueASCIIStringType() {
         DynamicTokenValue dynamicData = getDefaultSku();
     
diff --git a/Tools/Source/GenBuild/org/tianocore/build/pcd/entity/UsageInstance.java b/Tools/Source/GenBuild/org/tianocore/build/pcd/entity/UsageInstance.java
index 20a58ba5f5..2abcea8bdc 100644
--- a/Tools/Source/GenBuild/org/tianocore/build/pcd/entity/UsageInstance.java
+++ b/Tools/Source/GenBuild/org/tianocore/build/pcd/entity/UsageInstance.java
@@ -19,8 +19,10 @@ package org.tianocore.build.pcd.entity;
 
 
 import java.util.UUID;
+
 import org.tianocore.ModuleTypeDef;
 import org.tianocore.build.autogen.CommonDefinition;
+import org.tianocore.build.id.ModuleIdentification;
 import org.tianocore.build.pcd.exception.EntityException;
 
 /**
@@ -32,105 +34,65 @@ public class UsageInstance {
     ///
     /// This parent that this usage instance belongs to.
     ///
-    public Token            parentToken;
+    public Token                parentToken;
 
     ///
-    /// The name of the module who contains this PCD.
-    ///
-    public String           moduleName;
-
-    ///
-    /// The GUID of the module who contains this PCD. 
+    /// ModuleIdentification for Usage Instance
     /// 
-    public UUID             moduleGUID;
+    public ModuleIdentification moduleId;
 
     ///
-    /// The name of the package whose module contains this PCD.
-    ///
-    public String           packageName;
-
-    ///
-    /// The GUID of the package whose module contains this PCD.
+    /// Arch also is a key for a UsageInstance
     /// 
-    public UUID             packageGUID;
+    public String               arch;
 
     ///
     /// The PCD type defined for module 
     /// 
-    public Token.PCD_TYPE   modulePcdType;
-
-    ///
-    /// The arch string of module contains this PCD
-    ///
-    public String           arch;
-
-    ///
-    /// The version of module contains this PCD
-    /// 
-    public String           version;
-
-    ///
-    /// The module type for this usage instance.
-    ///
-    public int              moduleType;
+    public Token.PCD_TYPE       modulePcdType;
 
     ///
     /// The value of the PCD in this usage instance. 
     /// 
-    public String           datum;
+    public String               datum;
 
     ///
     /// The maxDatumSize could be different for same PCD in different module
     /// But this case is allow for FeatureFlag, FixedAtBuild, PatchableInModule
     /// type.
     /// 
-    public int              maxDatumSize;
+    public int                  maxDatumSize;
 
     ///
     /// Autogen string for header file.
     ///
-    public String           hAutogenStr;
+    public String               hAutogenStr;
 
     ///
     /// Auotgen string for C code file.
     /// 
-    public String           cAutogenStr;
+    public String               cAutogenStr;
 
     /**
-       Constructure function
+       Constructure function for UsageInstance
        
-       @param parentToken         Member variable.
-       @param moduleName          Member variable.
-       @param moduleGUID          Member variable.
-       @param packageName         Member variable.
-       @param packageGUID         Member variable.
-       @param moduleType          Member variable.
-       @param modulePcdType       Member variable.
-       @param arch                Member variable.
-       @param version             Member variable.
-       @param value               Member variable.
-       @param maxDatumSize        Member variable.
-     */
-    public UsageInstance (Token             parentToken,
-                          String            moduleName,
-                          UUID              moduleGUID,
-                          String            packageName,
-                          UUID              packageGUID,
-                          int               moduleType,
-                          Token.PCD_TYPE    modulePcdType,
-                          String            arch,
-                          String            version,
-                          String            value,
-                          int               maxDatumSize) {
+       @param parentToken         The token instance for this usgaInstance
+       @param id                  The identification for usage instance
+       @param modulePcdType       The PCD type for this usage instance
+       @param value               The value of this PCD in this usage instance
+       @param maxDatumSize        The max datum size of this PCD in this usage
+                                  instance.
+    **/
+    public UsageInstance(Token                 parentToken,
+                         ModuleIdentification  moduleId,
+                         Token.PCD_TYPE        modulePcdType,
+                         String                arch,
+                         String                value,
+                         int                   maxDatumSize) {
         this.parentToken      = parentToken;
-        this.moduleName       = moduleName;
-        this.moduleGUID       = moduleGUID;
-        this.packageName      = packageName;
-        this.packageGUID      = packageGUID;
-        this.moduleType       = moduleType;
+        this.moduleId         = moduleId;
         this.modulePcdType    = modulePcdType;
         this.arch             = arch;
-        this.version          = version;
         this.datum            = value;
         this.maxDatumSize     = maxDatumSize;
     }
@@ -138,30 +100,30 @@ public class UsageInstance {
     /**
        Get the primary key for usage instance array for every token.
        
-       @param moduleName      the name of module
-       @param moduleGUID      the GUID name of module
-       @param packageName     the name of package who contains this module
-       @param packageGUID     the GUID name of package
-       @param arch            the archtecture string
-       @param version         the version of this module
+       @param   moduleId      The module Identification for generating primary key
+       @param   arch          Arch string
        
-       @return String         primary key
-     */
-    public static String getPrimaryKey(String moduleName,  
-                                       UUID   moduleGUID,  
-                                       String packageName,  
-                                       UUID   packageGUID,
-                                       String arch,
-                                       String version) {
+       @retval  String        The primary key for this usage instance
+    **/
+    public static String getPrimaryKey(ModuleIdentification moduleId,
+                                       String               arch) {
+        String moduleName   = moduleId.getName();
+        String moduleGuid   = moduleId.getGuid();
+        String packageName  = moduleId.getPackage().getName();
+        String packageGuid  = moduleId.getPackage().getGuid();
+        String version      = moduleId.getVersion();
+
         //
         // Because currently transition schema not require write moduleGuid, package Name, Packge GUID in
         // <ModuleSA> section, So currently no expect all paramter must be valid.
-        return(moduleName                                                              + "_" +
-               ((moduleGUID  != null) ? moduleGUID.toString() : "NullModuleGuid")      + "_" +
-               ((packageName != null) ? packageName : "NullPackageName")               + "_" +
-               ((packageGUID != null) ? packageGUID.toString() : "NullPackageGuid")    + "_" +
-               ((arch        != null) ? arch : "NullArch")                             + "_" +
-               ((version     != null) ? version : "NullVersion"));
+        // BUGBUG: Because currently we can not get version from MSA, So ignore verison.
+        // 
+        return(moduleName                                                                + "_" +
+               ((moduleGuid  != null) ? moduleGuid.toLowerCase()    : "NullModuleGuid")  + "_" +
+               ((packageName != null) ? packageName                 : "NullPackageName") + "_" +
+               ((packageGuid != null) ? packageGuid.toLowerCase()   : "NullPackageGuid") + "_" +
+               ((arch        != null) ? arch                        : "NullArch")        + "_" +
+               "NullVersion");
     }
 
     /**
@@ -170,48 +132,50 @@ public class UsageInstance {
        @return String primary key string
     **/
     public String getPrimaryKey() {
-        return UsageInstance.getPrimaryKey(moduleName, moduleGUID, packageName, packageGUID, arch, version);
+        return UsageInstance.getPrimaryKey(moduleId, arch);
     }
 
     /**
        Judget whether current module is PEI driver
        
-       @return boolean
-     */
+       @return boolean whether current module is PEI driver
+    **/
     public boolean isPeiPhaseComponent() {
+        int moduleType = CommonDefinition.getModuleType(moduleId.getModuleType());
+
         if ((moduleType == CommonDefinition.ModuleTypePeiCore) ||
             (moduleType == CommonDefinition.ModuleTypePeim)) {
             return true;
         }
         return false;
     }
-  
-  public boolean isDxePhaseComponent() {
-      //
-      // BugBug: May need confirmation on which type of module can
-      //         make use of Dynamic(EX) PCD entry.
-      //
-      if ((moduleType == CommonDefinition.ModuleTypeDxeDriver) ||
-          (moduleType == CommonDefinition.ModuleTypeDxeRuntimeDriver) ||
-          (moduleType == CommonDefinition.ModuleTypeDxeSalDriver) ||
-          (moduleType == CommonDefinition.ModuleTypeDxeSmmDriver) ||
-          (moduleType == CommonDefinition.ModuleTypeUefiDriver) ||
-          (moduleType == CommonDefinition.ModuleTypeUefiApplication)
-          ) {
-          return true;
-      }
-      return false;
-  }
+
+    /**
+       Judge whether current module is DXE driver.
+       
+       @return boolean whether current module is DXE driver
+    **/
+    public boolean isDxePhaseComponent() {
+        int moduleType = CommonDefinition.getModuleType(moduleId.getModuleType());
+
+        if ((moduleType == CommonDefinition.ModuleTypeDxeDriver)        ||
+            (moduleType == CommonDefinition.ModuleTypeDxeRuntimeDriver) ||
+            (moduleType == CommonDefinition.ModuleTypeDxeSalDriver)     ||
+            (moduleType == CommonDefinition.ModuleTypeDxeSmmDriver)     ||
+            (moduleType == CommonDefinition.ModuleTypeUefiDriver)       ||
+            (moduleType == CommonDefinition.ModuleTypeUefiApplication)
+            ) {
+            return true;
+        }
+        return false;
+    }
 
     /**
        Generate autogen string for header file and C code file.
        
-       @throws EntityException Fail to generate.
-       
        @param isBuildUsedLibrary  whether the autogen is for library.
-     */
-    public void generateAutoGen(boolean isBuildUsedLibrary) 
-        throws EntityException {
+    **/
+    public void generateAutoGen(boolean isBuildUsedLibrary) {
         String  guidStringCName     = null;
         boolean isByteArray         = false;
         String  printDatum          = null;
@@ -221,20 +185,31 @@ public class UsageInstance {
         cAutogenStr = "";
 
         if (this.modulePcdType == Token.PCD_TYPE.DYNAMIC_EX) {
+            //
+            // For DYNAMIC_EX type PCD, use original token number in SPD or FPD to generate autogen
+            // 
             tokenNumberString =  Long.toString(parentToken.dynamicExTokenNumber, 16);
         } else {
+            //
+            // For Others type PCD, use autogenerated token number to generate autogen
+            // 
             tokenNumberString = Long.toString(parentToken.tokenNumber, 16);
         }
 
-        hAutogenStr += String.format("#define _PCD_TOKEN_%s  0x%s\r\n", 
-                                     parentToken.cName, tokenNumberString);
-        
+        hAutogenStr += String.format("#define _PCD_TOKEN_%s  0x%s\r\n", parentToken.cName, tokenNumberString);
+
+        //
+        // Judge the value of this PCD is byte array type
+        // 
         if (!isBuildUsedLibrary && !parentToken.isDynamicPCD) {
             if (datum.trim().charAt(0) == '{') {
                 isByteArray = true;
             }
         }
 
+        //
+        // "ULL" should be added to value's tail for UINT64 value
+        // 
         if (parentToken.datumType == Token.DATUM_TYPE.UINT64) {
             printDatum = this.datum + "ULL";
         } else {