]> git.proxmox.com Git - mirror_edk2.git/blobdiff - BaseTools/Source/Python/AutoGen/AutoGen.py
BaseTool: Add cache for the result of SkipAutogen.
[mirror_edk2.git] / BaseTools / Source / Python / AutoGen / AutoGen.py
index 2811952fe1d36bf814f0782ef9436dedfb425b9c..d100648606f7cbea022007373c4cabbf52e0d737 100644 (file)
@@ -2,6 +2,8 @@
 # Generate AutoGen.h, AutoGen.c and *.depex files\r
 #\r
 # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>\r
+# Copyright (c) 2018, Hewlett Packard Enterprise Development, L.P.<BR>\r
+#\r
 # This program and the accompanying materials\r
 # are licensed and made available under the terms and conditions of the BSD License\r
 # which accompanies this distribution.  The full text of the license may be found at\r
@@ -13,6 +15,7 @@
 \r
 ## Import Modules\r
 #\r
+from __future__ import print_function\r
 import Common.LongFilePathOs as os\r
 import re\r
 import os.path as path\r
@@ -22,7 +25,7 @@ import uuid
 import GenC\r
 import GenMake\r
 import GenDepex\r
-from StringIO import StringIO\r
+from io import BytesIO\r
 \r
 from StrGather import *\r
 from BuildEngine import BuildRule\r
@@ -31,7 +34,7 @@ from Common.LongFilePathSupport import CopyLongFilePath
 from Common.BuildToolError import *\r
 from Common.DataType import *\r
 from Common.Misc import *\r
-from Common.String import *\r
+from Common.StringUtils import *\r
 import Common.GlobalData as GlobalData\r
 from GenFds.FdfParser import *\r
 from CommonDataClass.CommonClass import SkuInfoClass\r
@@ -40,13 +43,15 @@ from GenPatchPcdTable.GenPatchPcdTable import parsePcdInfoFromMapFile
 import Common.VpdInfoFile as VpdInfoFile\r
 from GenPcdDb import CreatePcdDatabaseCode\r
 from Workspace.MetaFileCommentParser import UsageList\r
+from Workspace.WorkspaceCommon import GetModuleLibInstances\r
 from Common.MultipleWorkspace import MultipleWorkspace as mws\r
 import InfSectionParser\r
 import datetime\r
 import hashlib\r
-from GenVar import VariableMgr,var_info\r
+from GenVar import VariableMgr, var_info\r
 from collections import OrderedDict\r
 from collections import defaultdict\r
+from Workspace.WorkspaceCommon import OrderedListDict\r
 \r
 ## Regular expression for splitting Dependency Expression string into tokens\r
 gDepexTokenPattern = re.compile("(\(|\)|\w+| \S+\.inf)")\r
@@ -236,7 +241,7 @@ class WorkspaceAutoGen(AutoGen):
             super(WorkspaceAutoGen, self).__init__(Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)\r
             self._InitWorker(Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)\r
             self._Init = True\r
-    \r
+\r
     ## Initialize WorkspaceAutoGen\r
     #\r
     #   @param  WorkspaceDir            Root directory of workspace\r
@@ -305,7 +310,7 @@ class WorkspaceAutoGen(AutoGen):
                             ExtraData="Build target [%s] is not supported by the platform. [Valid target: %s]"\r
                                       % (self.BuildTarget, " ".join(self.Platform.BuildTargets)))\r
 \r
-        \r
+\r
         # parse FDF file to get PCDs in it, if any\r
         if not self.FdfFile:\r
             self.FdfFile = self.Platform.FlashDefinition\r
@@ -419,15 +424,33 @@ class WorkspaceAutoGen(AutoGen):
                         if BuildData.Pcds[key].Pending:\r
                             if key in Platform.Pcds:\r
                                 PcdInPlatform = Platform.Pcds[key]\r
-                                if PcdInPlatform.Type not in [None, '']:\r
+                                if PcdInPlatform.Type:\r
                                     BuildData.Pcds[key].Type = PcdInPlatform.Type\r
+                                    BuildData.Pcds[key].Pending = False\r
 \r
                             if BuildData.MetaFile in Platform.Modules:\r
                                 PlatformModule = Platform.Modules[str(BuildData.MetaFile)]\r
                                 if key in PlatformModule.Pcds:\r
                                     PcdInPlatform = PlatformModule.Pcds[key]\r
-                                    if PcdInPlatform.Type not in [None, '']:\r
+                                    if PcdInPlatform.Type:\r
                                         BuildData.Pcds[key].Type = PcdInPlatform.Type\r
+                                        BuildData.Pcds[key].Pending = False\r
+                            else:\r
+                                #Pcd used in Library, Pcd Type from reference module if Pcd Type is Pending\r
+                                if BuildData.Pcds[key].Pending:\r
+                                    MGen = ModuleAutoGen(self, BuildData.MetaFile, Target, Toolchain, Arch, self.MetaFile)\r
+                                    if MGen and MGen.IsLibrary:\r
+                                        if MGen in PGen.LibraryAutoGenList:\r
+                                            ReferenceModules = MGen._ReferenceModules\r
+                                            for ReferenceModule in ReferenceModules:\r
+                                                if ReferenceModule.MetaFile in Platform.Modules:\r
+                                                    RefPlatformModule = Platform.Modules[str(ReferenceModule.MetaFile)]\r
+                                                    if key in RefPlatformModule.Pcds:\r
+                                                        PcdInReferenceModule = RefPlatformModule.Pcds[key]\r
+                                                        if PcdInReferenceModule.Type:\r
+                                                            BuildData.Pcds[key].Type = PcdInReferenceModule.Type\r
+                                                            BuildData.Pcds[key].Pending = False\r
+                                                            break\r
 \r
                         if TAB_PCDS_DYNAMIC_EX in BuildData.Pcds[key].Type:\r
                             if BuildData.IsBinaryModule:\r
@@ -460,7 +483,7 @@ class WorkspaceAutoGen(AutoGen):
                             'build',\r
                             FORMAT_INVALID,\r
                             "Building modules from source INFs, following PCD use %s and %s access method. It must be corrected to use only one access method." % (i, j),\r
-                            ExtraData="%s" % '\n\t'.join([str(P[1]+'.'+P[0]) for P in Intersections])\r
+                            ExtraData='\n\t'.join(str(P[1]+'.'+P[0]) for P in Intersections)\r
                             )\r
 \r
             #\r
@@ -507,8 +530,8 @@ class WorkspaceAutoGen(AutoGen):
                         if (BuildData.Pcds[key].TokenCName, BuildData.Pcds[key].TokenSpaceGuidCName) == SinglePcd:\r
                             for item in GlobalData.MixedPcd[SinglePcd]:\r
                                 Pcd_Type = item[0].split('_')[-1]\r
-                                if (Pcd_Type == BuildData.Pcds[key].Type) or (Pcd_Type == TAB_PCDS_DYNAMIC_EX and BuildData.Pcds[key].Type in GenC.gDynamicExPcd) or \\r
-                                   (Pcd_Type == TAB_PCDS_DYNAMIC and BuildData.Pcds[key].Type in GenC.gDynamicPcd):\r
+                                if (Pcd_Type == BuildData.Pcds[key].Type) or (Pcd_Type == TAB_PCDS_DYNAMIC_EX and BuildData.Pcds[key].Type in PCD_DYNAMIC_EX_TYPE_SET) or \\r
+                                   (Pcd_Type == TAB_PCDS_DYNAMIC and BuildData.Pcds[key].Type in PCD_DYNAMIC_TYPE_SET):\r
                                     Value = BuildData.Pcds[key]\r
                                     Value.TokenCName = BuildData.Pcds[key].TokenCName + '_' + Pcd_Type\r
                                     if len(key) == 2:\r
@@ -666,10 +689,13 @@ class WorkspaceAutoGen(AutoGen):
             os.makedirs(self.BuildDir)\r
         with open(os.path.join(self.BuildDir, 'AutoGen'), 'w+') as file:\r
             for f in AllWorkSpaceMetaFiles:\r
-                print >> file, f\r
+                print(f, file=file)\r
         return True\r
 \r
     def _GenPkgLevelHash(self, Pkg):\r
+        if Pkg.PackageName in GlobalData.gPackageHash[Pkg.Arch]:\r
+            return\r
+\r
         PkgDir = os.path.join(self.BuildDir, Pkg.Arch, Pkg.PackageName)\r
         CreateDirectory(PkgDir)\r
         HashFile = os.path.join(PkgDir, Pkg.PackageName + '.hash')\r
@@ -681,17 +707,16 @@ class WorkspaceAutoGen(AutoGen):
         m.update(Content)\r
         # Get include files hash value\r
         if Pkg.Includes:\r
-            for inc in Pkg.Includes:\r
+            for inc in sorted(Pkg.Includes, key=lambda x: str(x)):\r
                 for Root, Dirs, Files in os.walk(str(inc)):\r
-                    for File in Files:\r
+                    for File in sorted(Files):\r
                         File_Path = os.path.join(Root, File)\r
                         f = open(File_Path, 'r')\r
                         Content = f.read()\r
                         f.close()\r
                         m.update(Content)\r
         SaveFileOnChange(HashFile, m.hexdigest(), True)\r
-        if Pkg.PackageName not in GlobalData.gPackageHash[Pkg.Arch]:\r
-            GlobalData.gPackageHash[Pkg.Arch][Pkg.PackageName] = m.hexdigest()\r
+        GlobalData.gPackageHash[Pkg.Arch][Pkg.PackageName] = m.hexdigest()\r
 \r
     def _GetMetaFiles(self, Target, Toolchain, Arch):\r
         AllWorkSpaceMetaFiles = set()\r
@@ -700,10 +725,8 @@ class WorkspaceAutoGen(AutoGen):
         #\r
         if self.FdfFile:\r
             AllWorkSpaceMetaFiles.add (self.FdfFile.Path)\r
-            if self.FdfFile:\r
-                FdfFiles = GlobalData.gFdfParser.GetAllIncludedFile()\r
-                for f in FdfFiles:\r
-                    AllWorkSpaceMetaFiles.add (f.FileName)\r
+            for f in GlobalData.gFdfParser.GetAllIncludedFile():\r
+                AllWorkSpaceMetaFiles.add (f.FileName)\r
         #\r
         # add dsc\r
         #\r
@@ -724,26 +747,23 @@ class WorkspaceAutoGen(AutoGen):
         AllWorkSpaceMetaFiles.add(os.path.join(self.BuildDir, 'PcdTokenNumber'))\r
 \r
         for Arch in self.ArchList:\r
-            Platform = self.BuildDatabase[self.MetaFile, Arch, Target, Toolchain]\r
-            PGen = PlatformAutoGen(self, self.MetaFile, Target, Toolchain, Arch)\r
-\r
             #\r
             # add dec\r
             #\r
-            for Package in PGen.PackageList:\r
+            for Package in PlatformAutoGen(self, self.MetaFile, Target, Toolchain, Arch).PackageList:\r
                 AllWorkSpaceMetaFiles.add(Package.MetaFile.Path)\r
 \r
             #\r
             # add included dsc\r
             #\r
-            for filePath in Platform._RawData.IncludedFiles:\r
+            for filePath in self.BuildDatabase[self.MetaFile, Arch, Target, Toolchain]._RawData.IncludedFiles:\r
                 AllWorkSpaceMetaFiles.add(filePath.Path)\r
 \r
         return AllWorkSpaceMetaFiles\r
 \r
     ## _CheckDuplicateInFV() method\r
     #\r
-    # Check whether there is duplicate modules/files exist in FV section. \r
+    # Check whether there is duplicate modules/files exist in FV section.\r
     # The check base on the file GUID;\r
     #\r
     def _CheckDuplicateInFV(self, Fdf):\r
@@ -774,7 +794,7 @@ class WorkspaceAutoGen(AutoGen):
                                                                                                                                    Module.Guid.upper()),\r
                                                     ExtraData=self.FdfFile)\r
                     #\r
-                    # Some INF files not have entity in DSC file. \r
+                    # Some INF files not have entity in DSC file.\r
                     #\r
                     if not InfFoundFlag:\r
                         if FfsFile.InfFileName.find('$') == -1:\r
@@ -784,7 +804,7 @@ class WorkspaceAutoGen(AutoGen):
 \r
                             PathClassObj = PathClass(FfsFile.InfFileName, self.WorkspaceDir)\r
                             #\r
-                            # Here we just need to get FILE_GUID from INF file, use 'COMMON' as ARCH attribute. and use \r
+                            # Here we just need to get FILE_GUID from INF file, use 'COMMON' as ARCH attribute. and use\r
                             # BuildObject from one of AutoGenObjectList is enough.\r
                             #\r
                             InfObj = self.AutoGenObjectList[0].BuildDatabase.WorkspaceDb.BuildObject[PathClassObj, TAB_ARCH_COMMON, self.BuildTarget, self.ToolChain]\r
@@ -803,7 +823,7 @@ class WorkspaceAutoGen(AutoGen):
 \r
                 if FfsFile.NameGuid is not None:\r
                     #\r
-                    # If the NameGuid reference a PCD name. \r
+                    # If the NameGuid reference a PCD name.\r
                     # The style must match: PCD(xxxx.yyy)\r
                     #\r
                     if gPCDAsGuidPattern.match(FfsFile.NameGuid):\r
@@ -867,11 +887,11 @@ class WorkspaceAutoGen(AutoGen):
 \r
 \r
     def _CheckPcdDefineAndType(self):\r
-        PcdTypeList = [\r
-            TAB_PCDS_FIXED_AT_BUILD, TAB_PCDS_PATCHABLE_IN_MODULE, TAB_PCDS_FEATURE_FLAG,\r
-            TAB_PCDS_DYNAMIC, #"DynamicHii", "DynamicVpd",\r
-            TAB_PCDS_DYNAMIC_EX, # "DynamicExHii", "DynamicExVpd"\r
-        ]\r
+        PcdTypeSet = {TAB_PCDS_FIXED_AT_BUILD,\r
+            TAB_PCDS_PATCHABLE_IN_MODULE,\r
+            TAB_PCDS_FEATURE_FLAG,\r
+            TAB_PCDS_DYNAMIC,\r
+            TAB_PCDS_DYNAMIC_EX}\r
 \r
         # This dict store PCDs which are not used by any modules with specified arches\r
         UnusedPcd = OrderedDict()\r
@@ -880,7 +900,7 @@ class WorkspaceAutoGen(AutoGen):
             for Pcd in Pa.Platform.Pcds:\r
                 PcdType = Pa.Platform.Pcds[Pcd].Type\r
 \r
-                # If no PCD type, this PCD comes from FDF \r
+                # If no PCD type, this PCD comes from FDF\r
                 if not PcdType:\r
                     continue\r
 \r
@@ -894,7 +914,7 @@ class WorkspaceAutoGen(AutoGen):
                     # Key of DEC's Pcds dictionary is PcdCName, TokenSpaceGuid, PcdType\r
                     if (Pcd[0], Pcd[1], PcdType) in Package.Pcds:\r
                         break\r
-                    for Type in PcdTypeList:\r
+                    for Type in PcdTypeSet:\r
                         if (Pcd[0], Pcd[1], Type) in Package.Pcds:\r
                             EdkLogger.error(\r
                                 'build',\r
@@ -922,7 +942,7 @@ class WorkspaceAutoGen(AutoGen):
     ## Return the directory to store FV files\r
     def _GetFvDir(self):\r
         if self._FvDir is None:\r
-            self._FvDir = path.join(self.BuildDir, 'FV')\r
+            self._FvDir = path.join(self.BuildDir, TAB_FV_DIRECTORY)\r
         return self._FvDir\r
 \r
     ## Return the directory to store all intermediate and final files built\r
@@ -972,14 +992,14 @@ class WorkspaceAutoGen(AutoGen):
     ## Check the PCDs token value conflict in each DEC file.\r
     #\r
     # Will cause build break and raise error message while two PCDs conflict.\r
-    # \r
+    #\r
     # @return  None\r
     #\r
     def _CheckAllPcdsTokenValueConflict(self):\r
         for Pa in self.AutoGenObjectList:\r
             for Package in Pa.PackageList:\r
                 PcdList = Package.Pcds.values()\r
-                PcdList.sort(lambda x, y: cmp(int(x.TokenValue, 0), int(y.TokenValue, 0))) \r
+                PcdList.sort(lambda x, y: cmp(int(x.TokenValue, 0), int(y.TokenValue, 0)))\r
                 Count = 0\r
                 while (Count < len(PcdList) - 1) :\r
                     Item = PcdList[Count]\r
@@ -1052,9 +1072,10 @@ class WorkspaceAutoGen(AutoGen):
     #                                       modules will be created as well\r
     #\r
     def CreateMakeFile(self, CreateDepsMakeFile=False):\r
-        if CreateDepsMakeFile:\r
-            for Pa in self.AutoGenObjectList:\r
-                Pa.CreateMakeFile(CreateDepsMakeFile)\r
+        if not CreateDepsMakeFile:\r
+            return\r
+        for Pa in self.AutoGenObjectList:\r
+            Pa.CreateMakeFile(True)\r
 \r
     ## Create autogen code for platform and modules\r
     #\r
@@ -1068,7 +1089,7 @@ class WorkspaceAutoGen(AutoGen):
         if not CreateDepsCodeFile:\r
             return\r
         for Pa in self.AutoGenObjectList:\r
-            Pa.CreateCodeFile(CreateDepsCodeFile)\r
+            Pa.CreateCodeFile(True)\r
 \r
     ## Create AsBuilt INF file the platform\r
     #\r
@@ -1103,20 +1124,20 @@ class PlatformAutoGen(AutoGen):
             self._InitWorker(Workspace, MetaFile, Target, Toolchain, Arch)\r
             self._Init = True\r
     #\r
-    # Used to store all PCDs for both PEI and DXE phase, in order to generate \r
+    # Used to store all PCDs for both PEI and DXE phase, in order to generate\r
     # correct PCD database\r
-    # \r
+    #\r
     _DynaPcdList_ = []\r
     _NonDynaPcdList_ = []\r
     _PlatformPcds = {}\r
-    \r
+\r
     #\r
-    # The priority list while override build option \r
+    # The priority list while override build option\r
     #\r
     PrioList = {"0x11111"  : 16,     #  TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE (Highest)\r
                 "0x01111"  : 15,     #  ******_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE\r
                 "0x10111"  : 14,     #  TARGET_*********_ARCH_COMMANDTYPE_ATTRIBUTE\r
-                "0x00111"  : 13,     #  ******_*********_ARCH_COMMANDTYPE_ATTRIBUTE \r
+                "0x00111"  : 13,     #  ******_*********_ARCH_COMMANDTYPE_ATTRIBUTE\r
                 "0x11011"  : 12,     #  TARGET_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE\r
                 "0x01011"  : 11,     #  ******_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE\r
                 "0x10011"  : 10,     #  TARGET_*********_****_COMMANDTYPE_ATTRIBUTE\r
@@ -1268,26 +1289,26 @@ class PlatformAutoGen(AutoGen):
     #\r
     def CollectFixedAtBuildPcds(self):\r
         for LibAuto in self.LibraryAutoGenList:\r
-            FixedAtBuildPcds = {}  \r
-            ShareFixedAtBuildPcdsSameValue = {} \r
-            for Module in LibAuto._ReferenceModules:                \r
+            FixedAtBuildPcds = {}\r
+            ShareFixedAtBuildPcdsSameValue = {}\r
+            for Module in LibAuto._ReferenceModules:\r
                 for Pcd in Module.FixedAtBuildPcds + LibAuto.FixedAtBuildPcds:\r
-                    key = ".".join((Pcd.TokenSpaceGuidCName,Pcd.TokenCName))  \r
+                    key = ".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName))\r
                     if key not in FixedAtBuildPcds:\r
                         ShareFixedAtBuildPcdsSameValue[key] = True\r
                         FixedAtBuildPcds[key] = Pcd.DefaultValue\r
                     else:\r
                         if FixedAtBuildPcds[key] != Pcd.DefaultValue:\r
-                            ShareFixedAtBuildPcdsSameValue[key] = False      \r
+                            ShareFixedAtBuildPcdsSameValue[key] = False\r
             for Pcd in LibAuto.FixedAtBuildPcds:\r
-                key = ".".join((Pcd.TokenSpaceGuidCName,Pcd.TokenCName))\r
-                if (Pcd.TokenCName,Pcd.TokenSpaceGuidCName) not in self.NonDynamicPcdDict:\r
+                key = ".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName))\r
+                if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) not in self.NonDynamicPcdDict:\r
                     continue\r
                 else:\r
-                    DscPcd = self.NonDynamicPcdDict[(Pcd.TokenCName,Pcd.TokenSpaceGuidCName)]\r
+                    DscPcd = self.NonDynamicPcdDict[(Pcd.TokenCName, Pcd.TokenSpaceGuidCName)]\r
                     if DscPcd.Type != TAB_PCDS_FIXED_AT_BUILD:\r
                         continue\r
-                if key in ShareFixedAtBuildPcdsSameValue and ShareFixedAtBuildPcdsSameValue[key]:                    \r
+                if key in ShareFixedAtBuildPcdsSameValue and ShareFixedAtBuildPcdsSameValue[key]:\r
                     LibAuto.ConstPcd[key] = FixedAtBuildPcds[key]\r
 \r
     def CollectVariables(self, DynamicPcdSet):\r
@@ -1304,12 +1325,12 @@ class PlatformAutoGen(AutoGen):
                         break\r
 \r
 \r
-        VariableInfo = VariableMgr(self.DscBuildDataObj._GetDefaultStores(),self.DscBuildDataObj._GetSkuIds())\r
+        VariableInfo = VariableMgr(self.DscBuildDataObj._GetDefaultStores(), self.DscBuildDataObj._GetSkuIds())\r
         VariableInfo.SetVpdRegionMaxSize(VpdRegionSize)\r
         VariableInfo.SetVpdRegionOffset(VpdRegionBase)\r
         Index = 0\r
         for Pcd in DynamicPcdSet:\r
-            pcdname = ".".join((Pcd.TokenSpaceGuidCName,Pcd.TokenCName))\r
+            pcdname = ".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName))\r
             for SkuName in Pcd.SkuInfoList:\r
                 Sku = Pcd.SkuInfoList[SkuName]\r
                 SkuId = Sku.SkuId\r
@@ -1319,13 +1340,13 @@ class PlatformAutoGen(AutoGen):
                     VariableGuidStructure = Sku.VariableGuidValue\r
                     VariableGuid = GuidStructureStringToGuidString(VariableGuidStructure)\r
                     for StorageName in Sku.DefaultStoreDict:\r
-                        VariableInfo.append_variable(var_info(Index,pcdname,StorageName,SkuName, StringToArray(Sku.VariableName),VariableGuid, Sku.VariableOffset, Sku.VariableAttribute , Sku.HiiDefaultValue,Sku.DefaultStoreDict[StorageName],Pcd.DatumType))\r
+                        VariableInfo.append_variable(var_info(Index, pcdname, StorageName, SkuName, StringToArray(Sku.VariableName), VariableGuid, Sku.VariableOffset, Sku.VariableAttribute, Sku.HiiDefaultValue, Sku.DefaultStoreDict[StorageName], Pcd.DatumType))\r
             Index += 1\r
         return VariableInfo\r
 \r
-    def UpdateNVStoreMaxSize(self,OrgVpdFile):\r
+    def UpdateNVStoreMaxSize(self, OrgVpdFile):\r
         if self.VariableInfo:\r
-            VpdMapFilePath = os.path.join(self.BuildDir, "FV", "%s.map" % self.Platform.VpdToolGuid)\r
+            VpdMapFilePath = os.path.join(self.BuildDir, TAB_FV_DIRECTORY, "%s.map" % self.Platform.VpdToolGuid)\r
             PcdNvStoreDfBuffer = [item for item in self._DynamicPcdList if item.TokenCName == "PcdNvStoreDefaultValueBuffer" and item.TokenSpaceGuidCName == "gEfiMdeModulePkgTokenSpaceGuid"]\r
 \r
             if PcdNvStoreDfBuffer:\r
@@ -1336,7 +1357,7 @@ class PlatformAutoGen(AutoGen):
                 else:\r
                     EdkLogger.error("build", FILE_READ_FAILURE, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath)\r
 \r
-                NvStoreOffset = int(NvStoreOffset,16) if NvStoreOffset.upper().startswith("0X") else int(NvStoreOffset)\r
+                NvStoreOffset = int(NvStoreOffset, 16) if NvStoreOffset.upper().startswith("0X") else int(NvStoreOffset)\r
                 default_skuobj = PcdNvStoreDfBuffer[0].SkuInfoList.get(TAB_DEFAULT)\r
                 maxsize = self.VariableInfo.VpdRegionSize  - NvStoreOffset if self.VariableInfo.VpdRegionSize else len(default_skuobj.DefaultValue.split(","))\r
                 var_data = self.VariableInfo.PatchNVStoreDefaultMaxSize(maxsize)\r
@@ -1362,8 +1383,8 @@ class PlatformAutoGen(AutoGen):
                 if (self.Platform.Pcds[key].TokenCName, self.Platform.Pcds[key].TokenSpaceGuidCName) == SinglePcd:\r
                     for item in GlobalData.MixedPcd[SinglePcd]:\r
                         Pcd_Type = item[0].split('_')[-1]\r
-                        if (Pcd_Type == self.Platform.Pcds[key].Type) or (Pcd_Type == TAB_PCDS_DYNAMIC_EX and self.Platform.Pcds[key].Type in GenC.gDynamicExPcd) or \\r
-                           (Pcd_Type == TAB_PCDS_DYNAMIC and self.Platform.Pcds[key].Type in GenC.gDynamicPcd):\r
+                        if (Pcd_Type == self.Platform.Pcds[key].Type) or (Pcd_Type == TAB_PCDS_DYNAMIC_EX and self.Platform.Pcds[key].Type in PCD_DYNAMIC_EX_TYPE_SET) or \\r
+                           (Pcd_Type == TAB_PCDS_DYNAMIC and self.Platform.Pcds[key].Type in PCD_DYNAMIC_TYPE_SET):\r
                             Value = self.Platform.Pcds[key]\r
                             Value.TokenCName = self.Platform.Pcds[key].TokenCName + '_' + Pcd_Type\r
                             if len(key) == 2:\r
@@ -1373,11 +1394,7 @@ class PlatformAutoGen(AutoGen):
                             del self.Platform.Pcds[key]\r
                             self.Platform.Pcds[newkey] = Value\r
                             break\r
-                        else:\r
-                            pass\r
                     break\r
-                else:\r
-                    pass\r
 \r
         # for gathering error information\r
         NoDatumTypePcdList = set()\r
@@ -1388,41 +1405,41 @@ class PlatformAutoGen(AutoGen):
         for F in self.Platform.Modules.keys():\r
             M = ModuleAutoGen(self.Workspace, F, self.BuildTarget, self.ToolChain, self.Arch, self.MetaFile)\r
             #GuidValue.update(M.Guids)\r
-            \r
+\r
             self.Platform.Modules[F].M = M\r
 \r
             for PcdFromModule in M.ModulePcdList + M.LibraryPcdList:\r
                 # make sure that the "VOID*" kind of datum has MaxDatumSize set\r
-                if PcdFromModule.DatumType == TAB_VOID and PcdFromModule.MaxDatumSize in [None, '']:\r
+                if PcdFromModule.DatumType == TAB_VOID and not PcdFromModule.MaxDatumSize:\r
                     NoDatumTypePcdList.add("%s.%s [%s]" % (PcdFromModule.TokenSpaceGuidCName, PcdFromModule.TokenCName, F))\r
 \r
                 # Check the PCD from Binary INF or Source INF\r
                 if M.IsBinaryModule == True:\r
                     PcdFromModule.IsFromBinaryInf = True\r
 \r
-                # Check the PCD from DSC or not \r
+                # Check the PCD from DSC or not\r
                 PcdFromModule.IsFromDsc = (PcdFromModule.TokenCName, PcdFromModule.TokenSpaceGuidCName) in self.Platform.Pcds\r
 \r
-                if PcdFromModule.Type in GenC.gDynamicPcd or PcdFromModule.Type in GenC.gDynamicExPcd:\r
+                if PcdFromModule.Type in PCD_DYNAMIC_TYPE_SET or PcdFromModule.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
                     if F.Path not in FdfModuleList:\r
-                        # If one of the Source built modules listed in the DSC is not listed \r
-                        # in FDF modules, and the INF lists a PCD can only use the PcdsDynamic \r
-                        # access method (it is only listed in the DEC file that declares the \r
+                        # If one of the Source built modules listed in the DSC is not listed\r
+                        # in FDF modules, and the INF lists a PCD can only use the PcdsDynamic\r
+                        # access method (it is only listed in the DEC file that declares the\r
                         # PCD as PcdsDynamic), then build tool will report warning message\r
-                        # notify the PI that they are attempting to build a module that must \r
-                        # be included in a flash image in order to be functional. These Dynamic \r
-                        # PCD will not be added into the Database unless it is used by other \r
+                        # notify the PI that they are attempting to build a module that must\r
+                        # be included in a flash image in order to be functional. These Dynamic\r
+                        # PCD will not be added into the Database unless it is used by other\r
                         # modules that are included in the FDF file.\r
-                        if PcdFromModule.Type in GenC.gDynamicPcd and \\r
+                        if PcdFromModule.Type in PCD_DYNAMIC_TYPE_SET and \\r
                             PcdFromModule.IsFromBinaryInf == False:\r
                             # Print warning message to let the developer make a determine.\r
                             continue\r
-                        # If one of the Source built modules listed in the DSC is not listed in \r
-                        # FDF modules, and the INF lists a PCD can only use the PcdsDynamicEx \r
-                        # access method (it is only listed in the DEC file that declares the \r
-                        # PCD as PcdsDynamicEx), then DO NOT break the build; DO NOT add the \r
+                        # If one of the Source built modules listed in the DSC is not listed in\r
+                        # FDF modules, and the INF lists a PCD can only use the PcdsDynamicEx\r
+                        # access method (it is only listed in the DEC file that declares the\r
+                        # PCD as PcdsDynamicEx), then DO NOT break the build; DO NOT add the\r
                         # PCD to the Platform's PCD Database.\r
-                        if PcdFromModule.Type in GenC.gDynamicExPcd:\r
+                        if PcdFromModule.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
                             continue\r
                     #\r
                     # If a dynamic PCD used by a PEM module/PEI module & DXE module,\r
@@ -1430,7 +1447,7 @@ class PlatformAutoGen(AutoGen):
                     # used by DXE module, it should be stored in DXE PCD database.\r
                     # The default Phase is DXE\r
                     #\r
-                    if M.ModuleType in [SUP_MODULE_PEIM, SUP_MODULE_PEI_CORE]:\r
+                    if M.ModuleType in SUP_MODULE_SET_PEI:\r
                         PcdFromModule.Phase = "PEI"\r
                     if PcdFromModule not in self._DynaPcdList_:\r
                         self._DynaPcdList_.append(PcdFromModule)\r
@@ -1448,14 +1465,14 @@ class PlatformAutoGen(AutoGen):
                         PcdFromModule.Pending = False\r
                         self._NonDynaPcdList_.append (PcdFromModule)\r
         DscModuleSet = {os.path.normpath(ModuleInf.Path) for ModuleInf in self.Platform.Modules}\r
-        # add the PCD from modules that listed in FDF but not in DSC to Database \r
+        # add the PCD from modules that listed in FDF but not in DSC to Database\r
         for InfName in FdfModuleList:\r
             if InfName not in DscModuleSet:\r
                 InfClass = PathClass(InfName)\r
                 M = self.BuildDatabase[InfClass, self.Arch, self.BuildTarget, self.ToolChain]\r
-                # If a module INF in FDF but not in current arch's DSC module list, it must be module (either binary or source) \r
-                # for different Arch. PCDs in source module for different Arch is already added before, so skip the source module here. \r
-                # For binary module, if in current arch, we need to list the PCDs into database.   \r
+                # If a module INF in FDF but not in current arch's DSC module list, it must be module (either binary or source)\r
+                # for different Arch. PCDs in source module for different Arch is already added before, so skip the source module here.\r
+                # For binary module, if in current arch, we need to list the PCDs into database.\r
                 if not M.IsSupportedArch:\r
                     continue\r
                 # Override the module PCD setting by platform setting\r
@@ -1464,36 +1481,36 @@ class PlatformAutoGen(AutoGen):
                     PcdFromModule.IsFromBinaryInf = True\r
                     PcdFromModule.IsFromDsc = False\r
                     # Only allow the DynamicEx and Patchable PCD in AsBuild INF\r
-                    if PcdFromModule.Type not in GenC.gDynamicExPcd and PcdFromModule.Type not in TAB_PCDS_PATCHABLE_IN_MODULE:\r
+                    if PcdFromModule.Type not in PCD_DYNAMIC_EX_TYPE_SET and PcdFromModule.Type not in TAB_PCDS_PATCHABLE_IN_MODULE:\r
                         EdkLogger.error("build", AUTOGEN_ERROR, "PCD setting error",\r
                                         File=self.MetaFile,\r
                                         ExtraData="\n\tExisted %s PCD %s in:\n\t\t%s\n"\r
                                         % (PcdFromModule.Type, PcdFromModule.TokenCName, InfName))\r
                     # make sure that the "VOID*" kind of datum has MaxDatumSize set\r
-                    if PcdFromModule.DatumType == TAB_VOID and PcdFromModule.MaxDatumSize in [None, '']:\r
+                    if PcdFromModule.DatumType == TAB_VOID and not PcdFromModule.MaxDatumSize:\r
                         NoDatumTypePcdList.add("%s.%s [%s]" % (PcdFromModule.TokenSpaceGuidCName, PcdFromModule.TokenCName, InfName))\r
-                    if M.ModuleType in [SUP_MODULE_PEIM, SUP_MODULE_PEI_CORE]:\r
+                    if M.ModuleType in SUP_MODULE_SET_PEI:\r
                         PcdFromModule.Phase = "PEI"\r
-                    if PcdFromModule not in self._DynaPcdList_ and PcdFromModule.Type in GenC.gDynamicExPcd:\r
+                    if PcdFromModule not in self._DynaPcdList_ and PcdFromModule.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
                         self._DynaPcdList_.append(PcdFromModule)\r
                     elif PcdFromModule not in self._NonDynaPcdList_ and PcdFromModule.Type in TAB_PCDS_PATCHABLE_IN_MODULE:\r
                         self._NonDynaPcdList_.append(PcdFromModule)\r
-                    if PcdFromModule in self._DynaPcdList_ and PcdFromModule.Phase == 'PEI' and PcdFromModule.Type in GenC.gDynamicExPcd:\r
+                    if PcdFromModule in self._DynaPcdList_ and PcdFromModule.Phase == 'PEI' and PcdFromModule.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
                         # Overwrite the phase of any the same PCD existing, if Phase is PEI.\r
-                        # It is to solve the case that a dynamic PCD used by a PEM module/PEI \r
+                        # It is to solve the case that a dynamic PCD used by a PEM module/PEI\r
                         # module & DXE module at a same time.\r
                         # Overwrite the type of the PCDs in source INF by the type of AsBuild\r
-                        # INF file as DynamicEx. \r
+                        # INF file as DynamicEx.\r
                         Index = self._DynaPcdList_.index(PcdFromModule)\r
                         self._DynaPcdList_[Index].Phase = PcdFromModule.Phase\r
                         self._DynaPcdList_[Index].Type = PcdFromModule.Type\r
         for PcdFromModule in self._NonDynaPcdList_:\r
-            # If a PCD is not listed in the DSC file, but binary INF files used by \r
-            # this platform all (that use this PCD) list the PCD in a [PatchPcds] \r
-            # section, AND all source INF files used by this platform the build \r
-            # that use the PCD list the PCD in either a [Pcds] or [PatchPcds] \r
+            # If a PCD is not listed in the DSC file, but binary INF files used by\r
+            # this platform all (that use this PCD) list the PCD in a [PatchPcds]\r
+            # section, AND all source INF files used by this platform the build\r
+            # that use the PCD list the PCD in either a [Pcds] or [PatchPcds]\r
             # section, then the tools must NOT add the PCD to the Platform's PCD\r
-            # Database; the build must assign the access method for this PCD as \r
+            # Database; the build must assign the access method for this PCD as\r
             # PcdsPatchableInModule.\r
             if PcdFromModule not in self._DynaPcdList_:\r
                 continue\r
@@ -1516,7 +1533,7 @@ class PlatformAutoGen(AutoGen):
         self._DynamicPcdList = self._DynaPcdList_\r
         #\r
         # Sort dynamic PCD list to:\r
-        # 1) If PCD's datum type is VOID* and value is unicode string which starts with L, the PCD item should \r
+        # 1) If PCD's datum type is VOID* and value is unicode string which starts with L, the PCD item should\r
         #    try to be put header of dynamicd List\r
         # 2) If PCD is HII type, the PCD item should be put after unicode type PCD\r
         #\r
@@ -1537,7 +1554,7 @@ class PlatformAutoGen(AutoGen):
             if self._PlatformPcds[item].DatumType and self._PlatformPcds[item].DatumType not in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64, TAB_VOID, "BOOLEAN"]:\r
                 self._PlatformPcds[item].DatumType = TAB_VOID\r
 \r
-        if (self.Workspace.ArchList[-1] == self.Arch): \r
+        if (self.Workspace.ArchList[-1] == self.Arch):\r
             for Pcd in self._DynamicPcdList:\r
                 # just pick the a value to determine whether is unicode string type\r
                 Sku = Pcd.SkuInfoList.values()[0]\r
@@ -1552,7 +1569,7 @@ class PlatformAutoGen(AutoGen):
                     VpdPcdDict[(Pcd.TokenCName, Pcd.TokenSpaceGuidCName)] = Pcd\r
 \r
             #Collect DynamicHii PCD values and assign it to DynamicExVpd PCD gEfiMdeModulePkgTokenSpaceGuid.PcdNvStoreDefaultValueBuffer\r
-            PcdNvStoreDfBuffer = VpdPcdDict.get(("PcdNvStoreDefaultValueBuffer","gEfiMdeModulePkgTokenSpaceGuid"))\r
+            PcdNvStoreDfBuffer = VpdPcdDict.get(("PcdNvStoreDefaultValueBuffer", "gEfiMdeModulePkgTokenSpaceGuid"))\r
             if PcdNvStoreDfBuffer:\r
                 self.VariableInfo = self.CollectVariables(self._DynamicPcdList)\r
                 vardump = self.VariableInfo.dump()\r
@@ -1562,8 +1579,7 @@ class PlatformAutoGen(AutoGen):
                         PcdNvStoreDfBuffer.SkuInfoList[skuname].DefaultValue = vardump\r
                         PcdNvStoreDfBuffer.MaxDatumSize = str(len(vardump.split(",")))\r
 \r
-            PlatformPcds = self._PlatformPcds.keys()\r
-            PlatformPcds.sort()\r
+            PlatformPcds = sorted(self._PlatformPcds.keys())\r
             #\r
             # Add VPD type PCD into VpdFile and determine whether the VPD PCD need to be fixed up.\r
             #\r
@@ -1579,10 +1595,10 @@ class PlatformAutoGen(AutoGen):
                         PcdValue = DefaultSku.DefaultValue\r
                         if PcdValue not in SkuValueMap:\r
                             SkuValueMap[PcdValue] = []\r
-                            VpdFile.Add(Pcd, TAB_DEFAULT,DefaultSku.VpdOffset)\r
+                            VpdFile.Add(Pcd, TAB_DEFAULT, DefaultSku.VpdOffset)\r
                         SkuValueMap[PcdValue].append(DefaultSku)\r
 \r
-                    for (SkuName,Sku) in Pcd.SkuInfoList.items():\r
+                    for (SkuName, Sku) in Pcd.SkuInfoList.items():\r
                         Sku.VpdOffset = Sku.VpdOffset.strip()\r
                         PcdValue = Sku.DefaultValue\r
                         if PcdValue == "":\r
@@ -1608,7 +1624,7 @@ class PlatformAutoGen(AutoGen):
                                     EdkLogger.error("build", FORMAT_INVALID, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName, Alignment))\r
                         if PcdValue not in SkuValueMap:\r
                             SkuValueMap[PcdValue] = []\r
-                            VpdFile.Add(Pcd, SkuName,Sku.VpdOffset)\r
+                            VpdFile.Add(Pcd, SkuName, Sku.VpdOffset)\r
                         SkuValueMap[PcdValue].append(Sku)\r
                         # if the offset of a VPD is *, then it need to be fixed up by third party tool.\r
                         if not NeedProcessVpdMapFile and Sku.VpdOffset == "*":\r
@@ -1621,7 +1637,7 @@ class PlatformAutoGen(AutoGen):
             #\r
             # Fix the PCDs define in VPD PCD section that never referenced by module.\r
             # An example is PCD for signature usage.\r
-            #            \r
+            #\r
             for DscPcd in PlatformPcds:\r
                 DscPcdEntry = self._PlatformPcds[DscPcd]\r
                 if DscPcdEntry.Type in [TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_VPD]:\r
@@ -1640,11 +1656,11 @@ class PlatformAutoGen(AutoGen):
                             SkuObjList = DscPcdEntry.SkuInfoList.items()\r
                             DefaultSku = DscPcdEntry.SkuInfoList.get(TAB_DEFAULT)\r
                             if DefaultSku:\r
-                                defaultindex = SkuObjList.index((TAB_DEFAULT,DefaultSku))\r
-                                SkuObjList[0],SkuObjList[defaultindex] = SkuObjList[defaultindex],SkuObjList[0]\r
-                            for (SkuName,Sku) in SkuObjList:\r
-                                Sku.VpdOffset = Sku.VpdOffset.strip() \r
-                                \r
+                                defaultindex = SkuObjList.index((TAB_DEFAULT, DefaultSku))\r
+                                SkuObjList[0], SkuObjList[defaultindex] = SkuObjList[defaultindex], SkuObjList[0]\r
+                            for (SkuName, Sku) in SkuObjList:\r
+                                Sku.VpdOffset = Sku.VpdOffset.strip()\r
+\r
                                 # Need to iterate DEC pcd information to get the value & datumtype\r
                                 for eachDec in self.PackageList:\r
                                     for DecPcd in eachDec.Pcds:\r
@@ -1655,8 +1671,8 @@ class PlatformAutoGen(AutoGen):
                                             EdkLogger.warn("build", "Unreferenced vpd pcd used!",\r
                                                             File=self.MetaFile, \\r
                                                             ExtraData = "PCD: %s.%s used in the DSC file %s is unreferenced." \\r
-                                                            %(DscPcdEntry.TokenSpaceGuidCName, DscPcdEntry.TokenCName, self.Platform.MetaFile.Path))  \r
-                                                                                  \r
+                                                            %(DscPcdEntry.TokenSpaceGuidCName, DscPcdEntry.TokenCName, self.Platform.MetaFile.Path))\r
+\r
                                             DscPcdEntry.DatumType    = DecPcdEntry.DatumType\r
                                             DscPcdEntry.DefaultValue = DecPcdEntry.DefaultValue\r
                                             DscPcdEntry.TokenValue = DecPcdEntry.TokenValue\r
@@ -1664,7 +1680,7 @@ class PlatformAutoGen(AutoGen):
                                             # Only fix the value while no value provided in DSC file.\r
                                             if not Sku.DefaultValue:\r
                                                 DscPcdEntry.SkuInfoList[DscPcdEntry.SkuInfoList.keys()[0]].DefaultValue = DecPcdEntry.DefaultValue\r
-                                                                                                                    \r
+\r
                                 if DscPcdEntry not in self._DynamicPcdList:\r
                                     self._DynamicPcdList.append(DscPcdEntry)\r
                                 Sku.VpdOffset = Sku.VpdOffset.strip()\r
@@ -1692,10 +1708,10 @@ class PlatformAutoGen(AutoGen):
                                             EdkLogger.error("build", FORMAT_INVALID, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (DscPcdEntry.TokenSpaceGuidCName, DscPcdEntry.TokenCName, Alignment))\r
                                 if PcdValue not in SkuValueMap:\r
                                     SkuValueMap[PcdValue] = []\r
-                                    VpdFile.Add(DscPcdEntry, SkuName,Sku.VpdOffset)\r
+                                    VpdFile.Add(DscPcdEntry, SkuName, Sku.VpdOffset)\r
                                 SkuValueMap[PcdValue].append(Sku)\r
                                 if not NeedProcessVpdMapFile and Sku.VpdOffset == "*":\r
-                                    NeedProcessVpdMapFile = True \r
+                                    NeedProcessVpdMapFile = True\r
                             if DscPcdEntry.DatumType == TAB_VOID and PcdValue.startswith("L"):\r
                                 UnicodePcdArray.add(DscPcdEntry)\r
                             elif len(Sku.VariableName) > 0:\r
@@ -1707,7 +1723,7 @@ class PlatformAutoGen(AutoGen):
                             VpdSkuMap[DscPcd] = SkuValueMap\r
             if (self.Platform.FlashDefinition is None or self.Platform.FlashDefinition == '') and \\r
                VpdFile.GetCount() != 0:\r
-                EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, \r
+                EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE,\r
                                 "Fail to get FLASH_DEFINITION definition in DSC file %s which is required when DSC contains VPD PCD." % str(self.Platform.MetaFile))\r
 \r
             if VpdFile.GetCount() != 0:\r
@@ -1718,7 +1734,7 @@ class PlatformAutoGen(AutoGen):
 \r
                 # Process VPD map file generated by third party BPDG tool\r
                 if NeedProcessVpdMapFile:\r
-                    VpdMapFilePath = os.path.join(self.BuildDir, "FV", "%s.map" % self.Platform.VpdToolGuid)\r
+                    VpdMapFilePath = os.path.join(self.BuildDir, TAB_FV_DIRECTORY, "%s.map" % self.Platform.VpdToolGuid)\r
                     if os.path.exists(VpdMapFilePath):\r
                         VpdFile.Read(VpdMapFilePath)\r
 \r
@@ -1758,18 +1774,18 @@ class PlatformAutoGen(AutoGen):
         self._DynamicPcdList.extend(list(UnicodePcdArray))\r
         self._DynamicPcdList.extend(list(HiiPcdArray))\r
         self._DynamicPcdList.extend(list(OtherPcdArray))\r
-        allskuset = [(SkuName,Sku.SkuId) for pcd in self._DynamicPcdList for (SkuName,Sku) in pcd.SkuInfoList.items()]\r
+        allskuset = [(SkuName, Sku.SkuId) for pcd in self._DynamicPcdList for (SkuName, Sku) in pcd.SkuInfoList.items()]\r
         for pcd in self._DynamicPcdList:\r
             if len(pcd.SkuInfoList) == 1:\r
-                for (SkuName,SkuId) in allskuset:\r
-                    if type(SkuId) in (str,unicode) and eval(SkuId) == 0 or SkuId == 0:\r
+                for (SkuName, SkuId) in allskuset:\r
+                    if type(SkuId) in (str, unicode) and eval(SkuId) == 0 or SkuId == 0:\r
                         continue\r
                     pcd.SkuInfoList[SkuName] = copy.deepcopy(pcd.SkuInfoList[TAB_DEFAULT])\r
                     pcd.SkuInfoList[SkuName].SkuId = SkuId\r
         self.AllPcdList = self._NonDynamicPcdList + self._DynamicPcdList\r
 \r
-    def FixVpdOffset(self,VpdFile ):\r
-        FvPath = os.path.join(self.BuildDir, "FV")\r
+    def FixVpdOffset(self, VpdFile ):\r
+        FvPath = os.path.join(self.BuildDir, TAB_FV_DIRECTORY)\r
         if not os.path.exists(FvPath):\r
             try:\r
                 os.makedirs(FvPath)\r
@@ -1782,8 +1798,8 @@ class PlatformAutoGen(AutoGen):
             # retrieve BPDG tool's path from tool_def.txt according to VPD_TOOL_GUID defined in DSC file.\r
             BPDGToolName = None\r
             for ToolDef in self.ToolDefinition.values():\r
-                if ToolDef.has_key("GUID") and ToolDef["GUID"] == self.Platform.VpdToolGuid:\r
-                    if not ToolDef.has_key("PATH"):\r
+                if TAB_GUID in ToolDef and ToolDef[TAB_GUID] == self.Platform.VpdToolGuid:\r
+                    if "PATH" not in ToolDef:\r
                         EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "PATH attribute was not provided for BPDG guid tool %s in tools_def.txt" % self.Platform.VpdToolGuid)\r
                     BPDGToolName = ToolDef["PATH"]\r
                     break\r
@@ -1869,7 +1885,7 @@ class PlatformAutoGen(AutoGen):
                         if Flags.startswith('='):\r
                             self._BuildCommand = [self._BuildCommand[0]] + [Flags[1:]]\r
                         else:\r
-                            self._BuildCommand += [Flags]\r
+                            self._BuildCommand.append(Flags)\r
         return self._BuildCommand\r
 \r
     ## Get tool chain definition\r
@@ -1998,7 +2014,7 @@ class PlatformAutoGen(AutoGen):
             BuildRuleFile = None\r
             if TAB_TAT_DEFINES_BUILD_RULE_CONF in self.Workspace.TargetTxt.TargetTxtDictionary:\r
                 BuildRuleFile = self.Workspace.TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_BUILD_RULE_CONF]\r
-            if BuildRuleFile in [None, '']:\r
+            if not BuildRuleFile:\r
                 BuildRuleFile = gDefaultBuildRuleFile\r
             self._BuildRule = BuildRule(BuildRuleFile)\r
             if self._BuildRule._FileVersion == "":\r
@@ -2034,7 +2050,7 @@ class PlatformAutoGen(AutoGen):
         if self._NonDynamicPcdDict:\r
             return self._NonDynamicPcdDict\r
         for Pcd in self.NonDynamicPcdList:\r
-            self._NonDynamicPcdDict[(Pcd.TokenCName,Pcd.TokenSpaceGuidCName)] = Pcd\r
+            self._NonDynamicPcdDict[(Pcd.TokenCName, Pcd.TokenSpaceGuidCName)] = Pcd\r
         return self._NonDynamicPcdDict\r
 \r
     ## Get list of non-dynamic PCDs\r
@@ -2055,41 +2071,37 @@ class PlatformAutoGen(AutoGen):
             self._PcdTokenNumber = OrderedDict()\r
             TokenNumber = 1\r
             #\r
-            # Make the Dynamic and DynamicEx PCD use within different TokenNumber area. \r
+            # Make the Dynamic and DynamicEx PCD use within different TokenNumber area.\r
             # Such as:\r
-            # \r
+            #\r
             # Dynamic PCD:\r
             # TokenNumber 0 ~ 10\r
             # DynamicEx PCD:\r
             # TokeNumber 11 ~ 20\r
             #\r
             for Pcd in self.DynamicPcdList:\r
-                if Pcd.Phase == "PEI":\r
-                    if Pcd.Type in [TAB_PCDS_DYNAMIC, "DynamicDefault", "DynamicVpd", "DynamicHii"]:\r
-                        EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))\r
-                        self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
-                        TokenNumber += 1\r
+                if Pcd.Phase == "PEI" and Pcd.Type in PCD_DYNAMIC_TYPE_SET:\r
+                    EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))\r
+                    self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
+                    TokenNumber += 1\r
 \r
             for Pcd in self.DynamicPcdList:\r
-                if Pcd.Phase == "PEI":\r
-                    if Pcd.Type in [TAB_PCDS_DYNAMIC_EX, "DynamicExDefault", "DynamicExVpd", "DynamicExHii"]:\r
-                        EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))\r
-                        self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
-                        TokenNumber += 1\r
+                if Pcd.Phase == "PEI" and Pcd.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
+                    EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))\r
+                    self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
+                    TokenNumber += 1\r
 \r
             for Pcd in self.DynamicPcdList:\r
-                if Pcd.Phase == "DXE":\r
-                    if Pcd.Type in [TAB_PCDS_DYNAMIC, "DynamicDefault", "DynamicVpd", "DynamicHii"]:\r
-                        EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))\r
-                        self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
-                        TokenNumber += 1\r
+                if Pcd.Phase == "DXE" and Pcd.Type in PCD_DYNAMIC_TYPE_SET:\r
+                    EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))\r
+                    self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
+                    TokenNumber += 1\r
 \r
             for Pcd in self.DynamicPcdList:\r
-                if Pcd.Phase == "DXE":\r
-                    if Pcd.Type in [TAB_PCDS_DYNAMIC_EX, "DynamicExDefault", "DynamicExVpd", "DynamicExHii"]:\r
-                        EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))\r
-                        self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
-                        TokenNumber += 1\r
+                if Pcd.Phase == "DXE" and Pcd.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
+                    EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))\r
+                    self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
+                    TokenNumber += 1\r
 \r
             for Pcd in self.NonDynamicPcdList:\r
                 self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
@@ -2152,169 +2164,21 @@ class PlatformAutoGen(AutoGen):
         if str(Module) not in self.Platform.Modules:\r
             return []\r
 \r
-        ModuleType = Module.ModuleType\r
-\r
-        # for overridding library instances with module specific setting\r
-        PlatformModule = self.Platform.Modules[str(Module)]\r
-\r
-        # add forced library instances (specified under LibraryClasses sections)\r
-        #\r
-        # If a module has a MODULE_TYPE of USER_DEFINED,\r
-        # do not link in NULL library class instances from the global [LibraryClasses.*] sections.\r
-        #\r
-        if Module.ModuleType != SUP_MODULE_USER_DEFINED:\r
-            for LibraryClass in self.Platform.LibraryClasses.GetKeys():\r
-                if LibraryClass.startswith("NULL") and self.Platform.LibraryClasses[LibraryClass, Module.ModuleType]:\r
-                    Module.LibraryClasses[LibraryClass] = self.Platform.LibraryClasses[LibraryClass, Module.ModuleType]\r
-\r
-        # add forced library instances (specified in module overrides)\r
-        for LibraryClass in PlatformModule.LibraryClasses:\r
-            if LibraryClass.startswith("NULL"):\r
-                Module.LibraryClasses[LibraryClass] = PlatformModule.LibraryClasses[LibraryClass]\r
-\r
-        # EdkII module\r
-        LibraryConsumerList = [Module]\r
-        Constructor         = []\r
-        ConsumedByList      = OrderedDict()\r
-        LibraryInstance     = OrderedDict()\r
-\r
-        EdkLogger.verbose("")\r
-        EdkLogger.verbose("Library instances of module [%s] [%s]:" % (str(Module), self.Arch))\r
-        while len(LibraryConsumerList) > 0:\r
-            M = LibraryConsumerList.pop()\r
-            for LibraryClassName in M.LibraryClasses:\r
-                if LibraryClassName not in LibraryInstance:\r
-                    # override library instance for this module\r
-                    if LibraryClassName in PlatformModule.LibraryClasses:\r
-                        LibraryPath = PlatformModule.LibraryClasses[LibraryClassName]\r
-                    else:\r
-                        LibraryPath = self.Platform.LibraryClasses[LibraryClassName, ModuleType]\r
-                    if LibraryPath is None or LibraryPath == "":\r
-                        LibraryPath = M.LibraryClasses[LibraryClassName]\r
-                        if LibraryPath is None or LibraryPath == "":\r
-                            EdkLogger.error("build", RESOURCE_NOT_AVAILABLE,\r
-                                            "Instance of library class [%s] is not found" % LibraryClassName,\r
-                                            File=self.MetaFile,\r
-                                            ExtraData="in [%s] [%s]\n\tconsumed by module [%s]" % (str(M), self.Arch, str(Module)))\r
-\r
-                    LibraryModule = self.BuildDatabase[LibraryPath, self.Arch, self.BuildTarget, self.ToolChain]\r
-                    # for those forced library instance (NULL library), add a fake library class\r
-                    if LibraryClassName.startswith("NULL"):\r
-                        LibraryModule.LibraryClass.append(LibraryClassObject(LibraryClassName, [ModuleType]))\r
-                    elif LibraryModule.LibraryClass is None \\r
-                         or len(LibraryModule.LibraryClass) == 0 \\r
-                         or (ModuleType != SUP_MODULE_USER_DEFINED\r
-                             and ModuleType not in LibraryModule.LibraryClass[0].SupModList):\r
-                        # only USER_DEFINED can link against any library instance despite of its SupModList\r
-                        EdkLogger.error("build", OPTION_MISSING,\r
-                                        "Module type [%s] is not supported by library instance [%s]" \\r
-                                        % (ModuleType, LibraryPath), File=self.MetaFile,\r
-                                        ExtraData="consumed by [%s]" % str(Module))\r
-\r
-                    LibraryInstance[LibraryClassName] = LibraryModule\r
-                    LibraryConsumerList.append(LibraryModule)\r
-                    EdkLogger.verbose("\t" + str(LibraryClassName) + " : " + str(LibraryModule))\r
-                else:\r
-                    LibraryModule = LibraryInstance[LibraryClassName]\r
-\r
-                if LibraryModule is None:\r
-                    continue\r
-\r
-                if LibraryModule.ConstructorList != [] and LibraryModule not in Constructor:\r
-                    Constructor.append(LibraryModule)\r
-\r
-                if LibraryModule not in ConsumedByList:\r
-                    ConsumedByList[LibraryModule] = []\r
-                # don't add current module itself to consumer list\r
-                if M != Module:\r
-                    if M in ConsumedByList[LibraryModule]:\r
-                        continue\r
-                    ConsumedByList[LibraryModule].append(M)\r
-        #\r
-        # Initialize the sorted output list to the empty set\r
-        #\r
-        SortedLibraryList = []\r
-        #\r
-        # Q <- Set of all nodes with no incoming edges\r
-        #\r
-        LibraryList = [] #LibraryInstance.values()\r
-        Q = []\r
-        for LibraryClassName in LibraryInstance:\r
-            M = LibraryInstance[LibraryClassName]\r
-            LibraryList.append(M)\r
-            if ConsumedByList[M] == []:\r
-                Q.append(M)\r
-\r
-        #\r
-        # start the  DAG algorithm\r
-        #\r
-        while True:\r
-            EdgeRemoved = True\r
-            while Q == [] and EdgeRemoved:\r
-                EdgeRemoved = False\r
-                # for each node Item with a Constructor\r
-                for Item in LibraryList:\r
-                    if Item not in Constructor:\r
-                        continue\r
-                    # for each Node without a constructor with an edge e from Item to Node\r
-                    for Node in ConsumedByList[Item]:\r
-                        if Node in Constructor:\r
-                            continue\r
-                        # remove edge e from the graph if Node has no constructor\r
-                        ConsumedByList[Item].remove(Node)\r
-                        EdgeRemoved = True\r
-                        if ConsumedByList[Item] == []:\r
-                            # insert Item into Q\r
-                            Q.insert(0, Item)\r
-                            break\r
-                    if Q != []:\r
-                        break\r
-            # DAG is done if there's no more incoming edge for all nodes\r
-            if Q == []:\r
-                break\r
-\r
-            # remove node from Q\r
-            Node = Q.pop()\r
-            # output Node\r
-            SortedLibraryList.append(Node)\r
-\r
-            # for each node Item with an edge e from Node to Item do\r
-            for Item in LibraryList:\r
-                if Node not in ConsumedByList[Item]:\r
-                    continue\r
-                # remove edge e from the graph\r
-                ConsumedByList[Item].remove(Node)\r
-\r
-                if ConsumedByList[Item] != []:\r
-                    continue\r
-                # insert Item into Q, if Item has no other incoming edges\r
-                Q.insert(0, Item)\r
-\r
-        #\r
-        # if any remaining node Item in the graph has a constructor and an incoming edge, then the graph has a cycle\r
-        #\r
-        for Item in LibraryList:\r
-            if ConsumedByList[Item] != [] and Item in Constructor and len(Constructor) > 1:\r
-                ErrorMessage = "\tconsumed by " + "\n\tconsumed by ".join([str(L) for L in ConsumedByList[Item]])\r
-                EdkLogger.error("build", BUILD_ERROR, 'Library [%s] with constructors has a cycle' % str(Item),\r
-                                ExtraData=ErrorMessage, File=self.MetaFile)\r
-            if Item not in SortedLibraryList:\r
-                SortedLibraryList.append(Item)\r
-\r
-        #\r
-        # Build the list of constructor and destructir names\r
-        # The DAG Topo sort produces the destructor order, so the list of constructors must generated in the reverse order\r
-        #\r
-        SortedLibraryList.reverse()\r
-        return SortedLibraryList\r
-\r
+        return GetModuleLibInstances(Module,\r
+                                     self.Platform,\r
+                                     self.BuildDatabase,\r
+                                     self.Arch,\r
+                                     self.BuildTarget,\r
+                                     self.ToolChain,\r
+                                     self.MetaFile,\r
+                                     EdkLogger)\r
 \r
     ## Override PCD setting (type, value, ...)\r
     #\r
     #   @param  ToPcd       The PCD to be overrided\r
     #   @param  FromPcd     The PCD overrideing from\r
     #\r
-    def _OverridePcd(self, ToPcd, FromPcd, Module=""):\r
+    def _OverridePcd(self, ToPcd, FromPcd, Module="", Msg="", Library=""):\r
         #\r
         # in case there's PCDs coming from FDF file, which have no type given.\r
         # at this point, ToPcd.Type has the type found from dependent\r
@@ -2326,18 +2190,20 @@ class PlatformAutoGen(AutoGen):
                 TokenCName = PcdItem[0]\r
                 break\r
         if FromPcd is not None:\r
-            if ToPcd.Pending and FromPcd.Type not in [None, '']:\r
+            if ToPcd.Pending and FromPcd.Type:\r
                 ToPcd.Type = FromPcd.Type\r
-            elif (ToPcd.Type not in [None, '']) and (FromPcd.Type not in [None, ''])\\r
-                and (ToPcd.Type != FromPcd.Type) and (ToPcd.Type in FromPcd.Type):\r
+            elif ToPcd.Type and FromPcd.Type\\r
+                and ToPcd.Type != FromPcd.Type and ToPcd.Type in FromPcd.Type:\r
                 if ToPcd.Type.strip() == TAB_PCDS_DYNAMIC_EX:\r
                     ToPcd.Type = FromPcd.Type\r
-            elif ToPcd.Type not in [None, ''] and FromPcd.Type not in [None, ''] \\r
+            elif ToPcd.Type and FromPcd.Type \\r
                 and ToPcd.Type != FromPcd.Type:\r
+                if Library:\r
+                    Module = str(Module) + " 's library file (" + str(Library) + ")"\r
                 EdkLogger.error("build", OPTION_CONFLICT, "Mismatched PCD type",\r
-                                ExtraData="%s.%s is defined as [%s] in module %s, but as [%s] in platform."\\r
+                                ExtraData="%s.%s is used as [%s] in module %s, but as [%s] in %s."\\r
                                           % (ToPcd.TokenSpaceGuidCName, TokenCName,\r
-                                             ToPcd.Type, Module, FromPcd.Type),\r
+                                             ToPcd.Type, Module, FromPcd.Type, Msg),\r
                                           File=self.MetaFile)\r
 \r
             if FromPcd.MaxDatumSize:\r
@@ -2355,7 +2221,7 @@ class PlatformAutoGen(AutoGen):
             if ToPcd.DefaultValue:\r
                 try:\r
                     ToPcd.DefaultValue = ValueExpressionEx(ToPcd.DefaultValue, ToPcd.DatumType, self._GuidDict)(True)\r
-                except BadExpression, Value:\r
+                except BadExpression as Value:\r
                     EdkLogger.error('Parser', FORMAT_INVALID, 'PCD [%s.%s] Value "%s", %s' %(ToPcd.TokenSpaceGuidCName, ToPcd.TokenCName, ToPcd.DefaultValue, Value),\r
                                         File=self.MetaFile)\r
 \r
@@ -2368,11 +2234,11 @@ class PlatformAutoGen(AutoGen):
             ToPcd.validlists = FromPcd.validlists\r
             ToPcd.expressions = FromPcd.expressions\r
 \r
-        if FromPcd is not None and ToPcd.DatumType == TAB_VOID and ToPcd.MaxDatumSize in ['', None]:\r
+        if FromPcd is not None and ToPcd.DatumType == TAB_VOID and not ToPcd.MaxDatumSize:\r
             EdkLogger.debug(EdkLogger.DEBUG_9, "No MaxDatumSize specified for PCD %s.%s" \\r
                             % (ToPcd.TokenSpaceGuidCName, TokenCName))\r
             Value = ToPcd.DefaultValue\r
-            if Value in [None, '']:\r
+            if not Value:\r
                 ToPcd.MaxDatumSize = '1'\r
             elif Value[0] == 'L':\r
                 ToPcd.MaxDatumSize = str((len(Value) - 2) * 2)\r
@@ -2382,8 +2248,8 @@ class PlatformAutoGen(AutoGen):
                 ToPcd.MaxDatumSize = str(len(Value) - 1)\r
 \r
         # apply default SKU for dynamic PCDS if specified one is not available\r
-        if (ToPcd.Type in PCD_DYNAMIC_TYPE_LIST or ToPcd.Type in PCD_DYNAMIC_EX_TYPE_LIST) \\r
-            and ToPcd.SkuInfoList in [None, {}, '']:\r
+        if (ToPcd.Type in PCD_DYNAMIC_TYPE_SET or ToPcd.Type in PCD_DYNAMIC_EX_TYPE_SET) \\r
+            and not ToPcd.SkuInfoList:\r
             if self.Platform.SkuName in self.Platform.SkuIds:\r
                 SkuName = self.Platform.SkuName\r
             else:\r
@@ -2398,7 +2264,7 @@ class PlatformAutoGen(AutoGen):
     #\r
     #   @retval PCD_list    The list PCDs with settings from platform\r
     #\r
-    def ApplyPcdSetting(self, Module, Pcds):\r
+    def ApplyPcdSetting(self, Module, Pcds, Library=""):\r
         # for each PCD in module\r
         for Name, Guid in Pcds:\r
             PcdInModule = Pcds[Name, Guid]\r
@@ -2408,14 +2274,14 @@ class PlatformAutoGen(AutoGen):
             else:\r
                 PcdInPlatform = None\r
             # then override the settings if any\r
-            self._OverridePcd(PcdInModule, PcdInPlatform, Module)\r
+            self._OverridePcd(PcdInModule, PcdInPlatform, Module, Msg="DSC PCD sections", Library=Library)\r
             # resolve the VariableGuid value\r
             for SkuId in PcdInModule.SkuInfoList:\r
                 Sku = PcdInModule.SkuInfoList[SkuId]\r
                 if Sku.VariableGuid == '': continue\r
                 Sku.VariableGuidValue = GuidValue(Sku.VariableGuid, self.PackageList, self.MetaFile.Path)\r
                 if Sku.VariableGuidValue is None:\r
-                    PackageList = "\n\t".join([str(P) for P in self.PackageList])\r
+                    PackageList = "\n\t".join(str(P) for P in self.PackageList)\r
                     EdkLogger.error(\r
                                 'build',\r
                                 RESOURCE_NOT_AVAILABLE,\r
@@ -2440,14 +2306,14 @@ class PlatformAutoGen(AutoGen):
                             Flag = True\r
                             break\r
                 if Flag:\r
-                    self._OverridePcd(ToPcd, PlatformModule.Pcds[Key], Module)\r
+                    self._OverridePcd(ToPcd, PlatformModule.Pcds[Key], Module, Msg="DSC Components Module scoped PCD section", Library=Library)\r
         # use PCD value to calculate the MaxDatumSize when it is not specified\r
         for Name, Guid in Pcds:\r
             Pcd = Pcds[Name, Guid]\r
-            if Pcd.DatumType == TAB_VOID and Pcd.MaxDatumSize in ['', None]:\r
+            if Pcd.DatumType == TAB_VOID and not Pcd.MaxDatumSize:\r
                 Pcd.MaxSizeUserSet = None\r
                 Value = Pcd.DefaultValue\r
-                if Value in [None, '']:\r
+                if not Value:\r
                     Pcd.MaxDatumSize = '1'\r
                 elif Value[0] == 'L':\r
                     Pcd.MaxDatumSize = str((len(Value) - 2) * 2)\r
@@ -2522,7 +2388,7 @@ class PlatformAutoGen(AutoGen):
     #   @param  Options     Options to be expanded\r
     #\r
     #   @retval options     Options expanded\r
-    #      \r
+    #\r
     def _ExpandBuildOption(self, Options, ModuleStyle=None):\r
         BuildOptions = {}\r
         FamilyMatch  = False\r
@@ -2540,16 +2406,17 @@ class PlatformAutoGen(AutoGen):
             if (Key[0] == self.BuildRuleFamily and\r
                 (ModuleStyle is None or len(Key) < 3 or (len(Key) > 2 and Key[2] == ModuleStyle))):\r
                 Target, ToolChain, Arch, CommandType, Attr = Key[1].split('_')\r
-                if Target == self.BuildTarget or Target == "*":\r
-                    if ToolChain == self.ToolChain or ToolChain == "*":\r
-                        if Arch == self.Arch or Arch == "*":\r
-                            if Options[Key].startswith("="):\r
-                                if OverrideList.get(Key[1]) is not None:\r
-                                    OverrideList.pop(Key[1])\r
-                                OverrideList[Key[1]] = Options[Key]\r
-        \r
+                if (Target == self.BuildTarget or Target == "*") and\\r
+                    (ToolChain == self.ToolChain or ToolChain == "*") and\\r
+                    (Arch == self.Arch or Arch == "*") and\\r
+                    Options[Key].startswith("="):\r
+\r
+                    if OverrideList.get(Key[1]) is not None:\r
+                        OverrideList.pop(Key[1])\r
+                    OverrideList[Key[1]] = Options[Key]\r
+\r
         #\r
-        # Use the highest priority value. \r
+        # Use the highest priority value.\r
         #\r
         if (len(OverrideList) >= 2):\r
             KeyList = OverrideList.keys()\r
@@ -2560,20 +2427,21 @@ class PlatformAutoGen(AutoGen):
                     NextKey = KeyList[Index1 + Index + 1]\r
                     #\r
                     # Compare two Key, if one is included by another, choose the higher priority one\r
-                    #                    \r
+                    #\r
                     Target2, ToolChain2, Arch2, CommandType2, Attr2 = NextKey.split("_")\r
-                    if Target1 == Target2 or Target1 == "*" or Target2 == "*":\r
-                        if ToolChain1 == ToolChain2 or ToolChain1 == "*" or ToolChain2 == "*":\r
-                            if Arch1 == Arch2 or Arch1 == "*" or Arch2 == "*":\r
-                                if CommandType1 == CommandType2 or CommandType1 == "*" or CommandType2 == "*":\r
-                                    if Attr1 == Attr2 or Attr1 == "*" or Attr2 == "*":\r
-                                        if self.CalculatePriorityValue(NowKey) > self.CalculatePriorityValue(NextKey):\r
-                                            if Options.get((self.BuildRuleFamily, NextKey)) is not None:\r
-                                                Options.pop((self.BuildRuleFamily, NextKey))\r
-                                        else:\r
-                                            if Options.get((self.BuildRuleFamily, NowKey)) is not None:\r
-                                                Options.pop((self.BuildRuleFamily, NowKey))\r
-                                                           \r
+                    if (Target1 == Target2 or Target1 == "*" or Target2 == "*") and\\r
+                        (ToolChain1 == ToolChain2 or ToolChain1 == "*" or ToolChain2 == "*") and\\r
+                        (Arch1 == Arch2 or Arch1 == "*" or Arch2 == "*") and\\r
+                        (CommandType1 == CommandType2 or CommandType1 == "*" or CommandType2 == "*") and\\r
+                        (Attr1 == Attr2 or Attr1 == "*" or Attr2 == "*"):\r
+\r
+                        if self.CalculatePriorityValue(NowKey) > self.CalculatePriorityValue(NextKey):\r
+                            if Options.get((self.BuildRuleFamily, NextKey)) is not None:\r
+                                Options.pop((self.BuildRuleFamily, NextKey))\r
+                        else:\r
+                            if Options.get((self.BuildRuleFamily, NowKey)) is not None:\r
+                                Options.pop((self.BuildRuleFamily, NowKey))\r
+\r
         for Key in Options:\r
             if ModuleStyle is not None and len (Key) > 2:\r
                 # Check Module style is EDK or EDKII.\r
@@ -2734,6 +2602,15 @@ class PlatformAutoGen(AutoGen):
     LibraryAutoGenList  = property(_GetLibraryAutoGenList)\r
     GenFdsCommand       = property(_GenFdsCommand)\r
 \r
+#\r
+# extend lists contained in a dictionary with lists stored in another dictionary\r
+# if CopyToDict is not derived from DefaultDict(list) then this may raise exception\r
+#\r
+def ExtendCopyDictionaryLists(CopyToDict, CopyFromDict):\r
+    for Key in CopyFromDict:\r
+        CopyToDict[Key].extend(CopyFromDict[Key])\r
+\r
+\r
 ## ModuleAutoGen class\r
 #\r
 # This class encapsules the AutoGen behaviors for the build tools. In addition to\r
@@ -2762,7 +2639,7 @@ class ModuleAutoGen(AutoGen):
                               % (MetaFile, Arch))\r
             return None\r
         return obj\r
-            \r
+\r
     ## Initialize ModuleAutoGen\r
     #\r
     #   @param      Workspace           EdkIIWorkspaceBuild object\r
@@ -2824,7 +2701,6 @@ class ModuleAutoGen(AutoGen):
         self._MakeFileDir     = None\r
 \r
         self._IncludePathList = None\r
-        self._IncludePathLength = 0\r
         self._AutoGenFileList = None\r
         self._UnicodeFileList = None\r
         self._VfrFileList = None\r
@@ -2839,16 +2715,16 @@ class ModuleAutoGen(AutoGen):
         self._DerivedPackageList      = None\r
         self._ModulePcdList           = None\r
         self._LibraryPcdList          = None\r
-        self._PcdComments = OrderedDict()\r
+        self._PcdComments = OrderedListDict()\r
         self._GuidList                = None\r
         self._GuidsUsedByPcd = None\r
-        self._GuidComments = OrderedDict()\r
+        self._GuidComments = OrderedListDict()\r
         self._ProtocolList            = None\r
-        self._ProtocolComments = OrderedDict()\r
+        self._ProtocolComments = OrderedListDict()\r
         self._PpiList                 = None\r
-        self._PpiComments = OrderedDict()\r
-        self._DepexList               = None\r
-        self._DepexExpressionList     = None\r
+        self._PpiComments = OrderedListDict()\r
+        self._DepexDict               = None\r
+        self._DepexExpressionDict     = None\r
         self._BuildOption             = None\r
         self._BuildOptionIncPathList  = None\r
         self._BuildTargets            = None\r
@@ -2861,16 +2737,15 @@ class ModuleAutoGen(AutoGen):
 \r
         self.AutoGenDepSet = set()\r
 \r
-        \r
+\r
         ## The Modules referenced to this Library\r
         #  Only Library has this attribute\r
-        self._ReferenceModules        = []        \r
-        \r
+        self._ReferenceModules        = []\r
+\r
         ## Store the FixedAtBuild Pcds\r
-        #  \r
+        #\r
         self._FixedAtBuildPcds         = []\r
         self.ConstPcd                  = {}\r
-        return True\r
 \r
     def __repr__(self):\r
         return "%s [%s]" % (self.MetaFile, self.Arch)\r
@@ -2884,8 +2759,8 @@ class ModuleAutoGen(AutoGen):
                 continue\r
             if Pcd not in self._FixedAtBuildPcds:\r
                 self._FixedAtBuildPcds.append(Pcd)\r
-                \r
-        return self._FixedAtBuildPcds        \r
+\r
+        return self._FixedAtBuildPcds\r
 \r
     def _GetUniqueBaseName(self):\r
         BaseName = self.Name\r
@@ -2905,7 +2780,7 @@ class ModuleAutoGen(AutoGen):
             self._Macro = OrderedDict()\r
             self._Macro["WORKSPACE"             ] = self.WorkspaceDir\r
             self._Macro["MODULE_NAME"           ] = self.Name\r
-            self._Macro["MODULE_NAME_GUID"      ] = self._GetUniqueBaseName()\r
+            self._Macro["MODULE_NAME_GUID"      ] = self.UniqueBaseName\r
             self._Macro["MODULE_GUID"           ] = self.Guid\r
             self._Macro["MODULE_VERSION"        ] = self.Version\r
             self._Macro["MODULE_TYPE"           ] = self.ModuleType\r
@@ -2998,10 +2873,7 @@ class ModuleAutoGen(AutoGen):
     ## Check if the module is library or not\r
     def _IsLibrary(self):\r
         if self._LibraryFlag is None:\r
-            if self.Module.LibraryClass is not None and self.Module.LibraryClass != []:\r
-                self._LibraryFlag = True\r
-            else:\r
-                self._LibraryFlag = False\r
+            self._LibraryFlag = True if self.Module.LibraryClass else False\r
         return self._LibraryFlag\r
 \r
     ## Check if the module is binary module or not\r
@@ -3031,7 +2903,7 @@ class ModuleAutoGen(AutoGen):
     def _GetFfsOutputDir(self):\r
         if self._FfsOutputDir is None:\r
             if GlobalData.gFdfParser is not None:\r
-                self._FfsOutputDir = path.join(self.PlatformInfo.BuildDir, "FV", "Ffs", self.Guid + self.Name)\r
+                self._FfsOutputDir = path.join(self.PlatformInfo.BuildDir, TAB_FV_DIRECTORY, "Ffs", self.Guid + self.Name)\r
             else:\r
                 self._FfsOutputDir = ''\r
         return self._FfsOutputDir\r
@@ -3087,7 +2959,7 @@ class ModuleAutoGen(AutoGen):
                     continue\r
                 PackageList.append(Package)\r
         return PackageList\r
-    \r
+\r
     ## Get the depex string\r
     #\r
     # @return : a string contain all depex expresion.\r
@@ -3116,18 +2988,18 @@ class ModuleAutoGen(AutoGen):
                           (Arch.upper() == self.Arch.upper() and \\r
                           ModuleType.upper() in [TAB_ARCH_COMMON, self.ModuleType.upper()]):\r
                             DepexList.append({(Arch, ModuleType): DepexExpr})\r
-        \r
+\r
         #the type of build module is USER_DEFINED.\r
         if self.ModuleType.upper() == SUP_MODULE_USER_DEFINED:\r
             for Depex in DepexList:\r
                 for key in Depex:\r
                     DepexStr += '[Depex.%s.%s]\n' % key\r
-                    DepexStr += '\n'.join(['# '+ val for val in Depex[key]])\r
+                    DepexStr += '\n'.join('# '+ val for val in Depex[key])\r
                     DepexStr += '\n\n'\r
             if not DepexStr:\r
                 return '[Depex.%s]\n' % self.Arch\r
             return DepexStr\r
-        \r
+\r
         #the type of build module not is USER_DEFINED.\r
         Count = 0\r
         for Depex in DepexList:\r
@@ -3136,7 +3008,7 @@ class ModuleAutoGen(AutoGen):
                 DepexStr += ' AND '\r
             DepexStr += '('\r
             for D in Depex.values():\r
-                DepexStr += ' '.join([val for val in D])\r
+                DepexStr += ' '.join(val for val in D)\r
             Index = DepexStr.find('END')\r
             if Index > -1 and Index == len(DepexStr) - 3:\r
                 DepexStr = DepexStr[:-3]\r
@@ -3147,21 +3019,21 @@ class ModuleAutoGen(AutoGen):
         if not DepexStr:\r
             return '[Depex.%s]\n' % self.Arch\r
         return '[Depex.%s]\n#  ' % self.Arch + DepexStr\r
-    \r
+\r
     ## Merge dependency expression\r
     #\r
     #   @retval     list    The token list of the dependency expression after parsed\r
     #\r
     def _GetDepexTokenList(self):\r
-        if self._DepexList is None:\r
-            self._DepexList = {}\r
+        if self._DepexDict is None:\r
+            self._DepexDict = {}\r
             if self.DxsFile or self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:\r
-                return self._DepexList\r
+                return self._DepexDict\r
 \r
-            self._DepexList[self.ModuleType] = []\r
+            self._DepexDict[self.ModuleType] = []\r
 \r
-            for ModuleType in self._DepexList:\r
-                DepexList = self._DepexList[ModuleType]\r
+            for ModuleType in self._DepexDict:\r
+                DepexList = self._DepexDict[ModuleType]\r
                 #\r
                 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion\r
                 #\r
@@ -3182,43 +3054,43 @@ class ModuleAutoGen(AutoGen):
                         break\r
                 if len(DepexList) > 0:\r
                     EdkLogger.verbose('')\r
-        return self._DepexList\r
+        return self._DepexDict\r
 \r
     ## Merge dependency expression\r
     #\r
     #   @retval     list    The token list of the dependency expression after parsed\r
     #\r
     def _GetDepexExpressionTokenList(self):\r
-        if self._DepexExpressionList is None:\r
-            self._DepexExpressionList = {}\r
+        if self._DepexExpressionDict is None:\r
+            self._DepexExpressionDict = {}\r
             if self.DxsFile or self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:\r
-                return self._DepexExpressionList\r
+                return self._DepexExpressionDict\r
 \r
-            self._DepexExpressionList[self.ModuleType] = ''\r
+            self._DepexExpressionDict[self.ModuleType] = ''\r
 \r
-            for ModuleType in self._DepexExpressionList:\r
-                DepexExpressionList = self._DepexExpressionList[ModuleType]\r
+            for ModuleType in self._DepexExpressionDict:\r
+                DepexExpressionString = self._DepexExpressionDict[ModuleType]\r
                 #\r
                 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion\r
                 #\r
                 for M in [self.Module] + self.DependentLibraryList:\r
                     Inherited = False\r
                     for D in M.DepexExpression[self.Arch, ModuleType]:\r
-                        if DepexExpressionList != '':\r
-                            DepexExpressionList += ' AND '\r
-                        DepexExpressionList += '('\r
-                        DepexExpressionList += D\r
-                        DepexExpressionList = DepexExpressionList.rstrip('END').strip()\r
-                        DepexExpressionList += ')'\r
+                        if DepexExpressionString != '':\r
+                            DepexExpressionString += ' AND '\r
+                        DepexExpressionString += '('\r
+                        DepexExpressionString += D\r
+                        DepexExpressionString = DepexExpressionString.rstrip('END').strip()\r
+                        DepexExpressionString += ')'\r
                         Inherited = True\r
                     if Inherited:\r
-                        EdkLogger.verbose("DEPEX[%s] (+%s) = %s" % (self.Name, M.BaseName, DepexExpressionList))\r
-                    if 'BEFORE' in DepexExpressionList or 'AFTER' in DepexExpressionList:\r
+                        EdkLogger.verbose("DEPEX[%s] (+%s) = %s" % (self.Name, M.BaseName, DepexExpressionString))\r
+                    if 'BEFORE' in DepexExpressionString or 'AFTER' in DepexExpressionString:\r
                         break\r
-                if len(DepexExpressionList) > 0:\r
+                if len(DepexExpressionString) > 0:\r
                     EdkLogger.verbose('')\r
-                self._DepexExpressionList[ModuleType] = DepexExpressionList\r
-        return self._DepexExpressionList\r
+                self._DepexExpressionDict[ModuleType] = DepexExpressionString\r
+        return self._DepexExpressionDict\r
 \r
     # Get the tiano core user extension, it is contain dependent library.\r
     # @retval: a list contain tiano core userextension.\r
@@ -3283,15 +3155,14 @@ class ModuleAutoGen(AutoGen):
                 #\r
                 self._BuildOptionIncPathList = []\r
                 return self._BuildOptionIncPathList\r
-            \r
+\r
             BuildOptionIncPathList = []\r
             for Tool in ('CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'ASM'):\r
-                Attr = 'FLAGS'\r
                 try:\r
-                    FlagOption = self.BuildOption[Tool][Attr]\r
+                    FlagOption = self.BuildOption[Tool]['FLAGS']\r
                 except KeyError:\r
                     FlagOption = ''\r
-                \r
+\r
                 if self.PlatformInfo.ToolChainFamily != 'RVCT':\r
                     IncPathList = [NormPath(Path, self.Macros) for Path in BuildOptIncludeRegEx.findall(FlagOption)]\r
                 else:\r
@@ -3301,13 +3172,13 @@ class ModuleAutoGen(AutoGen):
                     IncPathList = []\r
                     for Path in BuildOptIncludeRegEx.findall(FlagOption):\r
                         PathList = GetSplitList(Path, TAB_COMMA_SPLIT)\r
-                        IncPathList += [NormPath(PathEntry, self.Macros) for PathEntry in PathList]\r
+                        IncPathList.extend(NormPath(PathEntry, self.Macros) for PathEntry in PathList)\r
 \r
                 #\r
-                # EDK II modules must not reference header files outside of the packages they depend on or \r
+                # EDK II modules must not reference header files outside of the packages they depend on or\r
                 # within the module's directory tree. Report error if violation.\r
                 #\r
-                if self.AutoGenVersion >= 0x00010005 and len(IncPathList) > 0:\r
+                if self.AutoGenVersion >= 0x00010005:\r
                     for Path in IncPathList:\r
                         if (Path not in self.IncludePathList) and (CommonPath([Path, self.MetaFile.Dir]) != self.MetaFile.Dir):\r
                             ErrMsg = "The include directory for the EDK II module in this line is invalid %s specified in %s FLAGS '%s'" % (Path, Tool, FlagOption)\r
@@ -3316,13 +3187,13 @@ class ModuleAutoGen(AutoGen):
                                             ExtraData=ErrMsg,\r
                                             File=str(self.MetaFile))\r
 \r
-                \r
+\r
                 BuildOptionIncPathList += IncPathList\r
-            \r
+\r
             self._BuildOptionIncPathList = BuildOptionIncPathList\r
-        \r
+\r
         return self._BuildOptionIncPathList\r
-        \r
+\r
     ## Return a list of files which can be built from source\r
     #\r
     #  What kind of files can be built is determined by build rules in\r
@@ -3331,14 +3202,16 @@ class ModuleAutoGen(AutoGen):
     def _GetSourceFileList(self):\r
         if self._SourceFileList is None:\r
             self._SourceFileList = []\r
+            ToolChainTagSet = {"", "*", self.ToolChain}\r
+            ToolChainFamilySet = {"", "*", self.ToolChainFamily, self.BuildRuleFamily}\r
             for F in self.Module.Sources:\r
                 # match tool chain\r
-                if F.TagName not in ("", "*", self.ToolChain):\r
+                if F.TagName not in ToolChainTagSet:\r
                     EdkLogger.debug(EdkLogger.DEBUG_9, "The toolchain [%s] for processing file [%s] is found, "\r
                                     "but [%s] is needed" % (F.TagName, str(F), self.ToolChain))\r
                     continue\r
                 # match tool chain family or build rule family\r
-                if F.ToolChainFamily not in ("", "*", self.ToolChainFamily, self.BuildRuleFamily):\r
+                if F.ToolChainFamily not in ToolChainFamilySet:\r
                     EdkLogger.debug(\r
                                 EdkLogger.DEBUG_0,\r
                                 "The file [%s] must be built by tools of [%s], " \\r
@@ -3374,7 +3247,7 @@ class ModuleAutoGen(AutoGen):
                 Order_Dict[F].sort(key=lambda i: self.BuildRuleOrder.index(i))\r
                 for Ext in Order_Dict[F][1:]:\r
                     RemoveList.append(F + Ext)\r
-                   \r
+\r
         for item in RemoveList:\r
             FileList.remove(item)\r
 \r
@@ -3461,7 +3334,7 @@ class ModuleAutoGen(AutoGen):
         if not os.path.exists(SubDirectory):\r
             CreateDirectory(SubDirectory)\r
         LastTarget = None\r
-        RuleChain = []\r
+        RuleChain = set()\r
         SourceList = [File]\r
         Index = 0\r
         #\r
@@ -3518,7 +3391,7 @@ class ModuleAutoGen(AutoGen):
             if FileType in RuleChain:\r
                 break\r
 \r
-            RuleChain.append(FileType)\r
+            RuleChain.add(FileType)\r
             SourceList.extend(Target.Outputs)\r
             LastTarget = Target\r
             FileType = TAB_UNKNOWN_FILE\r
@@ -3566,8 +3439,8 @@ class ModuleAutoGen(AutoGen):
     def _GetAutoGenFileList(self):\r
         UniStringAutoGenC = True\r
         IdfStringAutoGenC = True\r
-        UniStringBinBuffer = StringIO()\r
-        IdfGenBinBuffer = StringIO()\r
+        UniStringBinBuffer = BytesIO()\r
+        IdfGenBinBuffer = BytesIO()\r
         if self.BuildType == 'UEFI_HII':\r
             UniStringAutoGenC = False\r
             IdfStringAutoGenC = False\r
@@ -3627,12 +3500,6 @@ class ModuleAutoGen(AutoGen):
                     self._DependentLibraryList = self.PlatformInfo.ApplyLibraryInstance(self.Module)\r
         return self._DependentLibraryList\r
 \r
-    @staticmethod\r
-    def UpdateComments(Recver, Src):\r
-        for Key in Src:\r
-            if Key not in Recver:\r
-                Recver[Key] = []\r
-            Recver[Key].extend(Src[Key])\r
     ## Get the list of PCDs from current module\r
     #\r
     #   @retval     list                    The list of PCD\r
@@ -3641,7 +3508,7 @@ class ModuleAutoGen(AutoGen):
         if self._ModulePcdList is None:\r
             # apply PCD settings from platform\r
             self._ModulePcdList = self.PlatformInfo.ApplyPcdSetting(self.Module, self.Module.Pcds)\r
-            self.UpdateComments(self._PcdComments, self.Module.PcdComments)\r
+            ExtendCopyDictionaryLists(self._PcdComments, self.Module.PcdComments)\r
         return self._ModulePcdList\r
 \r
     ## Get the list of PCDs from dependent libraries\r
@@ -3653,15 +3520,17 @@ class ModuleAutoGen(AutoGen):
             Pcds = OrderedDict()\r
             if not self.IsLibrary:\r
                 # get PCDs from dependent libraries\r
+                self._LibraryPcdList = []\r
                 for Library in self.DependentLibraryList:\r
-                    self.UpdateComments(self._PcdComments, Library.PcdComments)\r
+                    PcdsInLibrary = OrderedDict()\r
+                    ExtendCopyDictionaryLists(self._PcdComments, Library.PcdComments)\r
                     for Key in Library.Pcds:\r
                         # skip duplicated PCDs\r
                         if Key in self.Module.Pcds or Key in Pcds:\r
                             continue\r
                         Pcds[Key] = copy.copy(Library.Pcds[Key])\r
-                # apply PCD settings from platform\r
-                self._LibraryPcdList = self.PlatformInfo.ApplyPcdSetting(self.Module, Pcds)\r
+                        PcdsInLibrary[Key] = Pcds[Key]\r
+                    self._LibraryPcdList.extend(self.PlatformInfo.ApplyPcdSetting(self.Module, PcdsInLibrary, Library=Library))\r
             else:\r
                 self._LibraryPcdList = []\r
         return self._LibraryPcdList\r
@@ -3676,8 +3545,8 @@ class ModuleAutoGen(AutoGen):
             self._GuidList.update(self.Module.Guids)\r
             for Library in self.DependentLibraryList:\r
                 self._GuidList.update(Library.Guids)\r
-                self.UpdateComments(self._GuidComments, Library.GuidComments)\r
-            self.UpdateComments(self._GuidComments, self.Module.GuidComments)\r
+                ExtendCopyDictionaryLists(self._GuidComments, Library.GuidComments)\r
+            ExtendCopyDictionaryLists(self._GuidComments, self.Module.GuidComments)\r
         return self._GuidList\r
 \r
     def GetGuidsUsedByPcd(self):\r
@@ -3697,8 +3566,8 @@ class ModuleAutoGen(AutoGen):
             self._ProtocolList.update(self.Module.Protocols)\r
             for Library in self.DependentLibraryList:\r
                 self._ProtocolList.update(Library.Protocols)\r
-                self.UpdateComments(self._ProtocolComments, Library.ProtocolComments)\r
-            self.UpdateComments(self._ProtocolComments, self.Module.ProtocolComments)\r
+                ExtendCopyDictionaryLists(self._ProtocolComments, Library.ProtocolComments)\r
+            ExtendCopyDictionaryLists(self._ProtocolComments, self.Module.ProtocolComments)\r
         return self._ProtocolList\r
 \r
     ## Get the PPI value mapping\r
@@ -3711,8 +3580,8 @@ class ModuleAutoGen(AutoGen):
             self._PpiList.update(self.Module.Ppis)\r
             for Library in self.DependentLibraryList:\r
                 self._PpiList.update(Library.Ppis)\r
-                self.UpdateComments(self._PpiComments, Library.PpiComments)\r
-            self.UpdateComments(self._PpiComments, self.Module.PpiComments)\r
+                ExtendCopyDictionaryLists(self._PpiComments, Library.PpiComments)\r
+            ExtendCopyDictionaryLists(self._PpiComments, self.Module.PpiComments)\r
         return self._PpiList\r
 \r
     ## Get the list of include search path\r
@@ -3750,11 +3619,7 @@ class ModuleAutoGen(AutoGen):
         return self._IncludePathList\r
 \r
     def _GetIncludePathLength(self):\r
-        self._IncludePathLength = 0\r
-        if self._IncludePathList:\r
-            for inc in self._IncludePathList:\r
-                self._IncludePathLength += len(' ' + inc)\r
-        return self._IncludePathLength\r
+        return sum(len(inc)+1 for inc in self._IncludePathList)\r
 \r
     ## Get HII EX PCDs which maybe used by VFR\r
     #\r
@@ -3808,12 +3673,11 @@ class ModuleAutoGen(AutoGen):
         for Pcd in self.PlatformInfo.Platform.Pcds.values():\r
             if Pcd.Type != TAB_PCDS_DYNAMIC_EX_HII:\r
                 continue\r
-            for SkuName in Pcd.SkuInfoList:\r
-                SkuInfo = Pcd.SkuInfoList[SkuName]\r
-                Name = ConvertStringToByteArray(SkuInfo.VariableName)\r
+            for SkuInfo in Pcd.SkuInfoList.values():\r
                 Value = GuidValue(SkuInfo.VariableGuid, self.PlatformInfo.PackageList, self.MetaFile.Path)\r
                 if not Value:\r
                     continue\r
+                Name = ConvertStringToByteArray(SkuInfo.VariableName)\r
                 Guid = GuidStructureStringToGuidString(Value)\r
                 if (Name, Guid) in NameGuids and Pcd not in HiiExPcds:\r
                     HiiExPcds.append(Pcd)\r
@@ -3826,16 +3690,16 @@ class ModuleAutoGen(AutoGen):
         for SourceFile in self.Module.Sources:\r
             if SourceFile.Type.upper() == ".VFR" :\r
                 #\r
-                # search the .map file to find the offset of vfr binary in the PE32+/TE file. \r
+                # search the .map file to find the offset of vfr binary in the PE32+/TE file.\r
                 #\r
                 VfrUniBaseName[SourceFile.BaseName] = (SourceFile.BaseName + "Bin")\r
-            if SourceFile.Type.upper() == ".UNI" :\r
+            elif SourceFile.Type.upper() == ".UNI" :\r
                 #\r
-                # search the .map file to find the offset of Uni strings binary in the PE32+/TE file. \r
+                # search the .map file to find the offset of Uni strings binary in the PE32+/TE file.\r
                 #\r
                 VfrUniBaseName["UniOffsetName"] = (self.Name + "Strings")\r
 \r
-        if len(VfrUniBaseName) == 0:\r
+        if not VfrUniBaseName:\r
             return None\r
         MapFileName = os.path.join(self.OutputDir, self.Name + ".map")\r
         EfiFileName = os.path.join(self.OutputDir, self.Name + ".efi")\r
@@ -3849,10 +3713,10 @@ class ModuleAutoGen(AutoGen):
         try:\r
             fInputfile = open(UniVfrOffsetFileName, "wb+", 0)\r
         except:\r
-            EdkLogger.error("build", FILE_OPEN_FAILURE, "File open failed for %s" % UniVfrOffsetFileName,None)\r
+            EdkLogger.error("build", FILE_OPEN_FAILURE, "File open failed for %s" % UniVfrOffsetFileName, None)\r
 \r
-        # Use a instance of StringIO to cache data\r
-        fStringIO = StringIO('')  \r
+        # Use a instance of BytesIO to cache data\r
+        fStringIO = BytesIO('')\r
 \r
         for Item in VfrUniOffsetList:\r
             if (Item[0].find("Strings") != -1):\r
@@ -3863,7 +3727,7 @@ class ModuleAutoGen(AutoGen):
                 #\r
                 UniGuid = [0xe0, 0xc5, 0x13, 0x89, 0xf6, 0x33, 0x86, 0x4d, 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66]\r
                 UniGuid = [chr(ItemGuid) for ItemGuid in UniGuid]\r
-                fStringIO.write(''.join(UniGuid))            \r
+                fStringIO.write(''.join(UniGuid))\r
                 UniValue = pack ('Q', int (Item[1], 16))\r
                 fStringIO.write (UniValue)\r
             else:\r
@@ -3874,17 +3738,17 @@ class ModuleAutoGen(AutoGen):
                 #\r
                 VfrGuid = [0xb4, 0x7c, 0xbc, 0xd0, 0x47, 0x6a, 0x5f, 0x49, 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2]\r
                 VfrGuid = [chr(ItemGuid) for ItemGuid in VfrGuid]\r
-                fStringIO.write(''.join(VfrGuid))                   \r
+                fStringIO.write(''.join(VfrGuid))\r
                 VfrValue = pack ('Q', int (Item[1], 16))\r
                 fStringIO.write (VfrValue)\r
         #\r
         # write data into file.\r
         #\r
-        try :  \r
+        try :\r
             fInputfile.write (fStringIO.getvalue())\r
         except:\r
             EdkLogger.error("build", FILE_WRITE_FAILURE, "Write data to file %s failed, please check whether the "\r
-                            "file been locked or using by other applications." %UniVfrOffsetFileName,None)\r
+                            "file been locked or using by other applications." %UniVfrOffsetFileName, None)\r
 \r
         fStringIO.close ()\r
         fInputfile.close ()\r
@@ -3894,22 +3758,21 @@ class ModuleAutoGen(AutoGen):
     #\r
     def CreateAsBuiltInf(self, IsOnlyCopy = False):\r
         self.OutputFile = set()\r
-        if IsOnlyCopy:\r
-            if GlobalData.gBinCacheDest:\r
-                self.CopyModuleToCache()\r
-                return\r
+        if IsOnlyCopy and GlobalData.gBinCacheDest:\r
+            self.CopyModuleToCache()\r
+            return\r
 \r
         if self.IsAsBuiltInfCreated:\r
             return\r
-            \r
+\r
         # Skip the following code for EDK I inf\r
         if self.AutoGenVersion < 0x00010005:\r
             return\r
-            \r
+\r
         # Skip the following code for libraries\r
         if self.IsLibrary:\r
             return\r
-            \r
+\r
         # Skip the following code for modules with no source files\r
         if not self.SourceFileList:\r
             return\r
@@ -3917,7 +3780,7 @@ class ModuleAutoGen(AutoGen):
         # Skip the following code for modules without any binary files\r
         if self.BinaryFileList:\r
             return\r
-            \r
+\r
         ### TODO: How to handles mixed source and binary modules\r
 \r
         # Find all DynamicEx and PatchableInModule PCDs used by this module and dependent libraries\r
@@ -3929,11 +3792,11 @@ class ModuleAutoGen(AutoGen):
         PcdTokenSpaceList = []\r
         for Pcd in self.ModulePcdList + self.LibraryPcdList:\r
             if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:\r
-                PatchablePcds += [Pcd]\r
+                PatchablePcds.append(Pcd)\r
                 PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, TAB_PCDS_PATCHABLE_IN_MODULE))\r
-            elif Pcd.Type in GenC.gDynamicExPcd:\r
+            elif Pcd.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
                 if Pcd not in Pcds:\r
-                    Pcds += [Pcd]\r
+                    Pcds.append(Pcd)\r
                     PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC_EX))\r
                     PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC))\r
                     PcdTokenSpaceList.append(Pcd.TokenSpaceGuidCName)\r
@@ -3953,10 +3816,11 @@ class ModuleAutoGen(AutoGen):
             for Index in range(len(BeChecked)):\r
                 for Item in CheckList[Index]:\r
                     if Item in BeChecked[Index]:\r
-                        Packages += [Package]\r
+                        Packages.append(Package)\r
                         Found = True\r
                         break\r
-                if Found: break\r
+                if Found:\r
+                    break\r
 \r
         VfrPcds = self._GetPcdsMaybeUsedByVfr()\r
         for Pkg in self.PlatformInfo.PackageList:\r
@@ -3965,17 +3829,11 @@ class ModuleAutoGen(AutoGen):
             for VfrPcd in VfrPcds:\r
                 if ((VfrPcd.TokenCName, VfrPcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC_EX) in Pkg.Pcds or\r
                     (VfrPcd.TokenCName, VfrPcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC) in Pkg.Pcds):\r
-                    Packages += [Pkg]\r
+                    Packages.append(Pkg)\r
                     break\r
 \r
-        ModuleType = self.ModuleType\r
-        if ModuleType == SUP_MODULE_UEFI_DRIVER and self.DepexGenerated:\r
-            ModuleType = SUP_MODULE_DXE_DRIVER\r
-\r
-        DriverType = ''\r
-        if self.PcdIsDriver != '':\r
-            DriverType = self.PcdIsDriver\r
-\r
+        ModuleType = SUP_MODULE_DXE_DRIVER if self.ModuleType == SUP_MODULE_UEFI_DRIVER and self.DepexGenerated else self.ModuleType\r
+        DriverType = self.PcdIsDriver if self.PcdIsDriver else ''\r
         Guid = self.Guid\r
         MDefs = self.Module.Defines\r
 \r
@@ -4001,7 +3859,7 @@ class ModuleAutoGen(AutoGen):
           'module_uefi_hii_resource_section'  : [MDefs['UEFI_HII_RESOURCE_SECTION']] if 'UEFI_HII_RESOURCE_SECTION' in MDefs else [],\r
           'module_uni_file'                   : [MDefs['MODULE_UNI_FILE']] if 'MODULE_UNI_FILE' in MDefs else [],\r
           'module_arch'                       : self.Arch,\r
-          'package_item'                      : ['%s' % (Package.MetaFile.File.replace('\\', '/')) for Package in Packages],\r
+          'package_item'                      : [Package.MetaFile.File.replace('\\', '/') for Package in Packages],\r
           'binary_item'                       : [],\r
           'patchablepcd_item'                 : [],\r
           'pcd_item'                          : [],\r
@@ -4023,12 +3881,12 @@ class ModuleAutoGen(AutoGen):
             AsBuiltInfDict['module_inf_version'] = gInfSpecVersion\r
 \r
         if DriverType:\r
-            AsBuiltInfDict['pcd_is_driver_string'] += [DriverType]\r
+            AsBuiltInfDict['pcd_is_driver_string'].append(DriverType)\r
 \r
         if 'UEFI_SPECIFICATION_VERSION' in self.Specification:\r
-            AsBuiltInfDict['module_uefi_specification_version'] += [self.Specification['UEFI_SPECIFICATION_VERSION']]\r
+            AsBuiltInfDict['module_uefi_specification_version'].append(self.Specification['UEFI_SPECIFICATION_VERSION'])\r
         if 'PI_SPECIFICATION_VERSION' in self.Specification:\r
-            AsBuiltInfDict['module_pi_specification_version'] += [self.Specification['PI_SPECIFICATION_VERSION']]\r
+            AsBuiltInfDict['module_pi_specification_version'].append(self.Specification['PI_SPECIFICATION_VERSION'])\r
 \r
         OutputDir = self.OutputDir.replace('\\', '/').strip('/')\r
         DebugDir = self.DebugDir.replace('\\', '/').strip('/')\r
@@ -4038,31 +3896,31 @@ class ModuleAutoGen(AutoGen):
             if os.path.isabs(File):\r
                 File = File.replace('\\', '/').strip('/').replace(OutputDir, '').strip('/')\r
             if Item.Target.Ext.lower() == '.aml':\r
-                AsBuiltInfDict['binary_item'] += ['ASL|' + File]\r
+                AsBuiltInfDict['binary_item'].append('ASL|' + File)\r
             elif Item.Target.Ext.lower() == '.acpi':\r
-                AsBuiltInfDict['binary_item'] += ['ACPI|' + File]\r
+                AsBuiltInfDict['binary_item'].append('ACPI|' + File)\r
             elif Item.Target.Ext.lower() == '.efi':\r
-                AsBuiltInfDict['binary_item'] += ['PE32|' + self.Name + '.efi']\r
+                AsBuiltInfDict['binary_item'].append('PE32|' + self.Name + '.efi')\r
             else:\r
-                AsBuiltInfDict['binary_item'] += ['BIN|' + File]\r
+                AsBuiltInfDict['binary_item'].append('BIN|' + File)\r
         if self.DepexGenerated:\r
             self.OutputFile.add(self.Name + '.depex')\r
             if self.ModuleType in [SUP_MODULE_PEIM]:\r
-                AsBuiltInfDict['binary_item'] += ['PEI_DEPEX|' + self.Name + '.depex']\r
-            if self.ModuleType in [SUP_MODULE_DXE_DRIVER, SUP_MODULE_DXE_RUNTIME_DRIVER, SUP_MODULE_DXE_SAL_DRIVER, SUP_MODULE_UEFI_DRIVER]:\r
-                AsBuiltInfDict['binary_item'] += ['DXE_DEPEX|' + self.Name + '.depex']\r
-            if self.ModuleType in [SUP_MODULE_DXE_SMM_DRIVER]:\r
-                AsBuiltInfDict['binary_item'] += ['SMM_DEPEX|' + self.Name + '.depex']\r
+                AsBuiltInfDict['binary_item'].append('PEI_DEPEX|' + self.Name + '.depex')\r
+            elif self.ModuleType in [SUP_MODULE_DXE_DRIVER, SUP_MODULE_DXE_RUNTIME_DRIVER, SUP_MODULE_DXE_SAL_DRIVER, SUP_MODULE_UEFI_DRIVER]:\r
+                AsBuiltInfDict['binary_item'].append('DXE_DEPEX|' + self.Name + '.depex')\r
+            elif self.ModuleType in [SUP_MODULE_DXE_SMM_DRIVER]:\r
+                AsBuiltInfDict['binary_item'].append('SMM_DEPEX|' + self.Name + '.depex')\r
 \r
         Bin = self._GenOffsetBin()\r
         if Bin:\r
-            AsBuiltInfDict['binary_item'] += ['BIN|%s' % Bin]\r
+            AsBuiltInfDict['binary_item'].append('BIN|%s' % Bin)\r
             self.OutputFile.add(Bin)\r
 \r
         for Root, Dirs, Files in os.walk(OutputDir):\r
             for File in Files:\r
                 if File.lower().endswith('.pdb'):\r
-                    AsBuiltInfDict['binary_item'] += ['DISPOSABLE|' + File]\r
+                    AsBuiltInfDict['binary_item'].append('DISPOSABLE|' + File)\r
                     self.OutputFile.add(File)\r
         HeaderComments = self.Module.HeaderComments\r
         StartPos = 0\r
@@ -4081,12 +3939,8 @@ class ModuleAutoGen(AutoGen):
         ]\r
         for Item in GenList:\r
             for CName in Item[0]:\r
-                Comments = ''\r
-                if CName in Item[1]:\r
-                    Comments = '\n  '.join(Item[1][CName])\r
-                Entry = CName\r
-                if Comments:\r
-                    Entry = Comments + '\n  ' + CName\r
+                Comments = '\n  '.join(Item[1][CName]) if CName in Item[1] else ''\r
+                Entry = Comments + '\n  ' + CName if Comments else CName\r
                 AsBuiltInfDict[Item[2]].append(Entry)\r
         PatchList = parsePcdInfoFromMapFile(\r
                             os.path.join(self.OutputDir, self.Name + '.map'),\r
@@ -4175,12 +4029,9 @@ class ModuleAutoGen(AutoGen):
                     PcdItem = PcdComments + '\n  ' + PcdItem\r
                 AsBuiltInfDict['patchablepcd_item'].append(PcdItem)\r
 \r
-        HiiPcds = set()\r
         for Pcd in Pcds + VfrPcds:\r
-            PcdComments = ''\r
             PcdCommentList = []\r
             HiiInfo = ''\r
-            SkuId = ''\r
             TokenCName = Pcd.TokenCName\r
             for PcdItem in GlobalData.MixedPcd:\r
                 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:\r
@@ -4189,16 +4040,8 @@ class ModuleAutoGen(AutoGen):
             if Pcd.Type == TAB_PCDS_DYNAMIC_EX_HII:\r
                 for SkuName in Pcd.SkuInfoList:\r
                     SkuInfo = Pcd.SkuInfoList[SkuName]\r
-                    SkuId = SkuInfo.SkuId\r
                     HiiInfo = '## %s|%s|%s' % (SkuInfo.VariableName, SkuInfo.VariableGuid, SkuInfo.VariableOffset)\r
                     break\r
-            if SkuId:\r
-                #\r
-                # Don't generate duplicated HII PCD\r
-                #\r
-                if (SkuId, Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in HiiPcds:\r
-                    continue\r
-                HiiPcds.add((SkuId, Pcd.TokenSpaceGuidCName, Pcd.TokenCName))\r
             if (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in self._PcdComments:\r
                 PcdCommentList = self._PcdComments[Pcd.TokenSpaceGuidCName, Pcd.TokenCName][:]\r
             if HiiInfo:\r
@@ -4211,22 +4054,22 @@ class ModuleAutoGen(AutoGen):
                             UsageIndex = Index\r
                             break\r
                 if UsageIndex != -1:\r
-                    PcdCommentList[UsageIndex] = '## %s %s %s' % (UsageStr, HiiInfo, PcdCommentList[UsageIndex].replace(UsageStr, '')) \r
+                    PcdCommentList[UsageIndex] = '## %s %s %s' % (UsageStr, HiiInfo, PcdCommentList[UsageIndex].replace(UsageStr, ''))\r
                 else:\r
                     PcdCommentList.append('## UNDEFINED ' + HiiInfo)\r
             PcdComments = '\n  '.join(PcdCommentList)\r
             PcdEntry = Pcd.TokenSpaceGuidCName + '.' + TokenCName\r
             if PcdComments:\r
                 PcdEntry = PcdComments + '\n  ' + PcdEntry\r
-            AsBuiltInfDict['pcd_item'] += [PcdEntry]\r
+            AsBuiltInfDict['pcd_item'].append(PcdEntry)\r
         for Item in self.BuildOption:\r
             if 'FLAGS' in self.BuildOption[Item]:\r
-                AsBuiltInfDict['flags_item'] += ['%s:%s_%s_%s_%s_FLAGS = %s' % (self.ToolChainFamily, self.BuildTarget, self.ToolChain, self.Arch, Item, self.BuildOption[Item]['FLAGS'].strip())]\r
+                AsBuiltInfDict['flags_item'].append('%s:%s_%s_%s_%s_FLAGS = %s' % (self.ToolChainFamily, self.BuildTarget, self.ToolChain, self.Arch, Item, self.BuildOption[Item]['FLAGS'].strip()))\r
 \r
         # Generated LibraryClasses section in comments.\r
         for Library in self.LibraryAutoGenList:\r
-            AsBuiltInfDict['libraryclasses_item'] += [Library.MetaFile.File.replace('\\', '/')]\r
-        \r
+            AsBuiltInfDict['libraryclasses_item'].append(Library.MetaFile.File.replace('\\', '/'))\r
+\r
         # Generated UserExtensions TianoCore section.\r
         # All tianocore user extensions are copied.\r
         UserExtStr = ''\r
@@ -4238,16 +4081,14 @@ class ModuleAutoGen(AutoGen):
         AsBuiltInfDict['userextension_tianocore_item'] = UserExtStr\r
 \r
         # Generated depex expression section in comments.\r
-        AsBuiltInfDict['depexsection_item'] = ''\r
         DepexExpresion = self._GetDepexExpresionString()\r
-        if DepexExpresion:\r
-            AsBuiltInfDict['depexsection_item'] = DepexExpresion\r
-        \r
+        AsBuiltInfDict['depexsection_item'] = DepexExpresion if DepexExpresion else ''\r
+\r
         AsBuiltInf = TemplateString()\r
         AsBuiltInf.Append(gAsBuiltInfHeaderString.Replace(AsBuiltInfDict))\r
-        \r
+\r
         SaveFileOnChange(os.path.join(self.OutputDir, self.Name + '.inf'), str(AsBuiltInf), False)\r
-        \r
+\r
         self.IsAsBuiltInfCreated = True\r
         if GlobalData.gBinCacheDest:\r
             self.CopyModuleToCache()\r
@@ -4332,7 +4173,7 @@ class ModuleAutoGen(AutoGen):
     def CopyBinaryFiles(self):\r
         for File in self.Module.Binaries:\r
             SrcPath = File.Path\r
-            DstPath = os.path.join(self.OutputDir , os.path.basename(SrcPath))\r
+            DstPath = os.path.join(self.OutputDir, os.path.basename(SrcPath))\r
             CopyLongFilePath(SrcPath, DstPath)\r
     ## Create autogen code for the module and its dependent libraries\r
     #\r
@@ -4384,7 +4225,7 @@ class ModuleAutoGen(AutoGen):
             Dpx = GenDepex.DependencyExpression(self.DepexList[ModuleType], ModuleType, True)\r
             DpxFile = gAutoGenDepexFileName % {"module_name" : self.Name}\r
 \r
-            if len(Dpx.PostfixNotation) <> 0:\r
+            if len(Dpx.PostfixNotation) != 0:\r
                 self.DepexGenerated = True\r
 \r
             if Dpx.Generate(path.join(self.OutputDir, DpxFile)):\r
@@ -4432,13 +4273,13 @@ class ModuleAutoGen(AutoGen):
         m.update(GlobalData.gPlatformHash)\r
         # Add Package level hash\r
         if self.DependentPackageList:\r
-            for Pkg in self.DependentPackageList:\r
+            for Pkg in sorted(self.DependentPackageList, key=lambda x: x.PackageName):\r
                 if Pkg.PackageName in GlobalData.gPackageHash[self.Arch]:\r
                     m.update(GlobalData.gPackageHash[self.Arch][Pkg.PackageName])\r
 \r
         # Add Library hash\r
         if self.LibraryAutoGenList:\r
-            for Lib in self.LibraryAutoGenList:\r
+            for Lib in sorted(self.LibraryAutoGenList, key=lambda x: x.Name):\r
                 if Lib.Name not in GlobalData.gModuleHash[self.Arch]:\r
                     Lib.GenModuleHash()\r
                 m.update(GlobalData.gModuleHash[self.Arch][Lib.Name])\r
@@ -4450,7 +4291,7 @@ class ModuleAutoGen(AutoGen):
         m.update(Content)\r
         # Add Module's source files\r
         if self.SourceFileList:\r
-            for File in self.SourceFileList:\r
+            for File in sorted(self.SourceFileList, key=lambda x: str(x)):\r
                 f = open(str(File), 'r')\r
                 Content = f.read()\r
                 f.close()\r
@@ -4460,8 +4301,7 @@ class ModuleAutoGen(AutoGen):
         if self.Name not in GlobalData.gModuleHash[self.Arch]:\r
             GlobalData.gModuleHash[self.Arch][self.Name] = m.hexdigest()\r
         if GlobalData.gBinCacheSource:\r
-            CacheValid = self.AttemptModuleCacheCopy()\r
-            if CacheValid:\r
+            if self.AttemptModuleCacheCopy():\r
                 return False\r
         return SaveFileOnChange(ModuleHashFile, m.hexdigest(), True)\r
 \r
@@ -4469,11 +4309,14 @@ class ModuleAutoGen(AutoGen):
     def CanSkipbyHash(self):\r
         if GlobalData.gUseHashCache:\r
             return not self.GenModuleHash()\r
+        return False\r
 \r
     ## Decide whether we can skip the ModuleAutoGen process\r
     #  If any source file is newer than the module than we cannot skip\r
     #\r
     def CanSkip(self):\r
+        if self.MetaFile in GlobalData.gSikpAutoGenCache:\r
+            return True\r
         if not os.path.exists(self.GetTimeStampPath()):\r
             return False\r
         #last creation time of the module\r
@@ -4483,7 +4326,7 @@ class ModuleAutoGen(AutoGen):
         if SrcTimeStamp > DstTimeStamp:\r
             return False\r
 \r
-        with open(self.GetTimeStampPath(),'r') as f:\r
+        with open(self.GetTimeStampPath(), 'r') as f:\r
             for source in f:\r
                 source = source.rstrip('\n')\r
                 if not os.path.exists(source):\r
@@ -4492,6 +4335,7 @@ class ModuleAutoGen(AutoGen):
                     ModuleAutoGen.TimeDict[source] = os.stat(source)[8]\r
                 if ModuleAutoGen.TimeDict[source] > DstTimeStamp:\r
                     return False\r
+        GlobalData.gSikpAutoGenCache.add(self.MetaFile)\r
         return True\r
 \r
     def GetTimeStampPath(self):\r
@@ -4500,9 +4344,7 @@ class ModuleAutoGen(AutoGen):
         return self._TimeStampPath\r
     def CreateTimeStamp(self, Makefile):\r
 \r
-        FileSet = set()\r
-\r
-        FileSet.add (self.MetaFile.Path)\r
+        FileSet = {self.MetaFile.Path}\r
 \r
         for SourceFile in self.Module.Sources:\r
             FileSet.add (SourceFile.Path)\r
@@ -4517,7 +4359,7 @@ class ModuleAutoGen(AutoGen):
             os.remove (self.GetTimeStampPath())\r
         with open(self.GetTimeStampPath(), 'w+') as file:\r
             for f in FileSet:\r
-                print >> file, f\r
+                print(f, file=file)\r
 \r
     Module          = property(_GetModule)\r
     Name            = property(_GetBaseName)\r
@@ -4566,12 +4408,13 @@ class ModuleAutoGen(AutoGen):
     PpiList                 = property(_GetPpiList)\r
     DepexList               = property(_GetDepexTokenList)\r
     DxsFile                 = property(_GetDxsFile)\r
-    DepexExpressionList     = property(_GetDepexExpressionTokenList)\r
+    DepexExpressionDict     = property(_GetDepexExpressionTokenList)\r
     BuildOption             = property(_GetModuleBuildOption)\r
     BuildOptionIncPathList  = property(_GetBuildOptionIncPathList)\r
     BuildCommand            = property(_GetBuildCommand)\r
-    \r
+\r
     FixedAtBuildPcds         = property(_GetFixedAtBuildPcds)\r
+    UniqueBaseName          = property(_GetUniqueBaseName)\r
 \r
 # This acts like the main() function for the script, unless it is 'import'ed into another script.\r
 if __name__ == '__main__':\r