DxilLinker.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilLinker.cpp //
  4. // Copyright (C) Microsoft Corporation. All rights reserved. //
  5. // This file is distributed under the University of Illinois Open Source //
  6. // License. See LICENSE.TXT for details. //
  7. // //
  8. ///////////////////////////////////////////////////////////////////////////////
  9. #include "dxc/HLSL/DxilLinker.h"
  10. #include "dxc/HLSL/DxilCBuffer.h"
  11. #include "dxc/HLSL/DxilFunctionProps.h"
  12. #include "DxilEntryProps.h"
  13. #include "dxc/HLSL/DxilModule.h"
  14. #include "dxc/HLSL/DxilOperations.h"
  15. #include "dxc/HLSL/DxilResource.h"
  16. #include "dxc/HLSL/DxilSampler.h"
  17. #include "dxc/HLSL/DxilUtil.h"
  18. #include "dxc/Support/Global.h"
  19. #include "llvm/ADT/StringSet.h"
  20. #include "llvm/ADT/DenseSet.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/IRBuilder.h"
  23. #include "llvm/IR/Instructions.h"
  24. #include "llvm/IR/Module.h"
  25. #include "llvm/Transforms/Utils/Cloning.h"
  26. #include "llvm/ADT/StringMap.h"
  27. #include "llvm/ADT/SetVector.h"
  28. #include <memory>
  29. #include <vector>
  30. #include "dxc/HLSL/DxilContainer.h"
  31. #include "llvm/IR/DiagnosticPrinter.h"
  32. #include "llvm/IR/LLVMContext.h"
  33. #include "llvm/IR/DebugInfo.h"
  34. #include "dxc/HLSL/DxilGenerationPass.h"
  35. #include "llvm/IR/LegacyPassManager.h"
  36. #include "llvm/Transforms/IPO.h"
  37. #include "llvm/Transforms/Scalar.h"
  38. #include "dxc/HLSL/DxilExportMap.h"
  39. using namespace llvm;
  40. using namespace hlsl;
  41. namespace {
  42. void CollectUsedFunctions(Constant *C,
  43. std::unordered_set<Function *> &funcSet) {
  44. for (User *U : C->users()) {
  45. if (Instruction *I = dyn_cast<Instruction>(U)) {
  46. funcSet.insert(I->getParent()->getParent());
  47. } else {
  48. Constant *CU = cast<Constant>(U);
  49. CollectUsedFunctions(CU, funcSet);
  50. }
  51. }
  52. }
  53. template <class T>
  54. void AddResourceMap(
  55. const std::vector<std::unique_ptr<T>> &resTab, DXIL::ResourceClass resClass,
  56. std::unordered_map<const llvm::Constant *, DxilResourceBase *> &resMap,
  57. DxilModule &DM) {
  58. for (auto &Res : resTab) {
  59. resMap[Res->GetGlobalSymbol()] = Res.get();
  60. }
  61. }
  62. void CloneFunction(Function *F, Function *NewF, ValueToValueMapTy &vmap,
  63. hlsl::DxilTypeSystem *TypeSys = nullptr,
  64. hlsl::DxilTypeSystem *SrcTypeSys = nullptr) {
  65. SmallVector<ReturnInst *, 2> Returns;
  66. // Map params.
  67. auto paramIt = NewF->arg_begin();
  68. for (Argument &param : F->args()) {
  69. vmap[&param] = (paramIt++);
  70. }
  71. llvm::CloneFunctionInto(NewF, F, vmap, /*ModuleLevelChanges*/ true, Returns);
  72. if (TypeSys) {
  73. if (SrcTypeSys == nullptr)
  74. SrcTypeSys = TypeSys;
  75. TypeSys->CopyFunctionAnnotation(NewF, F, *SrcTypeSys);
  76. }
  77. // Remove params from vmap.
  78. for (Argument &param : F->args()) {
  79. vmap.erase(&param);
  80. }
  81. }
  82. } // namespace
  83. namespace {
  84. struct DxilFunctionLinkInfo {
  85. DxilFunctionLinkInfo(llvm::Function *F);
  86. llvm::Function *func;
  87. std::unordered_set<llvm::Function *> usedFunctions;
  88. std::unordered_set<llvm::GlobalVariable *> usedGVs;
  89. std::unordered_set<DxilResourceBase *> usedResources;
  90. };
  91. // Library to link.
  92. class DxilLib {
  93. public:
  94. DxilLib(std::unique_ptr<llvm::Module> pModule);
  95. virtual ~DxilLib() {}
  96. bool HasFunction(std::string &name);
  97. llvm::StringMap<std::unique_ptr<DxilFunctionLinkInfo>> &GetFunctionTable() {
  98. return m_functionNameMap;
  99. }
  100. bool IsInitFunc(llvm::Function *F);
  101. bool IsResourceGlobal(const llvm::Constant *GV);
  102. DxilResourceBase *GetResource(const llvm::Constant *GV);
  103. DxilModule &GetDxilModule() { return m_DM; }
  104. void LazyLoadFunction(Function *F);
  105. void BuildGlobalUsage();
  106. void CollectUsedInitFunctions(StringSet<> &addedFunctionSet,
  107. SmallVector<StringRef, 4> &workList);
  108. private:
  109. std::unique_ptr<llvm::Module> m_pModule;
  110. DxilModule &m_DM;
  111. // Map from name to Link info for extern functions.
  112. llvm::StringMap<std::unique_ptr<DxilFunctionLinkInfo>> m_functionNameMap;
  113. // Map from resource link global to resource.
  114. std::unordered_map<const llvm::Constant *, DxilResourceBase *> m_resourceMap;
  115. // Set of initialize functions for global variable.
  116. std::unordered_set<llvm::Function *> m_initFuncSet;
  117. };
  118. struct DxilLinkJob;
  119. class DxilLinkerImpl : public hlsl::DxilLinker {
  120. public:
  121. DxilLinkerImpl(LLVMContext &Ctx, unsigned valMajor, unsigned valMinor) : DxilLinker(Ctx, valMajor, valMinor) {}
  122. virtual ~DxilLinkerImpl() {}
  123. bool HasLibNameRegistered(StringRef name) override;
  124. bool RegisterLib(StringRef name, std::unique_ptr<llvm::Module> pModule,
  125. std::unique_ptr<llvm::Module> pDebugModule) override;
  126. bool AttachLib(StringRef name) override;
  127. bool DetachLib(StringRef name) override;
  128. void DetachAll() override;
  129. std::unique_ptr<llvm::Module>
  130. Link(StringRef entry, StringRef profile, dxilutil::ExportMap &exportMap) override;
  131. private:
  132. bool AttachLib(DxilLib *lib);
  133. bool DetachLib(DxilLib *lib);
  134. bool AddFunctions(SmallVector<StringRef, 4> &workList,
  135. DenseSet<DxilLib *> &libSet, StringSet<> &addedFunctionSet,
  136. DxilLinkJob &linkJob, bool bLazyLoadDone,
  137. bool bAllowFuncionDecls);
  138. // Attached libs to link.
  139. std::unordered_set<DxilLib *> m_attachedLibs;
  140. // Owner of all DxilLib.
  141. StringMap<std::unique_ptr<DxilLib>> m_LibMap;
  142. llvm::StringMap<std::pair<DxilFunctionLinkInfo *, DxilLib *>>
  143. m_functionNameMap;
  144. };
  145. } // namespace
  146. //------------------------------------------------------------------------------
  147. //
  148. // DxilFunctionLinkInfo methods.
  149. //
  150. DxilFunctionLinkInfo::DxilFunctionLinkInfo(Function *F) : func(F) {
  151. DXASSERT_NOMSG(F);
  152. }
  153. //------------------------------------------------------------------------------
  154. //
  155. // DxilLib methods.
  156. //
  157. DxilLib::DxilLib(std::unique_ptr<llvm::Module> pModule)
  158. : m_pModule(std::move(pModule)), m_DM(m_pModule->GetOrCreateDxilModule()) {
  159. Module &M = *m_pModule;
  160. const std::string &MID = M.getModuleIdentifier();
  161. // Collect function defines.
  162. for (Function &F : M.functions()) {
  163. if (F.isDeclaration())
  164. continue;
  165. if (F.getLinkage() == GlobalValue::LinkageTypes::InternalLinkage) {
  166. // Add prefix to internal function.
  167. F.setName(MID + F.getName());
  168. }
  169. m_functionNameMap[F.getName()] =
  170. llvm::make_unique<DxilFunctionLinkInfo>(&F);
  171. }
  172. // Update internal global name.
  173. for (GlobalVariable &GV : M.globals()) {
  174. if (GV.getLinkage() == GlobalValue::LinkageTypes::InternalLinkage) {
  175. // Add prefix to internal global.
  176. GV.setName(MID + GV.getName());
  177. }
  178. }
  179. }
  180. void DxilLib::LazyLoadFunction(Function *F) {
  181. DXASSERT(m_functionNameMap.count(F->getName()), "else invalid Function");
  182. DxilFunctionLinkInfo *linkInfo = m_functionNameMap[F->getName()].get();
  183. std::error_code EC = F->materialize();
  184. DXASSERT_LOCALVAR(EC, !EC, "else fail to materialize");
  185. // Build used functions for F.
  186. for (auto &BB : F->getBasicBlockList()) {
  187. for (auto &I : BB.getInstList()) {
  188. if (CallInst *CI = dyn_cast<CallInst>(&I)) {
  189. linkInfo->usedFunctions.insert(CI->getCalledFunction());
  190. }
  191. }
  192. }
  193. if (m_DM.HasDxilFunctionProps(F)) {
  194. DxilFunctionProps &props = m_DM.GetDxilFunctionProps(F);
  195. if (props.IsHS()) {
  196. // Add patch constant function to usedFunctions of entry.
  197. Function *patchConstantFunc = props.ShaderProps.HS.patchConstantFunc;
  198. linkInfo->usedFunctions.insert(patchConstantFunc);
  199. }
  200. }
  201. // Used globals will be build before link.
  202. }
  203. void DxilLib::BuildGlobalUsage() {
  204. Module &M = *m_pModule;
  205. // Collect init functions for static globals.
  206. if (GlobalVariable *Ctors = M.getGlobalVariable("llvm.global_ctors")) {
  207. if (ConstantArray *CA = dyn_cast<ConstantArray>(Ctors->getInitializer())) {
  208. for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e;
  209. ++i) {
  210. if (isa<ConstantAggregateZero>(*i))
  211. continue;
  212. ConstantStruct *CS = cast<ConstantStruct>(*i);
  213. if (isa<ConstantPointerNull>(CS->getOperand(1)))
  214. continue;
  215. // Must have a function or null ptr.
  216. if (!isa<Function>(CS->getOperand(1)))
  217. continue;
  218. Function *Ctor = cast<Function>(CS->getOperand(1));
  219. assert(Ctor->getReturnType()->isVoidTy() && Ctor->arg_size() == 0 &&
  220. "function type must be void (void)");
  221. // Add Ctor.
  222. m_initFuncSet.insert(Ctor);
  223. LazyLoadFunction(Ctor);
  224. }
  225. }
  226. }
  227. // Build used globals.
  228. for (GlobalVariable &GV : M.globals()) {
  229. std::unordered_set<Function *> funcSet;
  230. CollectUsedFunctions(&GV, funcSet);
  231. for (Function *F : funcSet) {
  232. DXASSERT(m_functionNameMap.count(F->getName()), "must exist in table");
  233. DxilFunctionLinkInfo *linkInfo = m_functionNameMap[F->getName()].get();
  234. linkInfo->usedGVs.insert(&GV);
  235. }
  236. }
  237. // Build resource map.
  238. AddResourceMap(m_DM.GetUAVs(), DXIL::ResourceClass::UAV, m_resourceMap, m_DM);
  239. AddResourceMap(m_DM.GetSRVs(), DXIL::ResourceClass::SRV, m_resourceMap, m_DM);
  240. AddResourceMap(m_DM.GetCBuffers(), DXIL::ResourceClass::CBuffer,
  241. m_resourceMap, m_DM);
  242. AddResourceMap(m_DM.GetSamplers(), DXIL::ResourceClass::Sampler,
  243. m_resourceMap, m_DM);
  244. }
  245. void DxilLib::CollectUsedInitFunctions(StringSet<> &addedFunctionSet,
  246. SmallVector<StringRef, 4> &workList) {
  247. // Add init functions to used functions.
  248. for (Function *Ctor : m_initFuncSet) {
  249. DXASSERT(m_functionNameMap.count(Ctor->getName()),
  250. "must exist in internal table");
  251. DxilFunctionLinkInfo *linkInfo = m_functionNameMap[Ctor->getName()].get();
  252. // If function other than Ctor used GV of Ctor.
  253. // Add Ctor to usedFunctions for it.
  254. for (GlobalVariable *GV : linkInfo->usedGVs) {
  255. std::unordered_set<Function *> funcSet;
  256. CollectUsedFunctions(GV, funcSet);
  257. bool bAdded = false;
  258. for (Function *F : funcSet) {
  259. if (F == Ctor)
  260. continue;
  261. // If F is added for link, add init func to workList.
  262. if (addedFunctionSet.count(F->getName())) {
  263. workList.emplace_back(Ctor->getName());
  264. bAdded = true;
  265. break;
  266. }
  267. }
  268. if (bAdded)
  269. break;
  270. }
  271. }
  272. }
  273. bool DxilLib::HasFunction(std::string &name) {
  274. return m_functionNameMap.count(name);
  275. }
  276. bool DxilLib::IsInitFunc(llvm::Function *F) { return m_initFuncSet.count(F); }
  277. bool DxilLib::IsResourceGlobal(const llvm::Constant *GV) {
  278. return m_resourceMap.count(GV);
  279. }
  280. DxilResourceBase *DxilLib::GetResource(const llvm::Constant *GV) {
  281. if (IsResourceGlobal(GV))
  282. return m_resourceMap[GV];
  283. else
  284. return nullptr;
  285. }
  286. namespace {
  287. // Create module from link defines.
  288. struct DxilLinkJob {
  289. DxilLinkJob(LLVMContext &Ctx, dxilutil::ExportMap &exportMap,
  290. unsigned valMajor, unsigned valMinor)
  291. : m_ctx(Ctx), m_exportMap(exportMap), m_valMajor(valMajor),
  292. m_valMinor(valMinor) {}
  293. std::unique_ptr<llvm::Module>
  294. Link(std::pair<DxilFunctionLinkInfo *, DxilLib *> &entryLinkPair,
  295. const ShaderModel *pSM);
  296. std::unique_ptr<llvm::Module> LinkToLib(const ShaderModel *pSM);
  297. void StripDeadDebugInfo(llvm::Module &M);
  298. void RunPreparePass(llvm::Module &M);
  299. void AddFunction(std::pair<DxilFunctionLinkInfo *, DxilLib *> &linkPair);
  300. void AddFunction(llvm::Function *F);
  301. private:
  302. void LinkNamedMDNodes(Module *pM, ValueToValueMapTy &vmap);
  303. void AddFunctionDecls(Module *pM);
  304. bool AddGlobals(DxilModule &DM, ValueToValueMapTy &vmap);
  305. void CloneFunctions(ValueToValueMapTy &vmap);
  306. void AddFunctions(DxilModule &DM, ValueToValueMapTy &vmap,
  307. std::unordered_set<Function *> &initFuncSet);
  308. bool AddResource(DxilResourceBase *res, llvm::GlobalVariable *GV);
  309. void AddResourceToDM(DxilModule &DM);
  310. std::unordered_map<DxilFunctionLinkInfo *, DxilLib *> m_functionDefs;
  311. llvm::StringMap<llvm::Function *> m_functionDecls;
  312. // New created functions.
  313. llvm::StringMap<llvm::Function *> m_newFunctions;
  314. // New created globals.
  315. llvm::StringMap<llvm::GlobalVariable *> m_newGlobals;
  316. // Map for resource.
  317. llvm::StringMap<std::pair<DxilResourceBase *, llvm::GlobalVariable *>>
  318. m_resourceMap;
  319. LLVMContext &m_ctx;
  320. dxilutil::ExportMap &m_exportMap;
  321. unsigned m_valMajor, m_valMinor;
  322. };
  323. } // namespace
  324. namespace {
  325. const char kUndefFunction[] = "Cannot find definition of function ";
  326. const char kRedefineFunction[] = "Definition already exists for function ";
  327. const char kRedefineGlobal[] = "Definition already exists for global variable ";
  328. const char kInvalidProfile[] = " is invalid profile to link";
  329. const char kExportOnlyForLib[] = "export map is only for library";
  330. const char kShaderKindMismatch[] =
  331. "Profile mismatch between entry function and target profile:";
  332. const char kNoEntryProps[] =
  333. "Cannot find function property for entry function ";
  334. const char kRedefineResource[] =
  335. "Resource already exists as ";
  336. const char kInvalidValidatorVersion[] = "Validator version does not support target profile ";
  337. const char kExportNameCollision[] = "Export name collides with another export: ";
  338. const char kExportFunctionMissing[] = "Could not find target for export: ";
  339. const char kNoFunctionsToExport[] = "Library has no functions to export";
  340. } // namespace
  341. //------------------------------------------------------------------------------
  342. //
  343. // DxilLinkJob methods.
  344. //
  345. namespace {
  346. // Helper function to check type match.
  347. bool IsMatchedType(Type *Ty0, Type *Ty);
  348. StringRef RemoveNameSuffix(StringRef Name) {
  349. size_t DotPos = Name.rfind('.');
  350. if (DotPos != StringRef::npos && Name.back() != '.' &&
  351. isdigit(static_cast<unsigned char>(Name[DotPos + 1])))
  352. Name = Name.substr(0, DotPos);
  353. return Name;
  354. }
  355. bool IsMatchedStructType(StructType *ST0, StructType *ST) {
  356. StringRef Name0 = RemoveNameSuffix(ST0->getName());
  357. StringRef Name = RemoveNameSuffix(ST->getName());
  358. if (Name0 != Name)
  359. return false;
  360. if (ST0->getNumElements() != ST->getNumElements())
  361. return false;
  362. if (ST0->isLayoutIdentical(ST))
  363. return true;
  364. for (unsigned i = 0; i < ST->getNumElements(); i++) {
  365. Type *Ty = ST->getElementType(i);
  366. Type *Ty0 = ST0->getElementType(i);
  367. if (!IsMatchedType(Ty, Ty0))
  368. return false;
  369. }
  370. return true;
  371. }
  372. bool IsMatchedArrayType(ArrayType *AT0, ArrayType *AT) {
  373. if (AT0->getNumElements() != AT->getNumElements())
  374. return false;
  375. return IsMatchedType(AT0->getElementType(), AT->getElementType());
  376. }
  377. bool IsMatchedType(Type *Ty0, Type *Ty) {
  378. if (Ty0->isStructTy() && Ty->isStructTy()) {
  379. StructType *ST0 = cast<StructType>(Ty0);
  380. StructType *ST = cast<StructType>(Ty);
  381. return IsMatchedStructType(ST0, ST);
  382. }
  383. if (Ty0->isArrayTy() && Ty->isArrayTy()) {
  384. ArrayType *AT0 = cast<ArrayType>(Ty0);
  385. ArrayType *AT = cast<ArrayType>(Ty);
  386. return IsMatchedArrayType(AT0, AT);
  387. }
  388. if (Ty0->isPointerTy() && Ty->isPointerTy()) {
  389. if (Ty0->getPointerAddressSpace() != Ty->getPointerAddressSpace())
  390. return false;
  391. return IsMatchedType(Ty0->getPointerElementType(),
  392. Ty->getPointerElementType());
  393. }
  394. return Ty0 == Ty;
  395. }
  396. } // namespace
  397. bool DxilLinkJob::AddResource(DxilResourceBase *res, llvm::GlobalVariable *GV) {
  398. if (m_resourceMap.count(res->GetGlobalName())) {
  399. DxilResourceBase *res0 = m_resourceMap[res->GetGlobalName()].first;
  400. Type *Ty0 = res0->GetGlobalSymbol()->getType()->getPointerElementType();
  401. Type *Ty = res->GetGlobalSymbol()->getType()->getPointerElementType();
  402. // Make sure res0 match res.
  403. bool bMatch = IsMatchedType(Ty0, Ty);
  404. if (!bMatch) {
  405. // Report error.
  406. m_ctx.emitError(Twine(kRedefineResource) + res->GetResClassName() + " for " +
  407. res->GetGlobalName());
  408. return false;
  409. }
  410. } else {
  411. m_resourceMap[res->GetGlobalName()] = std::make_pair(res, GV);
  412. }
  413. return true;
  414. }
  415. void DxilLinkJob::AddResourceToDM(DxilModule &DM) {
  416. for (auto &it : m_resourceMap) {
  417. DxilResourceBase *res = it.second.first;
  418. GlobalVariable *GV = it.second.second;
  419. unsigned ID = 0;
  420. DxilResourceBase *basePtr = nullptr;
  421. switch (res->GetClass()) {
  422. case DXIL::ResourceClass::UAV: {
  423. std::unique_ptr<DxilResource> pUAV = llvm::make_unique<DxilResource>();
  424. DxilResource *ptr = pUAV.get();
  425. // Copy the content.
  426. *ptr = *(static_cast<DxilResource *>(res));
  427. ID = DM.AddUAV(std::move(pUAV));
  428. basePtr = &DM.GetUAV(ID);
  429. } break;
  430. case DXIL::ResourceClass::SRV: {
  431. std::unique_ptr<DxilResource> pSRV = llvm::make_unique<DxilResource>();
  432. DxilResource *ptr = pSRV.get();
  433. // Copy the content.
  434. *ptr = *(static_cast<DxilResource *>(res));
  435. ID = DM.AddSRV(std::move(pSRV));
  436. basePtr = &DM.GetSRV(ID);
  437. } break;
  438. case DXIL::ResourceClass::CBuffer: {
  439. std::unique_ptr<DxilCBuffer> pCBuf = llvm::make_unique<DxilCBuffer>();
  440. DxilCBuffer *ptr = pCBuf.get();
  441. // Copy the content.
  442. *ptr = *(static_cast<DxilCBuffer *>(res));
  443. ID = DM.AddCBuffer(std::move(pCBuf));
  444. basePtr = &DM.GetCBuffer(ID);
  445. } break;
  446. case DXIL::ResourceClass::Sampler: {
  447. std::unique_ptr<DxilSampler> pSampler = llvm::make_unique<DxilSampler>();
  448. DxilSampler *ptr = pSampler.get();
  449. // Copy the content.
  450. *ptr = *(static_cast<DxilSampler *>(res));
  451. ID = DM.AddSampler(std::move(pSampler));
  452. basePtr = &DM.GetSampler(ID);
  453. }
  454. default:
  455. DXASSERT(res->GetClass() == DXIL::ResourceClass::Sampler,
  456. "else invalid resource");
  457. break;
  458. }
  459. // Update ID.
  460. basePtr->SetID(ID);
  461. basePtr->SetGlobalSymbol(GV);
  462. DM.GetLLVMUsed().push_back(GV);
  463. }
  464. // Prevent global vars used for resources from being deleted through optimizations
  465. // while we still have hidden uses (pointers in resource vectors).
  466. DM.EmitLLVMUsed();
  467. }
  468. void DxilLinkJob::LinkNamedMDNodes(Module *pM, ValueToValueMapTy &vmap) {
  469. SetVector<Module *> moduleSet;
  470. for (auto &it : m_functionDefs) {
  471. DxilLib *pLib = it.second;
  472. moduleSet.insert(pLib->GetDxilModule().GetModule());
  473. }
  474. // Link normal NamedMDNode.
  475. // TODO: skip duplicate operands.
  476. for (Module *pSrcM : moduleSet) {
  477. const NamedMDNode *pSrcModFlags = pSrcM->getModuleFlagsMetadata();
  478. for (const NamedMDNode &NMD : pSrcM->named_metadata()) {
  479. // Don't link module flags here. Do them separately.
  480. if (&NMD == pSrcModFlags)
  481. continue;
  482. // Skip dxil metadata which will be regenerated.
  483. if (DxilMDHelper::IsKnownNamedMetaData(NMD))
  484. continue;
  485. NamedMDNode *DestNMD = pM->getOrInsertNamedMetadata(NMD.getName());
  486. // Add Src elements into Dest node.
  487. for (const MDNode *op : NMD.operands())
  488. DestNMD->addOperand(MapMetadata(op, vmap, RF_None, /*TypeMap*/ nullptr,
  489. /*ValMaterializer*/ nullptr));
  490. }
  491. }
  492. // Link mod flags.
  493. SetVector<MDNode *> flagSet;
  494. for (Module *pSrcM : moduleSet) {
  495. NamedMDNode *pSrcModFlags = pSrcM->getModuleFlagsMetadata();
  496. if (pSrcModFlags) {
  497. for (MDNode *flag : pSrcModFlags->operands()) {
  498. flagSet.insert(flag);
  499. }
  500. }
  501. }
  502. // TODO: check conflict in flags.
  503. if (!flagSet.empty()) {
  504. NamedMDNode *ModFlags = pM->getOrInsertModuleFlagsMetadata();
  505. for (MDNode *flag : flagSet) {
  506. ModFlags->addOperand(flag);
  507. }
  508. }
  509. }
  510. void DxilLinkJob::AddFunctionDecls(Module *pM) {
  511. for (auto &it : m_functionDecls) {
  512. Function *F = it.second;
  513. Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
  514. F->getName(), pM);
  515. NewF->setAttributes(F->getAttributes());
  516. m_newFunctions[NewF->getName()] = NewF;
  517. }
  518. }
  519. bool DxilLinkJob::AddGlobals(DxilModule &DM, ValueToValueMapTy &vmap) {
  520. DxilTypeSystem &typeSys = DM.GetTypeSystem();
  521. Module *pM = DM.GetModule();
  522. bool bSuccess = true;
  523. for (auto &it : m_functionDefs) {
  524. DxilFunctionLinkInfo *linkInfo = it.first;
  525. DxilLib *pLib = it.second;
  526. DxilModule &tmpDM = pLib->GetDxilModule();
  527. DxilTypeSystem &tmpTypeSys = tmpDM.GetTypeSystem();
  528. for (GlobalVariable *GV : linkInfo->usedGVs) {
  529. // Skip added globals.
  530. if (m_newGlobals.count(GV->getName())) {
  531. if (vmap.find(GV) == vmap.end()) {
  532. if (DxilResourceBase *res = pLib->GetResource(GV)) {
  533. // For resource of same name, if class and type match, just map to
  534. // same NewGV.
  535. GlobalVariable *NewGV = m_newGlobals[GV->getName()];
  536. if (AddResource(res, NewGV)) {
  537. vmap[GV] = NewGV;
  538. } else {
  539. bSuccess = false;
  540. }
  541. continue;
  542. }
  543. // Redefine of global.
  544. m_ctx.emitError(Twine(kRedefineGlobal) + GV->getName());
  545. bSuccess = false;
  546. }
  547. continue;
  548. }
  549. Constant *Initializer = nullptr;
  550. if (GV->hasInitializer())
  551. Initializer = GV->getInitializer();
  552. Type *Ty = GV->getType()->getElementType();
  553. GlobalVariable *NewGV = new GlobalVariable(
  554. *pM, Ty, GV->isConstant(), GV->getLinkage(), Initializer,
  555. GV->getName(),
  556. /*InsertBefore*/ nullptr, GV->getThreadLocalMode(),
  557. GV->getType()->getAddressSpace(), GV->isExternallyInitialized());
  558. m_newGlobals[GV->getName()] = NewGV;
  559. vmap[GV] = NewGV;
  560. typeSys.CopyTypeAnnotation(Ty, tmpTypeSys);
  561. if (DxilResourceBase *res = pLib->GetResource(GV)) {
  562. bSuccess &= AddResource(res, NewGV);
  563. }
  564. }
  565. }
  566. return bSuccess;
  567. }
  568. void DxilLinkJob::CloneFunctions(ValueToValueMapTy &vmap) {
  569. for (auto &it : m_functionDefs) {
  570. DxilFunctionLinkInfo *linkInfo = it.first;
  571. Function *F = linkInfo->func;
  572. Function *NewF = m_newFunctions[F->getName()];
  573. // Add dxil functions to vmap.
  574. for (Function *UsedF : linkInfo->usedFunctions) {
  575. if (!vmap.count(UsedF)) {
  576. // Extern function need match by name
  577. DXASSERT(m_newFunctions.count(UsedF->getName()),
  578. "Must have new function.");
  579. vmap[UsedF] = m_newFunctions[UsedF->getName()];
  580. }
  581. }
  582. CloneFunction(F, NewF, vmap);
  583. }
  584. }
  585. void DxilLinkJob::AddFunctions(DxilModule &DM, ValueToValueMapTy &vmap,
  586. std::unordered_set<Function *> &initFuncSet) {
  587. DxilTypeSystem &typeSys = DM.GetTypeSystem();
  588. Module *pM = DM.GetModule();
  589. for (auto &it : m_functionDefs) {
  590. DxilFunctionLinkInfo *linkInfo = it.first;
  591. DxilLib *pLib = it.second;
  592. DxilModule &tmpDM = pLib->GetDxilModule();
  593. DxilTypeSystem &tmpTypeSys = tmpDM.GetTypeSystem();
  594. Function *F = linkInfo->func;
  595. Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
  596. F->getName(), pM);
  597. NewF->setAttributes(F->getAttributes());
  598. if (!NewF->hasFnAttribute(llvm::Attribute::NoInline))
  599. NewF->addFnAttr(llvm::Attribute::AlwaysInline);
  600. if (DxilFunctionAnnotation *funcAnnotation =
  601. tmpTypeSys.GetFunctionAnnotation(F)) {
  602. // Clone funcAnnotation to typeSys.
  603. typeSys.CopyFunctionAnnotation(NewF, F, tmpTypeSys);
  604. }
  605. // Add to function map.
  606. m_newFunctions[NewF->getName()] = NewF;
  607. if (pLib->IsInitFunc(F))
  608. initFuncSet.insert(NewF);
  609. vmap[F] = NewF;
  610. }
  611. }
  612. std::unique_ptr<Module>
  613. DxilLinkJob::Link(std::pair<DxilFunctionLinkInfo *, DxilLib *> &entryLinkPair,
  614. const ShaderModel *pSM) {
  615. Function *entryFunc = entryLinkPair.first->func;
  616. DxilModule &entryDM = entryLinkPair.second->GetDxilModule();
  617. if (!entryDM.HasDxilFunctionProps(entryFunc)) {
  618. // Cannot get function props.
  619. m_ctx.emitError(Twine(kNoEntryProps) + entryFunc->getName());
  620. return nullptr;
  621. }
  622. DxilFunctionProps props = entryDM.GetDxilFunctionProps(entryFunc);
  623. if (pSM->GetKind() != props.shaderKind) {
  624. // Shader kind mismatch.
  625. m_ctx.emitError(Twine(kShaderKindMismatch) +
  626. ShaderModel::GetKindName(pSM->GetKind()) + " and " +
  627. ShaderModel::GetKindName(props.shaderKind));
  628. return nullptr;
  629. }
  630. // Create new module.
  631. std::unique_ptr<Module> pM =
  632. llvm::make_unique<Module>(entryFunc->getName(), entryDM.GetCtx());
  633. // Set target.
  634. pM->setTargetTriple(entryDM.GetModule()->getTargetTriple());
  635. // Add dxil operation functions before create DxilModule.
  636. AddFunctionDecls(pM.get());
  637. // Create DxilModule.
  638. const bool bSkipInit = true;
  639. DxilModule &DM = pM->GetOrCreateDxilModule(bSkipInit);
  640. DM.SetShaderModel(pSM, entryDM.GetUseMinPrecision());
  641. // Set Validator version.
  642. DM.SetValidatorVersion(m_valMajor, m_valMinor);
  643. ValueToValueMapTy vmap;
  644. std::unordered_set<Function *> initFuncSet;
  645. // Add function
  646. AddFunctions(DM, vmap, initFuncSet);
  647. // Set Entry
  648. Function *NewEntryFunc = m_newFunctions[entryFunc->getName()];
  649. DM.SetEntryFunction(NewEntryFunc);
  650. DM.SetEntryFunctionName(entryFunc->getName());
  651. DxilEntryPropsMap EntryPropMap;
  652. std::unique_ptr<DxilEntryProps> pProps =
  653. llvm::make_unique<DxilEntryProps>(entryDM.GetDxilEntryProps(entryFunc));
  654. EntryPropMap[NewEntryFunc] = std::move(pProps);
  655. DM.ResetEntryPropsMap(std::move(EntryPropMap));
  656. if (NewEntryFunc->hasFnAttribute(llvm::Attribute::AlwaysInline))
  657. NewEntryFunc->removeFnAttr(llvm::Attribute::AlwaysInline);
  658. if (props.IsHS()) {
  659. Function *patchConstantFunc = props.ShaderProps.HS.patchConstantFunc;
  660. Function *newPatchConstantFunc =
  661. m_newFunctions[patchConstantFunc->getName()];
  662. props.ShaderProps.HS.patchConstantFunc = newPatchConstantFunc;
  663. if (newPatchConstantFunc->hasFnAttribute(llvm::Attribute::AlwaysInline))
  664. newPatchConstantFunc->removeFnAttr(llvm::Attribute::AlwaysInline);
  665. }
  666. // Set EntryProps
  667. DM.SetShaderProperties(&props);
  668. // Add global
  669. bool bSuccess = AddGlobals(DM, vmap);
  670. if (!bSuccess)
  671. return nullptr;
  672. // Clone functions.
  673. CloneFunctions(vmap);
  674. // Call global constrctor.
  675. IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(DM.GetEntryFunction()));
  676. for (auto &it : m_functionDefs) {
  677. DxilFunctionLinkInfo *linkInfo = it.first;
  678. DxilLib *pLib = it.second;
  679. Function *F = linkInfo->func;
  680. if (pLib->IsInitFunc(F)) {
  681. Function *NewF = m_newFunctions[F->getName()];
  682. Builder.CreateCall(NewF);
  683. }
  684. }
  685. // Refresh intrinsic cache.
  686. DM.GetOP()->RefreshCache();
  687. // Add resource to DM.
  688. // This should be after functions cloned.
  689. AddResourceToDM(DM);
  690. // Link metadata like debug info.
  691. LinkNamedMDNodes(pM.get(), vmap);
  692. RunPreparePass(*pM);
  693. return pM;
  694. }
  695. std::unique_ptr<Module>
  696. DxilLinkJob::LinkToLib(const ShaderModel *pSM) {
  697. if (m_functionDefs.empty()) {
  698. m_ctx.emitError(Twine(kNoFunctionsToExport));
  699. return nullptr;
  700. }
  701. DxilLib *pLib = m_functionDefs.begin()->second;
  702. DxilModule &tmpDM = pLib->GetDxilModule();
  703. // Create new module.
  704. std::unique_ptr<Module> pM =
  705. llvm::make_unique<Module>("merged_lib", tmpDM.GetCtx());
  706. // Set target.
  707. pM->setTargetTriple(tmpDM.GetModule()->getTargetTriple());
  708. // Add dxil operation functions and external decls before create DxilModule.
  709. AddFunctionDecls(pM.get());
  710. // Create DxilModule.
  711. const bool bSkipInit = true;
  712. DxilModule &DM = pM->GetOrCreateDxilModule(bSkipInit);
  713. DM.SetShaderModel(pSM, tmpDM.GetUseMinPrecision());
  714. // Set Validator version.
  715. DM.SetValidatorVersion(m_valMajor, m_valMinor);
  716. ValueToValueMapTy vmap;
  717. std::unordered_set<Function *> initFuncSet;
  718. // Add function
  719. AddFunctions(DM, vmap, initFuncSet);
  720. // Set DxilFunctionProps.
  721. DxilEntryPropsMap EntryPropMap;
  722. for (auto &it : m_functionDefs) {
  723. DxilFunctionLinkInfo *linkInfo = it.first;
  724. DxilLib *pLib = it.second;
  725. DxilModule &tmpDM = pLib->GetDxilModule();
  726. Function *F = linkInfo->func;
  727. if (tmpDM.HasDxilEntryProps(F)) {
  728. Function *NewF = m_newFunctions[F->getName()];
  729. DxilEntryProps &props = tmpDM.GetDxilEntryProps(F);
  730. std::unique_ptr<DxilEntryProps> pProps =
  731. llvm::make_unique<DxilEntryProps>(props);
  732. EntryPropMap[NewF] = std::move(pProps);
  733. }
  734. }
  735. DM.ResetEntryPropsMap(std::move(EntryPropMap));
  736. // Add global
  737. bool bSuccess = AddGlobals(DM, vmap);
  738. if (!bSuccess)
  739. return nullptr;
  740. // Clone functions.
  741. CloneFunctions(vmap);
  742. // Refresh intrinsic cache.
  743. DM.GetOP()->RefreshCache();
  744. // Add resource to DM.
  745. // This should be after functions cloned.
  746. AddResourceToDM(DM);
  747. // Link metadata like debug info.
  748. LinkNamedMDNodes(pM.get(), vmap);
  749. RunPreparePass(*pM);
  750. if (!m_exportMap.empty()) {
  751. m_exportMap.BeginProcessing();
  752. DM.ClearDxilMetadata(*pM);
  753. for (auto it = pM->begin(); it != pM->end();) {
  754. Function *F = it++;
  755. if (F->isDeclaration())
  756. continue;
  757. if (!m_exportMap.ProcessFunction(F, true)) {
  758. // Remove Function not in exportMap.
  759. DM.RemoveFunction(F);
  760. F->eraseFromParent();
  761. }
  762. }
  763. if(!m_exportMap.EndProcessing()) {
  764. for (auto &name : m_exportMap.GetNameCollisions()) {
  765. std::string escaped;
  766. llvm::raw_string_ostream os(escaped);
  767. dxilutil::PrintEscapedString(name, os);
  768. m_ctx.emitError(Twine(kExportNameCollision) + os.str());
  769. }
  770. for (auto &name : m_exportMap.GetUnusedExports()) {
  771. std::string escaped;
  772. llvm::raw_string_ostream os(escaped);
  773. dxilutil::PrintEscapedString(name, os);
  774. m_ctx.emitError(Twine(kExportFunctionMissing) + os.str());
  775. }
  776. return nullptr;
  777. }
  778. // Rename the original, if necessary, then clone the rest
  779. for (auto &it : m_exportMap.GetFunctionRenames()) {
  780. Function *F = it.first;
  781. auto &renames = it.second;
  782. if (renames.empty())
  783. continue;
  784. auto itName = renames.begin();
  785. // Rename the original, if necessary, then clone the rest
  786. if (renames.find(F->getName()) == renames.end())
  787. F->setName(*(itName++));
  788. while (itName != renames.end()) {
  789. if (F->getName() != *itName) {
  790. Function *NewF = Function::Create(F->getFunctionType(),
  791. GlobalValue::LinkageTypes::ExternalLinkage,
  792. *itName, DM.GetModule());
  793. ValueToValueMapTy vmap;
  794. CloneFunction(F, NewF, vmap, &DM.GetTypeSystem());
  795. // add DxilFunctionProps if entry
  796. if (DM.HasDxilFunctionProps(F)) {
  797. DM.CloneDxilEntryProps(F, NewF);
  798. }
  799. }
  800. itName++;
  801. }
  802. }
  803. DM.EmitDxilMetadata();
  804. }
  805. return pM;
  806. }
  807. void DxilLinkJob::AddFunction(
  808. std::pair<DxilFunctionLinkInfo *, DxilLib *> &linkPair) {
  809. m_functionDefs[linkPair.first] = linkPair.second;
  810. }
  811. void DxilLinkJob::AddFunction(llvm::Function *F) {
  812. m_functionDecls[F->getName()] = F;
  813. }
  814. // Clone of StripDeadDebugInfo::runOnModule.
  815. // Also remove function which not not in current Module.
  816. void DxilLinkJob::StripDeadDebugInfo(Module &M) {
  817. LLVMContext &C = M.getContext();
  818. // Find all debug info in F. This is actually overkill in terms of what we
  819. // want to do, but we want to try and be as resilient as possible in the face
  820. // of potential debug info changes by using the formal interfaces given to us
  821. // as much as possible.
  822. DebugInfoFinder F;
  823. F.processModule(M);
  824. // For each compile unit, find the live set of global variables/functions and
  825. // replace the current list of potentially dead global variables/functions
  826. // with the live list.
  827. SmallVector<Metadata *, 64> LiveGlobalVariables;
  828. SmallVector<Metadata *, 64> LiveSubprograms;
  829. DenseSet<const MDNode *> VisitedSet;
  830. for (DICompileUnit *DIC : F.compile_units()) {
  831. // Create our live subprogram list.
  832. bool SubprogramChange = false;
  833. for (DISubprogram *DISP : DIC->getSubprograms()) {
  834. // Make sure we visit each subprogram only once.
  835. if (!VisitedSet.insert(DISP).second)
  836. continue;
  837. // If the function referenced by DISP is not null, the function is live.
  838. if (Function *Func = DISP->getFunction()) {
  839. if (Func->getParent() == &M)
  840. LiveSubprograms.push_back(DISP);
  841. else
  842. SubprogramChange = true;
  843. } else {
  844. SubprogramChange = true;
  845. }
  846. }
  847. // Create our live global variable list.
  848. bool GlobalVariableChange = false;
  849. for (DIGlobalVariable *DIG : DIC->getGlobalVariables()) {
  850. // Make sure we only visit each global variable only once.
  851. if (!VisitedSet.insert(DIG).second)
  852. continue;
  853. // If the global variable referenced by DIG is not null, the global
  854. // variable is live.
  855. if (Constant *CV = DIG->getVariable()) {
  856. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CV)) {
  857. if (GV->getParent() == &M) {
  858. LiveGlobalVariables.push_back(DIG);
  859. } else {
  860. GlobalVariableChange = true;
  861. }
  862. } else {
  863. LiveGlobalVariables.push_back(DIG);
  864. }
  865. } else {
  866. GlobalVariableChange = true;
  867. }
  868. }
  869. // If we found dead subprograms or global variables, replace the current
  870. // subprogram list/global variable list with our new live subprogram/global
  871. // variable list.
  872. if (SubprogramChange) {
  873. DIC->replaceSubprograms(MDTuple::get(C, LiveSubprograms));
  874. }
  875. if (GlobalVariableChange) {
  876. DIC->replaceGlobalVariables(MDTuple::get(C, LiveGlobalVariables));
  877. }
  878. // Reset lists for the next iteration.
  879. LiveSubprograms.clear();
  880. LiveGlobalVariables.clear();
  881. }
  882. }
  883. void DxilLinkJob::RunPreparePass(Module &M) {
  884. StripDeadDebugInfo(M);
  885. legacy::PassManager PM;
  886. PM.add(createAlwaysInlinerPass(/*InsertLifeTime*/ false));
  887. // Remove unused functions.
  888. PM.add(createDxilDeadFunctionEliminationPass());
  889. // SROA
  890. PM.add(createSROAPass(/*RequiresDomTree*/false));
  891. // Remove MultiDimArray from function call arg.
  892. PM.add(createMultiDimArrayToOneDimArrayPass());
  893. // Lower matrix bitcast.
  894. PM.add(createMatrixBitcastLowerPass());
  895. // mem2reg.
  896. PM.add(createPromoteMemoryToRegisterPass());
  897. // Clean up vectors, and run mem2reg again
  898. PM.add(createScalarizerPass());
  899. PM.add(createPromoteMemoryToRegisterPass());
  900. PM.add(createSimplifyInstPass());
  901. PM.add(createCFGSimplificationPass());
  902. PM.add(createDeadCodeEliminationPass());
  903. PM.add(createGlobalDCEPass());
  904. PM.add(createDxilLowerCreateHandleForLibPass());
  905. PM.add(createDxilTranslateRawBuffer());
  906. PM.add(createDxilFinalizeModulePass());
  907. PM.add(createComputeViewIdStatePass());
  908. PM.add(createDxilDeadFunctionEliminationPass());
  909. PM.add(createNoPausePassesPass());
  910. PM.add(createDxilEmitMetadataPass());
  911. PM.run(M);
  912. }
  913. //------------------------------------------------------------------------------
  914. //
  915. // DxilLinkerImpl methods.
  916. //
  917. bool DxilLinkerImpl::HasLibNameRegistered(StringRef name) {
  918. return m_LibMap.count(name);
  919. }
  920. bool DxilLinkerImpl::RegisterLib(StringRef name,
  921. std::unique_ptr<llvm::Module> pModule,
  922. std::unique_ptr<llvm::Module> pDebugModule) {
  923. if (m_LibMap.count(name))
  924. return false;
  925. std::unique_ptr<llvm::Module> pM =
  926. pDebugModule ? std::move(pDebugModule) : std::move(pModule);
  927. if (!pM)
  928. return false;
  929. pM->setModuleIdentifier(name);
  930. std::unique_ptr<DxilLib> pLib =
  931. llvm::make_unique<DxilLib>(std::move(pM));
  932. m_LibMap[name] = std::move(pLib);
  933. return true;
  934. }
  935. bool DxilLinkerImpl::AttachLib(StringRef name) {
  936. auto iter = m_LibMap.find(name);
  937. if (iter == m_LibMap.end()) {
  938. return false;
  939. }
  940. return AttachLib(iter->second.get());
  941. }
  942. bool DxilLinkerImpl::DetachLib(StringRef name) {
  943. auto iter = m_LibMap.find(name);
  944. if (iter == m_LibMap.end()) {
  945. return false;
  946. }
  947. return DetachLib(iter->second.get());
  948. }
  949. void DxilLinkerImpl::DetachAll() {
  950. m_functionNameMap.clear();
  951. m_attachedLibs.clear();
  952. }
  953. bool DxilLinkerImpl::AttachLib(DxilLib *lib) {
  954. if (!lib) {
  955. // Invalid arg.
  956. return false;
  957. }
  958. if (m_attachedLibs.count(lib))
  959. return false;
  960. StringMap<std::unique_ptr<DxilFunctionLinkInfo>> &funcTable =
  961. lib->GetFunctionTable();
  962. bool bSuccess = true;
  963. for (auto it = funcTable.begin(), e = funcTable.end(); it != e; it++) {
  964. StringRef name = it->getKey();
  965. if (m_functionNameMap.count(name)) {
  966. // Redefine of function.
  967. m_ctx.emitError(Twine(kRedefineFunction) + name);
  968. bSuccess = false;
  969. continue;
  970. }
  971. m_functionNameMap[name] = std::make_pair(it->second.get(), lib);
  972. }
  973. if (bSuccess) {
  974. m_attachedLibs.insert(lib);
  975. } else {
  976. for (auto it = funcTable.begin(), e = funcTable.end(); it != e; it++) {
  977. StringRef name = it->getKey();
  978. auto iter = m_functionNameMap.find(name);
  979. if (iter == m_functionNameMap.end())
  980. continue;
  981. // Remove functions of lib.
  982. if (m_functionNameMap[name].second == lib)
  983. m_functionNameMap.erase(name);
  984. }
  985. }
  986. return bSuccess;
  987. }
  988. bool DxilLinkerImpl::DetachLib(DxilLib *lib) {
  989. if (!lib) {
  990. // Invalid arg.
  991. return false;
  992. }
  993. if (!m_attachedLibs.count(lib))
  994. return false;
  995. m_attachedLibs.erase(lib);
  996. // Remove functions from lib.
  997. StringMap<std::unique_ptr<DxilFunctionLinkInfo>> &funcTable =
  998. lib->GetFunctionTable();
  999. for (auto it = funcTable.begin(), e = funcTable.end(); it != e; it++) {
  1000. StringRef name = it->getKey();
  1001. m_functionNameMap.erase(name);
  1002. }
  1003. return true;
  1004. }
  1005. bool DxilLinkerImpl::AddFunctions(SmallVector<StringRef, 4> &workList,
  1006. DenseSet<DxilLib *> &libSet,
  1007. StringSet<> &addedFunctionSet,
  1008. DxilLinkJob &linkJob, bool bLazyLoadDone,
  1009. bool bAllowFuncionDecls) {
  1010. while (!workList.empty()) {
  1011. StringRef name = workList.pop_back_val();
  1012. // Ignore added function.
  1013. if (addedFunctionSet.count(name))
  1014. continue;
  1015. if (!m_functionNameMap.count(name)) {
  1016. // Cannot find function, report error.
  1017. m_ctx.emitError(Twine(kUndefFunction) + name);
  1018. return false;
  1019. }
  1020. std::pair<DxilFunctionLinkInfo *, DxilLib *> &linkPair =
  1021. m_functionNameMap[name];
  1022. linkJob.AddFunction(linkPair);
  1023. DxilLib *pLib = linkPair.second;
  1024. libSet.insert(pLib);
  1025. if (!bLazyLoadDone) {
  1026. Function *F = linkPair.first->func;
  1027. pLib->LazyLoadFunction(F);
  1028. }
  1029. for (Function *F : linkPair.first->usedFunctions) {
  1030. if (hlsl::OP::IsDxilOpFunc(F) || F->isIntrinsic()) {
  1031. // Add dxil operations directly.
  1032. linkJob.AddFunction(F);
  1033. } else if (addedFunctionSet.count(F->getName()) == 0) {
  1034. if (bAllowFuncionDecls && F->isDeclaration() && !m_functionNameMap.count(F->getName())) {
  1035. // When linking to lib, use of undefined function is allowed; add directly.
  1036. linkJob.AddFunction(F);
  1037. } else {
  1038. // Push function name to work list.
  1039. workList.emplace_back(F->getName());
  1040. }
  1041. }
  1042. }
  1043. addedFunctionSet.insert(name);
  1044. }
  1045. return true;
  1046. }
  1047. std::unique_ptr<llvm::Module>
  1048. DxilLinkerImpl::Link(StringRef entry, StringRef profile, dxilutil::ExportMap &exportMap) {
  1049. const ShaderModel *pSM = ShaderModel::GetByName(profile.data());
  1050. DXIL::ShaderKind kind = pSM->GetKind();
  1051. if (kind == DXIL::ShaderKind::Invalid ||
  1052. (kind >= DXIL::ShaderKind::RayGeneration &&
  1053. kind <= DXIL::ShaderKind::Callable)) {
  1054. m_ctx.emitError(profile + Twine(kInvalidProfile));
  1055. // Invalid profile.
  1056. return nullptr;
  1057. }
  1058. if (!exportMap.empty() && kind != DXIL::ShaderKind::Library) {
  1059. m_ctx.emitError(Twine(kExportOnlyForLib));
  1060. return nullptr;
  1061. }
  1062. // Verifying validator version supports the requested profile
  1063. unsigned minValMajor, minValMinor;
  1064. pSM->GetMinValidatorVersion(minValMajor, minValMinor);
  1065. if (minValMajor > m_valMajor ||
  1066. (minValMajor == m_valMajor && minValMinor > m_valMinor)) {
  1067. m_ctx.emitError(Twine(kInvalidValidatorVersion) + profile);
  1068. return nullptr;
  1069. }
  1070. DxilLinkJob linkJob(m_ctx, exportMap, m_valMajor, m_valMinor);
  1071. DenseSet<DxilLib *> libSet;
  1072. StringSet<> addedFunctionSet;
  1073. bool bIsLib = pSM->IsLib();
  1074. if (!bIsLib) {
  1075. SmallVector<StringRef, 4> workList;
  1076. workList.emplace_back(entry);
  1077. if (!AddFunctions(workList, libSet, addedFunctionSet, linkJob,
  1078. /*bLazyLoadDone*/ false,
  1079. /*bAllowFuncionDecls*/ false))
  1080. return nullptr;
  1081. } else {
  1082. if (exportMap.empty()) {
  1083. // Add every function for lib profile.
  1084. for (auto &it : m_functionNameMap) {
  1085. StringRef name = it.getKey();
  1086. std::pair<DxilFunctionLinkInfo *, DxilLib *> &linkPair = it.second;
  1087. DxilFunctionLinkInfo *linkInfo = linkPair.first;
  1088. DxilLib *pLib = linkPair.second;
  1089. Function *F = linkInfo->func;
  1090. pLib->LazyLoadFunction(F);
  1091. linkJob.AddFunction(linkPair);
  1092. libSet.insert(pLib);
  1093. addedFunctionSet.insert(name);
  1094. }
  1095. // Add every dxil function and llvm intrinsic.
  1096. for (auto *pLib : libSet) {
  1097. auto &DM = pLib->GetDxilModule();
  1098. DM.GetOP();
  1099. auto *pM = DM.GetModule();
  1100. for (Function &F : pM->functions()) {
  1101. if (hlsl::OP::IsDxilOpFunc(&F) || F.isIntrinsic() ||
  1102. (F.isDeclaration() && m_functionNameMap.count(F.getName()) == 0)) {
  1103. // Add intrinsics and function decls still not defined in any lib
  1104. linkJob.AddFunction(&F);
  1105. }
  1106. }
  1107. }
  1108. } else {
  1109. SmallVector<StringRef, 4> workList;
  1110. // Only add exported functions.
  1111. for (auto &it : m_functionNameMap) {
  1112. StringRef name = it.getKey();
  1113. // Only add names exist in exportMap.
  1114. if (exportMap.IsExported(name))
  1115. workList.emplace_back(name);
  1116. }
  1117. if (!AddFunctions(workList, libSet, addedFunctionSet, linkJob,
  1118. /*bLazyLoadDone*/ false,
  1119. /*bAllowFuncionDecls*/ true))
  1120. return nullptr;
  1121. }
  1122. }
  1123. // Save global users.
  1124. for (auto &pLib : libSet) {
  1125. pLib->BuildGlobalUsage();
  1126. }
  1127. SmallVector<StringRef, 4> workList;
  1128. // Save global ctor users.
  1129. for (auto &pLib : libSet) {
  1130. pLib->CollectUsedInitFunctions(addedFunctionSet, workList);
  1131. }
  1132. // Add init functions if used.
  1133. // All init function already loaded in BuildGlobalUsage,
  1134. // so set bLazyLoadDone to true here.
  1135. // Decls should have been added to addedFunctionSet if lib,
  1136. // so set bAllowFuncionDecls is false here.
  1137. if (!AddFunctions(workList, libSet, addedFunctionSet, linkJob,
  1138. /*bLazyLoadDone*/ true,
  1139. /*bAllowFuncionDecls*/ false))
  1140. return nullptr;
  1141. if (!bIsLib) {
  1142. std::pair<DxilFunctionLinkInfo *, DxilLib *> &entryLinkPair =
  1143. m_functionNameMap[entry];
  1144. return linkJob.Link(entryLinkPair, pSM);
  1145. } else {
  1146. return linkJob.LinkToLib(pSM);
  1147. }
  1148. }
  1149. namespace hlsl {
  1150. DxilLinker *DxilLinker::CreateLinker(LLVMContext &Ctx, unsigned valMajor, unsigned valMinor) {
  1151. return new DxilLinkerImpl(Ctx, valMajor, valMinor);
  1152. }
  1153. } // namespace hlsl