HLModule.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // HLModule.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. // HighLevel DX IR module. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "dxc/HLSL/DxilOperations.h"
  12. #include "dxc/HLSL/DxilShaderModel.h"
  13. #include "dxc/HLSL/DxilCBuffer.h"
  14. #include "dxc/HLSL/HLModule.h"
  15. #include "dxc/HLSL/DxilTypeSystem.h"
  16. #include "dxc/HLSL/DxilRootSignature.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/IR/Constants.h"
  19. #include "llvm/IR/Function.h"
  20. #include "llvm/IR/IRBuilder.h"
  21. #include "llvm/IR/LLVMContext.h"
  22. #include "llvm/IR/Metadata.h"
  23. #include "llvm/IR/Module.h"
  24. #include "llvm/IR/DebugInfo.h"
  25. #include "llvm/IR/DIBuilder.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include "llvm/IR/GetElementPtrTypeIterator.h"
  28. using namespace llvm;
  29. using std::string;
  30. using std::vector;
  31. using std::unique_ptr;
  32. namespace hlsl {
  33. static void
  34. CreateSignatures(const ShaderModel *pSM,
  35. std::unique_ptr<DxilSignature> &InputSignature,
  36. std::unique_ptr<DxilSignature> &OutputSignature,
  37. std::unique_ptr<DxilSignature> &PatchConstantSignature,
  38. std::unique_ptr<RootSignatureHandle> &RootSignature) {
  39. DXIL::ShaderKind shaderKind = pSM->GetKind();
  40. InputSignature = llvm::make_unique<DxilSignature>(shaderKind, DxilSignature::Kind::Input);
  41. OutputSignature = llvm::make_unique<DxilSignature>(shaderKind, DxilSignature::Kind::Output);
  42. PatchConstantSignature = llvm::make_unique<DxilSignature>(shaderKind, DxilSignature::Kind::PatchConstant);
  43. RootSignature = llvm::make_unique<RootSignatureHandle>();
  44. }
  45. //------------------------------------------------------------------------------
  46. //
  47. // HLModule methods.
  48. //
  49. HLModule::HLModule(Module *pModule)
  50. : m_Ctx(pModule->getContext())
  51. , m_pModule(pModule)
  52. , m_pEntryFunc(nullptr)
  53. , m_EntryName("")
  54. , m_pMDHelper(llvm::make_unique<DxilMDHelper>(
  55. pModule, llvm::make_unique<HLExtraPropertyHelper>(pModule)))
  56. , m_pDebugInfoFinder(nullptr)
  57. , m_pSM(nullptr)
  58. , m_DxilMajor(DXIL::kDxilMajor)
  59. , m_DxilMinor(DXIL::kDxilMinor)
  60. , m_pOP(llvm::make_unique<OP>(pModule->getContext(), pModule))
  61. , m_pTypeSystem(llvm::make_unique<DxilTypeSystem>(pModule)) {
  62. DXASSERT_NOMSG(m_pModule != nullptr);
  63. // Pin LLVM dump methods. TODO: make debug-only.
  64. void (__thiscall Module::*pfnModuleDump)() const = &Module::dump;
  65. void (__thiscall Type::*pfnTypeDump)() const = &Type::dump;
  66. m_pUnused = (char *)&pfnModuleDump - (char *)&pfnTypeDump;
  67. }
  68. HLModule::~HLModule() {
  69. }
  70. LLVMContext &HLModule::GetCtx() const { return m_Ctx; }
  71. Module *HLModule::GetModule() const { return m_pModule; }
  72. OP *HLModule::GetOP() const { return m_pOP.get(); }
  73. void HLModule::SetShaderModel(const ShaderModel *pSM) {
  74. DXASSERT(m_pSM == nullptr, "shader model must not change for the module");
  75. m_pSM = pSM;
  76. m_pSM->GetDxilVersion(m_DxilMajor, m_DxilMinor);
  77. m_pMDHelper->SetShaderModel(m_pSM);
  78. CreateSignatures(m_pSM, m_InputSignature, m_OutputSignature, m_PatchConstantSignature, m_RootSignature);
  79. }
  80. const ShaderModel *HLModule::GetShaderModel() const {
  81. return m_pSM;
  82. }
  83. uint32_t HLOptions::GetHLOptionsRaw() const {
  84. union Cast {
  85. Cast(const HLOptions &options) {
  86. hlOptions = options;
  87. }
  88. HLOptions hlOptions;
  89. uint32_t rawData;
  90. };
  91. static_assert(sizeof(uint32_t) == sizeof(HLOptions),
  92. "size must match to make sure no undefined bits when cast");
  93. Cast rawCast(*this);
  94. return rawCast.rawData;
  95. }
  96. void HLOptions::SetHLOptionsRaw(uint32_t data) {
  97. union Cast {
  98. Cast(uint32_t data) {
  99. rawData = data;
  100. }
  101. HLOptions hlOptions;
  102. uint64_t rawData;
  103. };
  104. Cast rawCast(data);
  105. *this = rawCast.hlOptions;
  106. }
  107. void HLModule::SetHLOptions(HLOptions &opts) {
  108. m_Options = opts;
  109. }
  110. const HLOptions &HLModule::GetHLOptions() const {
  111. return m_Options;
  112. }
  113. Function *HLModule::GetEntryFunction() const {
  114. return m_pEntryFunc;
  115. }
  116. void HLModule::SetEntryFunction(Function *pEntryFunc) {
  117. m_pEntryFunc = pEntryFunc;
  118. }
  119. const string &HLModule::GetEntryFunctionName() const { return m_EntryName; }
  120. void HLModule::SetEntryFunctionName(const string &name) { m_EntryName = name; }
  121. template<typename T> unsigned
  122. HLModule::AddResource(vector<unique_ptr<T> > &Vec, unique_ptr<T> pRes) {
  123. DXASSERT_NOMSG((unsigned)Vec.size() < UINT_MAX);
  124. unsigned Id = (unsigned)Vec.size();
  125. Vec.emplace_back(std::move(pRes));
  126. return Id;
  127. }
  128. unsigned HLModule::AddCBuffer(unique_ptr<DxilCBuffer> pCBuffer) {
  129. return AddResource<DxilCBuffer>(m_CBuffers, std::move(pCBuffer));
  130. }
  131. DxilCBuffer &HLModule::GetCBuffer(unsigned idx) {
  132. return *m_CBuffers[idx];
  133. }
  134. const DxilCBuffer &HLModule::GetCBuffer(unsigned idx) const {
  135. return *m_CBuffers[idx];
  136. }
  137. const vector<unique_ptr<DxilCBuffer> > &HLModule::GetCBuffers() const {
  138. return m_CBuffers;
  139. }
  140. unsigned HLModule::AddSampler(unique_ptr<DxilSampler> pSampler) {
  141. return AddResource<DxilSampler>(m_Samplers, std::move(pSampler));
  142. }
  143. DxilSampler &HLModule::GetSampler(unsigned idx) {
  144. return *m_Samplers[idx];
  145. }
  146. const DxilSampler &HLModule::GetSampler(unsigned idx) const {
  147. return *m_Samplers[idx];
  148. }
  149. const vector<unique_ptr<DxilSampler> > &HLModule::GetSamplers() const {
  150. return m_Samplers;
  151. }
  152. unsigned HLModule::AddSRV(unique_ptr<HLResource> pSRV) {
  153. return AddResource<HLResource>(m_SRVs, std::move(pSRV));
  154. }
  155. HLResource &HLModule::GetSRV(unsigned idx) {
  156. return *m_SRVs[idx];
  157. }
  158. const HLResource &HLModule::GetSRV(unsigned idx) const {
  159. return *m_SRVs[idx];
  160. }
  161. const vector<unique_ptr<HLResource> > &HLModule::GetSRVs() const {
  162. return m_SRVs;
  163. }
  164. unsigned HLModule::AddUAV(unique_ptr<HLResource> pUAV) {
  165. return AddResource<HLResource>(m_UAVs, std::move(pUAV));
  166. }
  167. HLResource &HLModule::GetUAV(unsigned idx) {
  168. return *m_UAVs[idx];
  169. }
  170. const HLResource &HLModule::GetUAV(unsigned idx) const {
  171. return *m_UAVs[idx];
  172. }
  173. const vector<unique_ptr<HLResource> > &HLModule::GetUAVs() const {
  174. return m_UAVs;
  175. }
  176. void HLModule::RemoveFunction(llvm::Function *F) {
  177. DXASSERT_NOMSG(F != nullptr);
  178. m_HLFunctionPropsMap.erase(F);
  179. if (m_pTypeSystem.get()->GetFunctionAnnotation(F))
  180. m_pTypeSystem.get()->EraseFunctionAnnotation(F);
  181. m_pOP->RemoveFunction(F);
  182. }
  183. template <typename TResource>
  184. bool RemoveResource(std::vector<std::unique_ptr<TResource>> &vec,
  185. GlobalVariable *pVariable) {
  186. for (auto p = vec.begin(), e = vec.end(); p != e; ++p) {
  187. if ((*p)->GetGlobalSymbol() == pVariable) {
  188. p = vec.erase(p);
  189. // Update ID.
  190. for (e = vec.end();p != e; ++p) {
  191. unsigned ID = (*p)->GetID()-1;
  192. (*p)->SetID(ID);
  193. }
  194. return true;
  195. }
  196. }
  197. return false;
  198. }
  199. bool RemoveResource(std::vector<GlobalVariable *> &vec,
  200. llvm::GlobalVariable *pVariable) {
  201. for (auto p = vec.begin(), e = vec.end(); p != e; ++p) {
  202. if (*p == pVariable) {
  203. vec.erase(p);
  204. return true;
  205. }
  206. }
  207. return false;
  208. }
  209. void HLModule::RemoveGlobal(llvm::GlobalVariable *GV) {
  210. RemoveResources(&GV, 1);
  211. }
  212. void HLModule::RemoveResources(llvm::GlobalVariable **ppVariables,
  213. unsigned count) {
  214. DXASSERT_NOMSG(count == 0 || ppVariables != nullptr);
  215. unsigned resourcesRemoved = count;
  216. for (unsigned i = 0; i < count; ++i) {
  217. GlobalVariable *pVariable = ppVariables[i];
  218. // This could be considerably faster - check variable type to see which
  219. // resource type this is rather than scanning all lists, and look for
  220. // usage and removal patterns.
  221. if (RemoveResource(m_CBuffers, pVariable))
  222. continue;
  223. if (RemoveResource(m_SRVs, pVariable))
  224. continue;
  225. if (RemoveResource(m_UAVs, pVariable))
  226. continue;
  227. if (RemoveResource(m_Samplers, pVariable))
  228. continue;
  229. // TODO: do m_TGSMVariables and m_StreamOutputs need maintenance?
  230. --resourcesRemoved; // Global variable is not a resource?
  231. }
  232. }
  233. HLModule::tgsm_iterator HLModule::tgsm_begin() {
  234. return m_TGSMVariables.begin();
  235. }
  236. HLModule::tgsm_iterator HLModule::tgsm_end() {
  237. return m_TGSMVariables.end();
  238. }
  239. void HLModule::AddGroupSharedVariable(GlobalVariable *GV) {
  240. m_TGSMVariables.emplace_back(GV);
  241. }
  242. DxilSignature &HLModule::GetInputSignature() {
  243. return *m_InputSignature;
  244. }
  245. DxilSignature &HLModule::GetOutputSignature() {
  246. return *m_OutputSignature;
  247. }
  248. DxilSignature &HLModule::GetPatchConstantSignature() {
  249. return *m_PatchConstantSignature;
  250. }
  251. RootSignatureHandle &HLModule::GetRootSignature() {
  252. return *m_RootSignature;
  253. }
  254. DxilTypeSystem &HLModule::GetTypeSystem() {
  255. return *m_pTypeSystem;
  256. }
  257. DxilSignature *HLModule::ReleaseInputSignature() {
  258. return m_InputSignature.release();
  259. }
  260. DxilSignature *HLModule::ReleaseOutputSignature() {
  261. return m_OutputSignature.release();
  262. }
  263. DxilSignature *HLModule::ReleasePatchConstantSignature() {
  264. return m_PatchConstantSignature.release();
  265. }
  266. DxilTypeSystem *HLModule::ReleaseTypeSystem() {
  267. return m_pTypeSystem.release();
  268. }
  269. hlsl::OP *HLModule::ReleaseOP() {
  270. return m_pOP.release();
  271. }
  272. RootSignatureHandle *HLModule::ReleaseRootSignature() {
  273. return m_RootSignature.release();
  274. }
  275. void HLModule::EmitLLVMUsed() {
  276. if (m_LLVMUsed.empty())
  277. return;
  278. vector<llvm::Constant*> GVs;
  279. GVs.resize(m_LLVMUsed.size());
  280. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  281. GVs[i] = ConstantExpr::getAddrSpaceCast(cast<llvm::Constant>(&*m_LLVMUsed[i]), Type::getInt8PtrTy(m_Ctx));
  282. }
  283. ArrayType *pATy = ArrayType::get(Type::getInt8PtrTy(m_Ctx), GVs.size());
  284. GlobalVariable *pGV = new GlobalVariable(*m_pModule, pATy, false,
  285. GlobalValue::AppendingLinkage,
  286. ConstantArray::get(pATy, GVs),
  287. "llvm.used");
  288. pGV->setSection("llvm.metadata");
  289. }
  290. vector<GlobalVariable* > &HLModule::GetLLVMUsed() {
  291. return m_LLVMUsed;
  292. }
  293. bool HLModule::HasHLFunctionProps(llvm::Function *F) {
  294. return m_HLFunctionPropsMap.find(F) != m_HLFunctionPropsMap.end();
  295. }
  296. HLFunctionProps &HLModule::GetHLFunctionProps(llvm::Function *F) {
  297. return *m_HLFunctionPropsMap[F];
  298. }
  299. void HLModule::AddHLFunctionProps(llvm::Function *F, std::unique_ptr<HLFunctionProps> &info) {
  300. DXASSERT(m_HLFunctionPropsMap.count(F) == 0, "F already in map, info will be overwritten");
  301. m_HLFunctionPropsMap[F] = std::move(info);
  302. }
  303. DxilFunctionAnnotation *HLModule::GetFunctionAnnotation(llvm::Function *F) {
  304. return m_pTypeSystem->GetFunctionAnnotation(F);
  305. }
  306. DxilFunctionAnnotation *HLModule::AddFunctionAnnotation(llvm::Function *F) {
  307. DXASSERT(m_pTypeSystem->GetFunctionAnnotation(F)==nullptr, "function annotation already exist");
  308. return m_pTypeSystem->AddFunctionAnnotation(F);
  309. }
  310. void HLModule::AddResourceTypeAnnotation(llvm::Type *Ty,
  311. DXIL::ResourceClass resClass,
  312. DXIL::ResourceKind kind) {
  313. if (m_ResTypeAnnotation.count(Ty) == 0) {
  314. m_ResTypeAnnotation.emplace(Ty, std::make_pair(resClass, kind));
  315. } else {
  316. DXASSERT(resClass == m_ResTypeAnnotation[Ty].first, "resClass mismatch");
  317. DXASSERT(kind == m_ResTypeAnnotation[Ty].second, "kind mismatch");
  318. }
  319. }
  320. DXIL::ResourceClass HLModule::GetResourceClass(llvm::Type *Ty) {
  321. if (m_ResTypeAnnotation.count(Ty) > 0) {
  322. return m_ResTypeAnnotation[Ty].first;
  323. } else {
  324. return DXIL::ResourceClass::Invalid;
  325. }
  326. }
  327. DXIL::ResourceKind HLModule::GetResourceKind(llvm::Type *Ty) {
  328. if (m_ResTypeAnnotation.count(Ty) > 0) {
  329. return m_ResTypeAnnotation[Ty].second;
  330. } else {
  331. return DXIL::ResourceKind::Invalid;
  332. }
  333. }
  334. static unsigned GetIntAt(MDTuple *tuple, unsigned idx) {
  335. return DxilMDHelper::ConstMDToUint32(tuple->getOperand(idx));
  336. }
  337. static unsigned GetFloatAt(MDTuple *tuple, unsigned idx) {
  338. return DxilMDHelper::ConstMDToFloat(tuple->getOperand(idx));
  339. }
  340. static const StringRef kHLDxilFunctionPropertiesMDName = "dx.fnprops";
  341. static const StringRef kHLDxilOptionsMDName = "dx.options";
  342. static const StringRef kHLDxilResourceTypeAnnotationMDName = "dx.resource.type.annotation";
  343. // DXIL metadata serialization/deserialization.
  344. void HLModule::EmitHLMetadata() {
  345. m_pMDHelper->EmitDxilVersion(m_DxilMajor, m_DxilMinor);
  346. m_pMDHelper->EmitDxilShaderModel(m_pSM);
  347. MDTuple *pMDSignatures = m_pMDHelper->EmitDxilSignatures(*m_InputSignature,
  348. *m_OutputSignature,
  349. *m_PatchConstantSignature);
  350. MDTuple *pMDResources = EmitHLResources();
  351. MDTuple *pMDProperties = EmitHLShaderProperties();
  352. m_pMDHelper->EmitDxilTypeSystem(GetTypeSystem(), m_LLVMUsed);
  353. EmitLLVMUsed();
  354. MDTuple *pEntry = m_pMDHelper->EmitDxilEntryPointTuple(GetEntryFunction(), m_EntryName, pMDSignatures, pMDResources, pMDProperties);
  355. vector<MDNode *> Entries;
  356. Entries.emplace_back(pEntry);
  357. m_pMDHelper->EmitDxilEntryPoints(Entries);
  358. {
  359. NamedMDNode * fnProps = m_pModule->getOrInsertNamedMetadata(kHLDxilFunctionPropertiesMDName);
  360. for (auto && pair : m_HLFunctionPropsMap) {
  361. const hlsl::HLFunctionProps * props = pair.second.get();
  362. Metadata *MDVals[30];
  363. std::fill(MDVals, MDVals + _countof(MDVals), nullptr);
  364. unsigned valIdx = 0;
  365. MDVals[valIdx++] = ValueAsMetadata::get(pair.first);
  366. switch (m_pSM->GetKind()) {
  367. case DXIL::ShaderKind::Compute:
  368. MDVals[valIdx++] = m_pMDHelper->Uint32ToConstMD(props->ShaderProps.CS.numThreads[0]);
  369. MDVals[valIdx++] = m_pMDHelper->Uint32ToConstMD(props->ShaderProps.CS.numThreads[1]);
  370. MDVals[valIdx++] = m_pMDHelper->Uint32ToConstMD(props->ShaderProps.CS.numThreads[2]);
  371. break;
  372. case DXIL::ShaderKind::Geometry:
  373. MDVals[valIdx++] = m_pMDHelper->Uint8ToConstMD((uint8_t)props->ShaderProps.GS.inputPrimitive);
  374. MDVals[valIdx++] = m_pMDHelper->Uint32ToConstMD(props->ShaderProps.GS.maxVertexCount);
  375. for (size_t i = 0; i < _countof(props->ShaderProps.GS.streamPrimitiveTopologies); ++i)
  376. MDVals[valIdx++] = m_pMDHelper->Uint8ToConstMD((uint8_t)props->ShaderProps.GS.streamPrimitiveTopologies[i]);
  377. break;
  378. case DXIL::ShaderKind::Hull:
  379. MDVals[valIdx++] = ValueAsMetadata::get(props->ShaderProps.HS.patchConstantFunc);
  380. MDVals[valIdx++] = m_pMDHelper->Uint8ToConstMD((uint8_t)props->ShaderProps.HS.domain);
  381. MDVals[valIdx++] = m_pMDHelper->Uint8ToConstMD((uint8_t)props->ShaderProps.HS.partition);
  382. MDVals[valIdx++] = m_pMDHelper->Uint8ToConstMD((uint8_t)props->ShaderProps.HS.outputPrimitive);
  383. MDVals[valIdx++] = m_pMDHelper->Uint32ToConstMD(props->ShaderProps.HS.inputControlPoints);
  384. MDVals[valIdx++] = m_pMDHelper->Uint32ToConstMD(props->ShaderProps.HS.outputControlPoints);
  385. MDVals[valIdx++] = m_pMDHelper->FloatToConstMD(props->ShaderProps.HS.maxTessFactor);
  386. break;
  387. case DXIL::ShaderKind::Domain:
  388. MDVals[valIdx++] = m_pMDHelper->Uint8ToConstMD((uint8_t)props->ShaderProps.DS.domain);
  389. MDVals[valIdx++] = m_pMDHelper->Uint32ToConstMD(props->ShaderProps.DS.inputControlPoints);
  390. break;
  391. case DXIL::ShaderKind::Pixel:
  392. MDVals[valIdx++] = m_pMDHelper->BoolToConstMD(props->ShaderProps.PS.EarlyDepthStencil);
  393. break;
  394. }
  395. fnProps->addOperand(MDTuple::get(m_Ctx, ArrayRef<llvm::Metadata *>(MDVals, valIdx)));
  396. }
  397. NamedMDNode * options = m_pModule->getOrInsertNamedMetadata(kHLDxilOptionsMDName);
  398. uint32_t hlOptions = m_Options.GetHLOptionsRaw();
  399. options->addOperand(MDNode::get(m_Ctx, m_pMDHelper->Uint32ToConstMD(hlOptions)));
  400. NamedMDNode * resTyAnnotations = m_pModule->getOrInsertNamedMetadata(kHLDxilResourceTypeAnnotationMDName);
  401. resTyAnnotations->addOperand(EmitResTyAnnotations());
  402. }
  403. if (!m_RootSignature->IsEmpty()) {
  404. m_pMDHelper->EmitRootSignature(*m_RootSignature.get());
  405. }
  406. }
  407. void HLModule::LoadHLMetadata() {
  408. m_pMDHelper->LoadDxilVersion(m_DxilMajor, m_DxilMinor);
  409. m_pMDHelper->LoadDxilShaderModel(m_pSM);
  410. CreateSignatures(m_pSM, m_InputSignature, m_OutputSignature, m_PatchConstantSignature, m_RootSignature);
  411. const llvm::NamedMDNode *pEntries = m_pMDHelper->GetDxilEntryPoints();
  412. Function *pEntryFunc;
  413. string EntryName;
  414. const llvm::MDOperand *pSignatures, *pResources, *pProperties;
  415. m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(0), pEntryFunc, EntryName, pSignatures, pResources, pProperties);
  416. SetEntryFunction(pEntryFunc);
  417. SetEntryFunctionName(EntryName);
  418. m_pMDHelper->LoadDxilSignatures(*pSignatures, *m_InputSignature,
  419. *m_OutputSignature, *m_PatchConstantSignature);
  420. LoadHLResources(*pResources);
  421. LoadHLShaderProperties(*pProperties);
  422. m_pMDHelper->LoadDxilTypeSystem(*m_pTypeSystem.get());
  423. {
  424. NamedMDNode * fnProps = m_pModule->getNamedMetadata(kHLDxilFunctionPropertiesMDName);
  425. size_t propIdx = 0;
  426. while (propIdx < fnProps->getNumOperands()) {
  427. MDTuple *pProps = dyn_cast<MDTuple>(fnProps->getOperand(propIdx++));
  428. std::unique_ptr<hlsl::HLFunctionProps> props = llvm::make_unique<hlsl::HLFunctionProps>();
  429. unsigned idx = 0;
  430. Function *F = dyn_cast<Function>(dyn_cast<ValueAsMetadata>(pProps->getOperand(idx++))->getValue());
  431. switch (m_pSM->GetKind()) {
  432. case DXIL::ShaderKind::Compute:
  433. props->ShaderProps.CS.numThreads[0] = GetIntAt(pProps, idx++);
  434. props->ShaderProps.CS.numThreads[1] = GetIntAt(pProps, idx++);
  435. props->ShaderProps.CS.numThreads[2] = GetIntAt(pProps, idx++);
  436. break;
  437. case DXIL::ShaderKind::Geometry:
  438. props->ShaderProps.GS.inputPrimitive = (DXIL::InputPrimitive)GetIntAt(pProps, idx++);
  439. props->ShaderProps.GS.maxVertexCount = GetIntAt(pProps, idx++);
  440. for (size_t i = 0; i < _countof(props->ShaderProps.GS.streamPrimitiveTopologies); ++i)
  441. props->ShaderProps.GS.streamPrimitiveTopologies[i] = (DXIL::PrimitiveTopology)GetIntAt(pProps, idx++);
  442. break;
  443. case DXIL::ShaderKind::Hull:
  444. props->ShaderProps.HS.patchConstantFunc = dyn_cast<Function>(dyn_cast<ValueAsMetadata>(pProps->getOperand(idx++))->getValue());
  445. props->ShaderProps.HS.domain = (DXIL::TessellatorDomain)GetIntAt(pProps, idx++);
  446. props->ShaderProps.HS.partition = (DXIL::TessellatorPartitioning)GetIntAt(pProps, idx++);
  447. props->ShaderProps.HS.outputPrimitive = (DXIL::TessellatorOutputPrimitive)GetIntAt(pProps, idx++);
  448. props->ShaderProps.HS.inputControlPoints = GetIntAt(pProps, idx++);
  449. props->ShaderProps.HS.outputControlPoints = GetIntAt(pProps, idx++);
  450. props->ShaderProps.HS.maxTessFactor = GetFloatAt(pProps, idx++);
  451. break;
  452. case DXIL::ShaderKind::Domain:
  453. props->ShaderProps.DS.domain = (DXIL::TessellatorDomain)GetIntAt(pProps, idx++);
  454. props->ShaderProps.DS.inputControlPoints = GetIntAt(pProps, idx++);
  455. break;
  456. case DXIL::ShaderKind::Pixel:
  457. props->ShaderProps.PS.EarlyDepthStencil = GetIntAt(pProps, idx++);
  458. break;
  459. }
  460. m_HLFunctionPropsMap[F] = std::move(props);
  461. }
  462. const NamedMDNode * options = m_pModule->getOrInsertNamedMetadata(kHLDxilOptionsMDName);
  463. const MDNode *MDOptions = options->getOperand(0);
  464. m_Options.SetHLOptionsRaw(DxilMDHelper::ConstMDToUint32(MDOptions->getOperand(0)));
  465. NamedMDNode * resTyAnnotations = m_pModule->getOrInsertNamedMetadata(kHLDxilResourceTypeAnnotationMDName);
  466. const MDNode *MDResTyAnnotations = resTyAnnotations->getOperand(0);
  467. if (MDResTyAnnotations->getNumOperands())
  468. LoadResTyAnnotations(MDResTyAnnotations->getOperand(0));
  469. }
  470. m_pMDHelper->LoadRootSignature(*m_RootSignature.get());
  471. }
  472. void HLModule::ClearHLMetadata(llvm::Module &M) {
  473. Module::named_metadata_iterator
  474. b = M.named_metadata_begin(),
  475. e = M.named_metadata_end();
  476. SmallVector<NamedMDNode*, 8> nodes;
  477. for (; b != e; ++b) {
  478. StringRef name = b->getName();
  479. if (name == DxilMDHelper::kDxilVersionMDName ||
  480. name == DxilMDHelper::kDxilShaderModelMDName ||
  481. name == DxilMDHelper::kDxilEntryPointsMDName ||
  482. name == DxilMDHelper::kDxilRootSignatureMDName ||
  483. name == DxilMDHelper::kDxilResourcesMDName ||
  484. name == DxilMDHelper::kDxilTypeSystemMDName ||
  485. name == kHLDxilFunctionPropertiesMDName || // TODO: adjust to proper name
  486. name == kHLDxilResourceTypeAnnotationMDName ||
  487. name == kHLDxilOptionsMDName ||
  488. name.startswith(DxilMDHelper::kDxilTypeSystemHelperVariablePrefix)) {
  489. nodes.push_back(b);
  490. }
  491. }
  492. for (size_t i = 0; i < nodes.size(); ++i) {
  493. M.eraseNamedMetadata(nodes[i]);
  494. }
  495. }
  496. MDTuple *HLModule::EmitHLResources() {
  497. // Emit SRV records.
  498. MDTuple *pTupleSRVs = nullptr;
  499. if (!m_SRVs.empty()) {
  500. vector<Metadata *> MDVals;
  501. for (size_t i = 0; i < m_SRVs.size(); i++) {
  502. MDVals.emplace_back(m_pMDHelper->EmitDxilSRV(*m_SRVs[i]));
  503. }
  504. pTupleSRVs = MDNode::get(m_Ctx, MDVals);
  505. }
  506. // Emit UAV records.
  507. MDTuple *pTupleUAVs = nullptr;
  508. if (!m_UAVs.empty()) {
  509. vector<Metadata *> MDVals;
  510. for (size_t i = 0; i < m_UAVs.size(); i++) {
  511. MDVals.emplace_back(m_pMDHelper->EmitDxilUAV(*m_UAVs[i]));
  512. }
  513. pTupleUAVs = MDNode::get(m_Ctx, MDVals);
  514. }
  515. // Emit CBuffer records.
  516. MDTuple *pTupleCBuffers = nullptr;
  517. if (!m_CBuffers.empty()) {
  518. vector<Metadata *> MDVals;
  519. for (size_t i = 0; i < m_CBuffers.size(); i++) {
  520. MDVals.emplace_back(m_pMDHelper->EmitDxilCBuffer(*m_CBuffers[i]));
  521. }
  522. pTupleCBuffers = MDNode::get(m_Ctx, MDVals);
  523. }
  524. // Emit Sampler records.
  525. MDTuple *pTupleSamplers = nullptr;
  526. if (!m_Samplers.empty()) {
  527. vector<Metadata *> MDVals;
  528. for (size_t i = 0; i < m_Samplers.size(); i++) {
  529. MDVals.emplace_back(m_pMDHelper->EmitDxilSampler(*m_Samplers[i]));
  530. }
  531. pTupleSamplers = MDNode::get(m_Ctx, MDVals);
  532. }
  533. if (pTupleSRVs != nullptr || pTupleUAVs != nullptr || pTupleCBuffers != nullptr || pTupleSamplers != nullptr) {
  534. return m_pMDHelper->EmitDxilResourceTuple(pTupleSRVs, pTupleUAVs, pTupleCBuffers, pTupleSamplers);
  535. } else {
  536. return nullptr;
  537. }
  538. }
  539. void HLModule::LoadHLResources(const llvm::MDOperand &MDO) {
  540. const llvm::MDTuple *pSRVs, *pUAVs, *pCBuffers, *pSamplers;
  541. m_pMDHelper->GetDxilResources(MDO, pSRVs, pUAVs, pCBuffers, pSamplers);
  542. // Load SRV records.
  543. if (pSRVs != nullptr) {
  544. for (unsigned i = 0; i < pSRVs->getNumOperands(); i++) {
  545. unique_ptr<HLResource> pSRV(new HLResource);
  546. m_pMDHelper->LoadDxilSRV(pSRVs->getOperand(i), *pSRV);
  547. AddSRV(std::move(pSRV));
  548. }
  549. }
  550. // Load UAV records.
  551. if (pUAVs != nullptr) {
  552. for (unsigned i = 0; i < pUAVs->getNumOperands(); i++) {
  553. unique_ptr<HLResource> pUAV(new HLResource);
  554. m_pMDHelper->LoadDxilUAV(pUAVs->getOperand(i), *pUAV);
  555. AddUAV(std::move(pUAV));
  556. }
  557. }
  558. // Load CBuffer records.
  559. if (pCBuffers != nullptr) {
  560. for (unsigned i = 0; i < pCBuffers->getNumOperands(); i++) {
  561. unique_ptr<DxilCBuffer> pCB = llvm::make_unique<DxilCBuffer>();
  562. m_pMDHelper->LoadDxilCBuffer(pCBuffers->getOperand(i), *pCB);
  563. AddCBuffer(std::move(pCB));
  564. }
  565. }
  566. // Load Sampler records.
  567. if (pSamplers != nullptr) {
  568. for (unsigned i = 0; i < pSamplers->getNumOperands(); i++) {
  569. unique_ptr<DxilSampler> pSampler(new DxilSampler);
  570. m_pMDHelper->LoadDxilSampler(pSamplers->getOperand(i), *pSampler);
  571. AddSampler(std::move(pSampler));
  572. }
  573. }
  574. }
  575. llvm::MDTuple *HLModule::EmitResTyAnnotations() {
  576. vector<Metadata *> MDVals;
  577. for (auto &resAnnotation : m_ResTypeAnnotation) {
  578. Metadata *TyMeta =
  579. ValueAsMetadata::get(UndefValue::get(resAnnotation.first));
  580. MDVals.emplace_back(TyMeta);
  581. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(
  582. static_cast<unsigned>(resAnnotation.second.first)));
  583. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(
  584. static_cast<unsigned>(resAnnotation.second.second)));
  585. }
  586. return MDNode::get(m_Ctx, MDVals);
  587. }
  588. void HLModule::LoadResTyAnnotations(const llvm::MDOperand &MDO) {
  589. if (MDO.get() == nullptr)
  590. return;
  591. const MDTuple *pTupleMD = dyn_cast<MDTuple>(MDO.get());
  592. IFTBOOL(pTupleMD != nullptr, DXC_E_INCORRECT_DXIL_METADATA);
  593. IFTBOOL((pTupleMD->getNumOperands() & 0x3) == 0,
  594. DXC_E_INCORRECT_DXIL_METADATA);
  595. for (unsigned iNode = 0; iNode < pTupleMD->getNumOperands(); iNode += 3) {
  596. const MDOperand &MDTy = pTupleMD->getOperand(iNode);
  597. const MDOperand &MDClass = pTupleMD->getOperand(iNode + 1);
  598. const MDOperand &MDKind = pTupleMD->getOperand(iNode + 2);
  599. Type *Ty = m_pMDHelper->ValueMDToValue(MDTy)->getType();
  600. DXIL::ResourceClass resClass = static_cast<DXIL::ResourceClass>(
  601. DxilMDHelper::ConstMDToUint32(MDClass));
  602. DXIL::ResourceKind kind =
  603. static_cast<DXIL::ResourceKind>(DxilMDHelper::ConstMDToUint32(MDKind));
  604. AddResourceTypeAnnotation(Ty, resClass, kind);
  605. }
  606. }
  607. MDTuple *HLModule::EmitHLShaderProperties() {
  608. return nullptr;
  609. }
  610. void HLModule::LoadHLShaderProperties(const MDOperand &MDO) {
  611. return;
  612. }
  613. MDNode *HLModule::DxilSamplerToMDNode(const DxilSampler &S) {
  614. MDNode *MD = m_pMDHelper->EmitDxilSampler(S);
  615. ValueAsMetadata *ResClass =
  616. m_pMDHelper->Uint32ToConstMD((unsigned)DXIL::ResourceClass::Sampler);
  617. return MDNode::get(m_Ctx, {ResClass, MD});
  618. }
  619. MDNode *HLModule::DxilSRVToMDNode(const DxilResource &SRV) {
  620. MDNode *MD = m_pMDHelper->EmitDxilSRV(SRV);
  621. ValueAsMetadata *ResClass =
  622. m_pMDHelper->Uint32ToConstMD((unsigned)DXIL::ResourceClass::SRV);
  623. return MDNode::get(m_Ctx, {ResClass, MD});
  624. }
  625. MDNode *HLModule::DxilUAVToMDNode(const DxilResource &UAV) {
  626. MDNode *MD = m_pMDHelper->EmitDxilUAV(UAV);
  627. ValueAsMetadata *ResClass =
  628. m_pMDHelper->Uint32ToConstMD((unsigned)DXIL::ResourceClass::UAV);
  629. return MDNode::get(m_Ctx, {ResClass, MD});
  630. }
  631. MDNode *HLModule::DxilCBufferToMDNode(const DxilCBuffer &CB) {
  632. MDNode *MD = m_pMDHelper->EmitDxilCBuffer(CB);
  633. ValueAsMetadata *ResClass =
  634. m_pMDHelper->Uint32ToConstMD((unsigned)DXIL::ResourceClass::CBuffer);
  635. return MDNode::get(m_Ctx, {ResClass, MD});
  636. }
  637. void HLModule::LoadDxilResourceBaseFromMDNode(MDNode *MD, DxilResourceBase &R) {
  638. return m_pMDHelper->LoadDxilResourceBaseFromMDNode(MD, R);
  639. }
  640. void HLModule::AddResourceWithGlobalVariableAndMDNode(llvm::Constant *GV,
  641. llvm::MDNode *MD) {
  642. IFTBOOL(MD->getNumOperands() >= DxilMDHelper::kHLDxilResourceAttributeNumFields,
  643. DXC_E_INCORRECT_DXIL_METADATA);
  644. DxilResource::Class RC =
  645. static_cast<DxilResource::Class>(m_pMDHelper->ConstMDToUint32(
  646. MD->getOperand(DxilMDHelper::kHLDxilResourceAttributeClass)));
  647. const MDOperand &Meta =
  648. MD->getOperand(DxilMDHelper::kHLDxilResourceAttributeMeta);
  649. unsigned rangeSize = 1;
  650. Type *Ty = GV->getType()->getPointerElementType();
  651. if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
  652. rangeSize = AT->getNumElements();
  653. switch (RC) {
  654. case DxilResource::Class::Sampler: {
  655. std::unique_ptr<DxilSampler> S = llvm::make_unique<DxilSampler>();
  656. m_pMDHelper->LoadDxilSampler(Meta, *S);
  657. S->SetGlobalSymbol(GV);
  658. S->SetGlobalName(GV->getName());
  659. S->SetRangeSize(rangeSize);
  660. AddSampler(std::move(S));
  661. } break;
  662. case DxilResource::Class::SRV: {
  663. std::unique_ptr<HLResource> Res = llvm::make_unique<HLResource>();
  664. m_pMDHelper->LoadDxilSRV(Meta, *Res);
  665. Res->SetGlobalSymbol(GV);
  666. Res->SetGlobalName(GV->getName());
  667. Res->SetRangeSize(rangeSize);
  668. AddSRV(std::move(Res));
  669. } break;
  670. case DxilResource::Class::UAV: {
  671. std::unique_ptr<HLResource> Res = llvm::make_unique<HLResource>();
  672. m_pMDHelper->LoadDxilUAV(Meta, *Res);
  673. Res->SetGlobalSymbol(GV);
  674. Res->SetGlobalName(GV->getName());
  675. Res->SetRangeSize(rangeSize);
  676. AddUAV(std::move(Res));
  677. } break;
  678. default:
  679. DXASSERT(0, "Invalid metadata for AddResourceWithGlobalVariableAndMDNode");
  680. }
  681. }
  682. // TODO: Don't check names.
  683. bool HLModule::IsStreamOutputType(llvm::Type *Ty) {
  684. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  685. if (ST->getName().startswith("class.PointStream"))
  686. return true;
  687. if (ST->getName().startswith("class.LineStream"))
  688. return true;
  689. if (ST->getName().startswith("class.TriangleStream"))
  690. return true;
  691. }
  692. return false;
  693. }
  694. bool HLModule::IsStreamOutputPtrType(llvm::Type *Ty) {
  695. if (!Ty->isPointerTy())
  696. return false;
  697. Ty = Ty->getPointerElementType();
  698. return IsStreamOutputType(Ty);
  699. }
  700. bool HLModule::IsHLSLObjectType(llvm::Type *Ty) {
  701. if (llvm::StructType *ST = dyn_cast<llvm::StructType>(Ty)) {
  702. StringRef name = ST->getName();
  703. if (name.startswith("dx.types.wave_t"))
  704. return true;
  705. if (name.endswith("_slice_type"))
  706. return false;
  707. name = name.ltrim("class.");
  708. name = name.ltrim("struct.");
  709. if (name == "SamplerState")
  710. return true;
  711. if (name == "SamplerComparisonState")
  712. return true;
  713. if (name.startswith("TriangleStream"))
  714. return true;
  715. if (name.startswith("PointStream"))
  716. return true;
  717. if (name.startswith("LineStream"))
  718. return true;
  719. if (name.startswith("AppendStructuredBuffer"))
  720. return true;
  721. if (name.startswith("ConsumeStructuredBuffer"))
  722. return true;
  723. if (name.startswith("ConstantBuffer"))
  724. return true;
  725. name = name.ltrim("RasterizerOrdered");
  726. name = name.ltrim("RW");
  727. if (name == "ByteAddressBuffer")
  728. return true;
  729. if (name.startswith("Buffer"))
  730. return true;
  731. if (name.startswith("StructuredBuffer"))
  732. return true;
  733. if (name.startswith("Texture1D"))
  734. return true;
  735. if (name.startswith("Texture1DArray"))
  736. return true;
  737. if (name.startswith("Texture2D"))
  738. return true;
  739. if (name.startswith("Texture2DArray"))
  740. return true;
  741. if (name.startswith("Texture3D"))
  742. return true;
  743. if (name.startswith("TextureCube"))
  744. return true;
  745. if (name.startswith("TextureCubeArray"))
  746. return true;
  747. if (name.startswith("Texture2DMS"))
  748. return true;
  749. if (name.startswith("Texture2DMSArray"))
  750. return true;
  751. }
  752. return false;
  753. }
  754. unsigned
  755. HLModule::GetLegacyCBufferFieldElementSize(DxilFieldAnnotation &fieldAnnotation,
  756. llvm::Type *Ty,
  757. DxilTypeSystem &typeSys) {
  758. while (isa<ArrayType>(Ty)) {
  759. Ty = Ty->getArrayElementType();
  760. }
  761. // Bytes.
  762. unsigned compSize = fieldAnnotation.GetCompType().Is64Bit()?8:4;
  763. unsigned fieldSize = compSize;
  764. if (Ty->isVectorTy()) {
  765. fieldSize *= Ty->getVectorNumElements();
  766. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  767. DxilStructAnnotation *EltAnnotation = typeSys.GetStructAnnotation(ST);
  768. if (EltAnnotation) {
  769. fieldSize = EltAnnotation->GetCBufferSize();
  770. } else {
  771. // Calculate size when don't have annotation.
  772. if (fieldAnnotation.HasMatrixAnnotation()) {
  773. const DxilMatrixAnnotation &matAnnotation =
  774. fieldAnnotation.GetMatrixAnnotation();
  775. unsigned rows = matAnnotation.Rows;
  776. unsigned cols = matAnnotation.Cols;
  777. if (matAnnotation.Orientation == MatrixOrientation::ColumnMajor) {
  778. rows = cols;
  779. cols = matAnnotation.Rows;
  780. } else if (matAnnotation.Orientation != MatrixOrientation::RowMajor) {
  781. // Invalid matrix orientation.
  782. fieldSize = 0;
  783. }
  784. fieldSize = (rows - 1) * 16 + cols * 4;
  785. } else {
  786. // Cannot find struct annotation.
  787. fieldSize = 0;
  788. }
  789. }
  790. }
  791. return fieldSize;
  792. }
  793. bool HLModule::IsStaticGlobal(GlobalVariable *GV) {
  794. return GV->getLinkage() == GlobalValue::LinkageTypes::InternalLinkage &&
  795. GV->getType()->getPointerAddressSpace() == DXIL::kDefaultAddrSpace;
  796. }
  797. bool HLModule::IsSharedMemoryGlobal(llvm::GlobalVariable *GV) {
  798. return GV->getType()->getPointerAddressSpace() == DXIL::kTGSMAddrSpace;
  799. }
  800. void HLModule::GetParameterRowsAndCols(Type *Ty, unsigned &rows, unsigned &cols,
  801. DxilParameterAnnotation &paramAnnotation) {
  802. if (Ty->isPointerTy())
  803. Ty = Ty->getPointerElementType();
  804. // For array input of HS, DS, GS,
  805. // we need to skip the first level which size is based on primitive type.
  806. DxilParamInputQual inputQual = paramAnnotation.GetParamInputQual();
  807. bool skipOneLevelArray = inputQual == DxilParamInputQual::InputPatch;
  808. skipOneLevelArray |= inputQual == DxilParamInputQual::OutputPatch;
  809. skipOneLevelArray |= inputQual == DxilParamInputQual::InputPrimitive;
  810. if (skipOneLevelArray) {
  811. if (Ty->isArrayTy())
  812. Ty = Ty->getArrayElementType();
  813. }
  814. unsigned arraySize = 1;
  815. while (Ty->isArrayTy()) {
  816. arraySize *= Ty->getArrayNumElements();
  817. Ty = Ty->getArrayElementType();
  818. }
  819. rows = 1;
  820. cols = 1;
  821. if (paramAnnotation.HasMatrixAnnotation()) {
  822. const DxilMatrixAnnotation &matrix = paramAnnotation.GetMatrixAnnotation();
  823. if (matrix.Orientation == MatrixOrientation::RowMajor) {
  824. rows = matrix.Rows;
  825. cols = matrix.Cols;
  826. } else {
  827. DXASSERT(matrix.Orientation == MatrixOrientation::ColumnMajor, "");
  828. cols = matrix.Rows;
  829. rows = matrix.Cols;
  830. }
  831. } else if (Ty->isVectorTy())
  832. cols = Ty->getVectorNumElements();
  833. rows *= arraySize;
  834. }
  835. // For legacy data layout, everything less than 32 align to 32.
  836. static const StringRef kLegacyLayoutString = "e-m:e-p:32:32-i1:32:32-i8:32:32-i16:32:32-i64:64-f16:32-f80:32-n8:16:32-a:0:32-S32";
  837. const char *HLModule::GetLegacyDataLayoutDesc() {
  838. return kLegacyLayoutString.data();
  839. }
  840. static Value *MergeGEP(GEPOperator *SrcGEP, GetElementPtrInst *GEP) {
  841. IRBuilder<> Builder(GEP);
  842. SmallVector<Value *, 8> Indices;
  843. // Find out whether the last index in the source GEP is a sequential idx.
  844. bool EndsWithSequential = false;
  845. for (gep_type_iterator I = gep_type_begin(*SrcGEP), E = gep_type_end(*SrcGEP);
  846. I != E; ++I)
  847. EndsWithSequential = !(*I)->isStructTy();
  848. if (EndsWithSequential) {
  849. Value *Sum;
  850. Value *SO1 = SrcGEP->getOperand(SrcGEP->getNumOperands() - 1);
  851. Value *GO1 = GEP->getOperand(1);
  852. if (SO1 == Constant::getNullValue(SO1->getType())) {
  853. Sum = GO1;
  854. } else if (GO1 == Constant::getNullValue(GO1->getType())) {
  855. Sum = SO1;
  856. } else {
  857. // If they aren't the same type, then the input hasn't been processed
  858. // by the loop above yet (which canonicalizes sequential index types to
  859. // intptr_t). Just avoid transforming this until the input has been
  860. // normalized.
  861. if (SO1->getType() != GO1->getType())
  862. return nullptr;
  863. // Only do the combine when GO1 and SO1 are both constants. Only in
  864. // this case, we are sure the cost after the merge is never more than
  865. // that before the merge.
  866. if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
  867. return nullptr;
  868. Sum = Builder.CreateAdd(SO1, GO1);
  869. }
  870. // Update the GEP in place if possible.
  871. if (SrcGEP->getNumOperands() == 2) {
  872. GEP->setOperand(0, SrcGEP->getOperand(0));
  873. GEP->setOperand(1, Sum);
  874. return GEP;
  875. }
  876. Indices.append(SrcGEP->op_begin() + 1, SrcGEP->op_end() - 1);
  877. Indices.push_back(Sum);
  878. Indices.append(GEP->op_begin() + 2, GEP->op_end());
  879. } else if (isa<Constant>(*GEP->idx_begin()) &&
  880. cast<Constant>(*GEP->idx_begin())->isNullValue() &&
  881. SrcGEP->getNumOperands() != 1) {
  882. // Otherwise we can do the fold if the first index of the GEP is a zero
  883. Indices.append(SrcGEP->op_begin() + 1, SrcGEP->op_end());
  884. Indices.append(GEP->idx_begin() + 1, GEP->idx_end());
  885. }
  886. if (!Indices.empty())
  887. return Builder.CreateInBoundsGEP(SrcGEP->getSourceElementType(),
  888. SrcGEP->getOperand(0), Indices,
  889. GEP->getName());
  890. else
  891. llvm_unreachable("must merge");
  892. }
  893. void HLModule::MergeGepUse(Value *V) {
  894. for (auto U = V->user_begin(); U != V->user_end();) {
  895. auto Use = U++;
  896. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*Use)) {
  897. if (GEPOperator *prevGEP = dyn_cast<GEPOperator>(V)) {
  898. // merge the 2 GEPs
  899. Value *newGEP = MergeGEP(prevGEP, GEP);
  900. GEP->replaceAllUsesWith(newGEP);
  901. GEP->eraseFromParent();
  902. MergeGepUse(newGEP);
  903. } else {
  904. MergeGepUse(*Use);
  905. }
  906. } else if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(*Use)) {
  907. if (GEPOperator *prevGEP = dyn_cast<GEPOperator>(V)) {
  908. // merge the 2 GEPs
  909. Value *newGEP = MergeGEP(prevGEP, GEP);
  910. GEP->replaceAllUsesWith(newGEP);
  911. GEP->eraseFromParent();
  912. MergeGepUse(newGEP);
  913. } else {
  914. MergeGepUse(*Use);
  915. }
  916. }
  917. }
  918. if (V->user_empty()) {
  919. // Only remove GEP here, root ptr will be removed by DCE.
  920. if (GetElementPtrInst *I = dyn_cast<GetElementPtrInst>(V))
  921. I->eraseFromParent();
  922. }
  923. }
  924. template<typename BuilderTy>
  925. CallInst *HLModule::EmitHLOperationCall(BuilderTy &Builder,
  926. HLOpcodeGroup group, unsigned opcode,
  927. Type *RetType,
  928. ArrayRef<Value *> paramList,
  929. llvm::Module &M) {
  930. SmallVector<llvm::Type *, 4> paramTyList;
  931. // Add the opcode param
  932. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  933. paramTyList.emplace_back(opcodeTy);
  934. for (Value *param : paramList) {
  935. paramTyList.emplace_back(param->getType());
  936. }
  937. llvm::FunctionType *funcTy =
  938. llvm::FunctionType::get(RetType, paramTyList, false);
  939. Function *opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  940. SmallVector<Value *, 4> opcodeParamList;
  941. Value *opcodeConst = Constant::getIntegerValue(opcodeTy, APInt(32, opcode));
  942. opcodeParamList.emplace_back(opcodeConst);
  943. opcodeParamList.append(paramList.begin(), paramList.end());
  944. return Builder.CreateCall(opFunc, opcodeParamList);
  945. }
  946. template
  947. CallInst *HLModule::EmitHLOperationCall(IRBuilder<> &Builder,
  948. HLOpcodeGroup group, unsigned opcode,
  949. Type *RetType,
  950. ArrayRef<Value *> paramList,
  951. llvm::Module &M);
  952. unsigned HLModule::FindCastOp(bool fromUnsigned, bool toUnsigned,
  953. llvm::Type *SrcTy, llvm::Type *DstTy) {
  954. Instruction::CastOps castOp = llvm::Instruction::CastOps::BitCast;
  955. if (SrcTy->isAggregateType() || DstTy->isAggregateType())
  956. return llvm::Instruction::CastOps::BitCast;
  957. uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
  958. uint32_t DstBitSize = DstTy->getScalarSizeInBits();
  959. if (SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy()) {
  960. if (SrcBitSize > DstBitSize)
  961. return Instruction::Trunc;
  962. if (toUnsigned)
  963. return Instruction::ZExt;
  964. else
  965. return Instruction::SExt;
  966. }
  967. if (SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy()) {
  968. if (SrcBitSize > DstBitSize)
  969. return Instruction::FPTrunc;
  970. else
  971. return Instruction::FPExt;
  972. }
  973. if (SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy())
  974. if (fromUnsigned)
  975. return Instruction::UIToFP;
  976. else
  977. return Instruction::SIToFP;
  978. if (SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy())
  979. if (toUnsigned)
  980. return Instruction::FPToUI;
  981. else
  982. return Instruction::FPToSI;
  983. DXASSERT_NOMSG(0);
  984. return castOp;
  985. }
  986. bool HLModule::HasPreciseAttributeWithMetadata(Instruction *I) {
  987. MDNode *preciseNode =
  988. I->getMetadata(DxilMDHelper::kDxilPreciseAttributeMDName);
  989. return preciseNode != nullptr;
  990. }
  991. void HLModule::MarkPreciseAttributeWithMetadata(Instruction *I) {
  992. LLVMContext &Ctx = I->getContext();
  993. MDNode *preciseNode = MDNode::get(
  994. Ctx,
  995. {ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Ctx), 1))});
  996. I->setMetadata(DxilMDHelper::kDxilPreciseAttributeMDName, preciseNode);
  997. }
  998. void HLModule::ClearPreciseAttributeWithMetadata(Instruction *I) {
  999. I->setMetadata(DxilMDHelper::kDxilPreciseAttributeMDName, nullptr);
  1000. }
  1001. static void MarkPreciseAttribute(Function *F) {
  1002. LLVMContext &Ctx = F->getContext();
  1003. MDNode *preciseNode = MDNode::get(
  1004. Ctx, {MDString::get(Ctx, DxilMDHelper::kDxilPreciseAttributeMDName)});
  1005. F->setMetadata(DxilMDHelper::kDxilPreciseAttributeMDName, preciseNode);
  1006. }
  1007. static void MarkPreciseAttributeOnValWithFunctionCall(
  1008. llvm::Value *V, llvm::IRBuilder<> &Builder, llvm::Module &M) {
  1009. Type *Ty = V->getType();
  1010. Type *EltTy = Ty->getScalarType();
  1011. // TODO: Only do this on basic types.
  1012. FunctionType *preciseFuncTy =
  1013. FunctionType::get(Type::getVoidTy(M.getContext()), {EltTy}, false);
  1014. // The function will be deleted after precise propagate.
  1015. std::string preciseFuncName = "dx.attribute.precise.";
  1016. raw_string_ostream mangledNameStr(preciseFuncName);
  1017. EltTy->print(mangledNameStr);
  1018. mangledNameStr.flush();
  1019. Function *preciseFunc =
  1020. cast<Function>(M.getOrInsertFunction(preciseFuncName, preciseFuncTy));
  1021. if (!HLModule::HasPreciseAttribute(preciseFunc))
  1022. MarkPreciseAttribute(preciseFunc);
  1023. if (Ty->isVectorTy()) {
  1024. for (unsigned i = 0; i < Ty->getVectorNumElements(); i++) {
  1025. Value *Elt = Builder.CreateExtractElement(V, i);
  1026. Builder.CreateCall(preciseFunc, {Elt});
  1027. }
  1028. } else
  1029. Builder.CreateCall(preciseFunc, {V});
  1030. }
  1031. void HLModule::MarkPreciseAttributeOnPtrWithFunctionCall(llvm::Value *Ptr,
  1032. llvm::Module &M) {
  1033. for (User *U : Ptr->users()) {
  1034. // Skip load inst.
  1035. if (LoadInst *LI = dyn_cast<LoadInst>(U))
  1036. continue;
  1037. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  1038. Value *V = SI->getValueOperand();
  1039. if (isa<Instruction>(V)) {
  1040. // Mark the Value with function call.
  1041. IRBuilder<> Builder(SI);
  1042. MarkPreciseAttributeOnValWithFunctionCall(V, Builder, M);
  1043. }
  1044. } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
  1045. if (CI->getType()->isVoidTy()) {
  1046. IRBuilder<> Builder(CI);
  1047. // For void type, cannot use as function arg.
  1048. // Mark all arg for it?
  1049. for (auto &arg : CI->arg_operands()) {
  1050. MarkPreciseAttributeOnValWithFunctionCall(arg, Builder, M);
  1051. }
  1052. } else {
  1053. IRBuilder<> Builder(CI->getNextNode());
  1054. MarkPreciseAttributeOnValWithFunctionCall(CI, Builder, M);
  1055. }
  1056. } else {
  1057. // Must be GEP here.
  1058. GetElementPtrInst *GEP = cast<GetElementPtrInst>(U);
  1059. MarkPreciseAttributeOnPtrWithFunctionCall(GEP, M);
  1060. }
  1061. }
  1062. }
  1063. bool HLModule::HasPreciseAttribute(Function *F) {
  1064. MDNode *preciseNode =
  1065. F->getMetadata(DxilMDHelper::kDxilPreciseAttributeMDName);
  1066. return preciseNode != nullptr;
  1067. }
  1068. void HLModule::MarkDxilResourceAttrib(llvm::Function *F, MDNode *MD) {
  1069. F->setMetadata(DxilMDHelper::kHLDxilResourceAttributeMDName, MD);
  1070. }
  1071. MDNode *HLModule::GetDxilResourceAttrib(llvm::Function *F) {
  1072. return F->getMetadata(DxilMDHelper::kHLDxilResourceAttributeMDName);
  1073. }
  1074. void HLModule::MarkDxilResourceAttrib(llvm::Argument *Arg, llvm::MDNode *MD) {
  1075. unsigned i = Arg->getArgNo();
  1076. Function *F = Arg->getParent();
  1077. DxilFunctionAnnotation *FuncAnnot = m_pTypeSystem->GetFunctionAnnotation(F);
  1078. if (!FuncAnnot) {
  1079. DXASSERT(0, "Invalid function");
  1080. return;
  1081. }
  1082. DxilParameterAnnotation &ParamAnnot = FuncAnnot->GetParameterAnnotation(i);
  1083. ParamAnnot.SetResourceAttribute(MD);
  1084. }
  1085. MDNode *HLModule::GetDxilResourceAttrib(llvm::Argument *Arg) {
  1086. unsigned i = Arg->getArgNo();
  1087. Function *F = Arg->getParent();
  1088. DxilFunctionAnnotation *FuncAnnot = m_pTypeSystem->GetFunctionAnnotation(F);
  1089. if (!FuncAnnot)
  1090. return nullptr;
  1091. DxilParameterAnnotation &ParamAnnot = FuncAnnot->GetParameterAnnotation(i);
  1092. return ParamAnnot.GetResourceAttribute();
  1093. }
  1094. MDNode *HLModule::GetDxilResourceAttrib(Type *Ty, Module &M) {
  1095. for (Function &F : M.functions()) {
  1096. if (hlsl::GetHLOpcodeGroupByName(&F) == HLOpcodeGroup::HLCreateHandle) {
  1097. Type *ResTy = F.getFunctionType()->getParamType(
  1098. HLOperandIndex::kCreateHandleResourceOpIdx);
  1099. if (ResTy == Ty)
  1100. return GetDxilResourceAttrib(&F);
  1101. }
  1102. }
  1103. return nullptr;
  1104. }
  1105. DIGlobalVariable *
  1106. HLModule::FindGlobalVariableDebugInfo(GlobalVariable *GV,
  1107. DebugInfoFinder &DbgInfoFinder) {
  1108. struct GlobalFinder {
  1109. GlobalVariable *GV;
  1110. bool operator()(llvm::DIGlobalVariable *const arg) const {
  1111. return arg->getVariable() == GV;
  1112. }
  1113. };
  1114. GlobalFinder F = {GV};
  1115. DebugInfoFinder::global_variable_iterator Found =
  1116. std::find_if(DbgInfoFinder.global_variables().begin(),
  1117. DbgInfoFinder.global_variables().end(), F);
  1118. if (Found != DbgInfoFinder.global_variables().end()) {
  1119. return *Found;
  1120. }
  1121. return nullptr;
  1122. }
  1123. static void AddDIGlobalVariable(DIBuilder &Builder, DIGlobalVariable *LocDIGV,
  1124. StringRef Name, DIType *DITy,
  1125. GlobalVariable *GV, DebugInfoFinder &DbgInfoFinder, bool removeLocDIGV) {
  1126. DIGlobalVariable *EltDIGV = Builder.createGlobalVariable(
  1127. LocDIGV->getScope(), Name, GV->getName(), LocDIGV->getFile(),
  1128. LocDIGV->getLine(), DITy, false, GV);
  1129. DICompileUnit *DICU = dyn_cast<DICompileUnit>(LocDIGV->getScope());
  1130. if (!DICU) {
  1131. DISubprogram *DIS = dyn_cast<DISubprogram>(LocDIGV->getScope());
  1132. if (DIS) {
  1133. // Find the DICU which has this Subprogram.
  1134. NamedMDNode *CompileUnits = GV->getParent()->getNamedMetadata("llvm.dbg.cu");
  1135. DXASSERT_NOMSG(CompileUnits);
  1136. for (unsigned I = 0, E = CompileUnits->getNumOperands(); I != E; ++I) {
  1137. auto *CU = cast<DICompileUnit>(CompileUnits->getOperand(I));
  1138. DXASSERT(CU , "Expected valid compile unit");
  1139. for (DISubprogram *SP : CU->getSubprograms()) {
  1140. if (SP == DIS) {
  1141. DICU = CU;
  1142. break;
  1143. }
  1144. }
  1145. }
  1146. }
  1147. }
  1148. DXASSERT_NOMSG(DICU);
  1149. // Add global to CU.
  1150. auto *GlobalVariables = DICU->getRawGlobalVariables();
  1151. DXASSERT_NOMSG(GlobalVariables);
  1152. MDTuple *GTuple = cast<MDTuple>(GlobalVariables);
  1153. std::vector<Metadata *> AllGVs(GTuple->operands().begin(),
  1154. GTuple->operands().end());
  1155. if (removeLocDIGV) {
  1156. auto locIt = std::find(AllGVs.begin(), AllGVs.end(), LocDIGV);
  1157. AllGVs.erase(locIt);
  1158. }
  1159. AllGVs.emplace_back(EltDIGV);
  1160. DICU->replaceGlobalVariables(MDTuple::get(GV->getContext(), AllGVs));
  1161. DXVERIFY_NOMSG(DbgInfoFinder.appendGlobalVariable(EltDIGV));
  1162. }
  1163. void HLModule::CreateElementGlobalVariableDebugInfo(
  1164. GlobalVariable *GV, DebugInfoFinder &DbgInfoFinder, GlobalVariable *EltGV,
  1165. unsigned sizeInBits, unsigned alignInBits, unsigned offsetInBits,
  1166. StringRef eltName) {
  1167. DIGlobalVariable *DIGV = FindGlobalVariableDebugInfo(GV, DbgInfoFinder);
  1168. DXASSERT_NOMSG(DIGV);
  1169. DIBuilder Builder(*GV->getParent());
  1170. DITypeIdentifierMap EmptyMap;
  1171. DIType *DITy = DIGV->getType().resolve(EmptyMap);
  1172. DIScope *DITyScope = DITy->getScope().resolve(EmptyMap);
  1173. // Create Elt type.
  1174. DIType *EltDITy =
  1175. Builder.createMemberType(DITyScope, DITy->getName().str() + eltName.str(),
  1176. DITy->getFile(), DITy->getLine(), sizeInBits,
  1177. alignInBits, offsetInBits, /*Flags*/ 0, DITy);
  1178. AddDIGlobalVariable(Builder, DIGV, DIGV->getName().str() + eltName.str(),
  1179. EltDITy, EltGV, DbgInfoFinder, /*removeDIGV*/false);
  1180. }
  1181. void HLModule::UpdateGlobalVariableDebugInfo(
  1182. llvm::GlobalVariable *GV, llvm::DebugInfoFinder &DbgInfoFinder,
  1183. llvm::GlobalVariable *NewGV) {
  1184. DIGlobalVariable *DIGV = FindGlobalVariableDebugInfo(GV, DbgInfoFinder);
  1185. DXASSERT_NOMSG(DIGV);
  1186. DIBuilder Builder(*GV->getParent());
  1187. DITypeIdentifierMap EmptyMap;
  1188. DIType *DITy = DIGV->getType().resolve(EmptyMap);
  1189. AddDIGlobalVariable(Builder, DIGV, DIGV->getName(), DITy, NewGV,
  1190. DbgInfoFinder,/*removeDIGV*/true);
  1191. }
  1192. DebugInfoFinder &HLModule::GetOrCreateDebugInfoFinder() {
  1193. if (m_pDebugInfoFinder == nullptr) {
  1194. m_pDebugInfoFinder = llvm::make_unique<llvm::DebugInfoFinder>();
  1195. m_pDebugInfoFinder->processModule(*m_pModule);
  1196. }
  1197. return *m_pDebugInfoFinder;
  1198. }
  1199. //------------------------------------------------------------------------------
  1200. //
  1201. // Signature methods.
  1202. //
  1203. HLExtraPropertyHelper::HLExtraPropertyHelper(llvm::Module *pModule)
  1204. : DxilExtraPropertyHelper(pModule) {
  1205. }
  1206. void HLExtraPropertyHelper::EmitSignatureElementProperties(const DxilSignatureElement &SE,
  1207. vector<Metadata *> &MDVals) {
  1208. }
  1209. void HLExtraPropertyHelper::LoadSignatureElementProperties(const MDOperand &MDO,
  1210. DxilSignatureElement &SE) {
  1211. if (MDO.get() == nullptr)
  1212. return;
  1213. }
  1214. } // namespace hlsl
  1215. namespace llvm {
  1216. hlsl::HLModule &Module::GetOrCreateHLModule(bool skipInit) {
  1217. std::unique_ptr<hlsl::HLModule> M;
  1218. if (!HasHLModule()) {
  1219. M = llvm::make_unique<hlsl::HLModule>(this);
  1220. if (!skipInit) {
  1221. M->LoadHLMetadata();
  1222. }
  1223. SetHLModule(M.release());
  1224. }
  1225. return GetHLModule();
  1226. }
  1227. void Module::ResetHLModule() {
  1228. if (HasHLModule()) {
  1229. delete TheHLModule;
  1230. TheHLModule = nullptr;
  1231. }
  1232. }
  1233. }