HLModule.cpp 44 KB

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