DxilCondenseResources.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilCondenseResources.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. // Provides a pass to make resource IDs zero-based and dense. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "dxc/HLSL/DxilGenerationPass.h"
  12. #include "dxc/HLSL/DxilOperations.h"
  13. #include "dxc/HLSL/DxilSignatureElement.h"
  14. #include "dxc/HLSL/DxilModule.h"
  15. #include "dxc/Support/Global.h"
  16. #include "dxc/HLSL/DxilTypeSystem.h"
  17. #include "dxc/HLSL/DxilInstructions.h"
  18. #include "dxc/HLSL/DxilSpanAllocator.h"
  19. #include "llvm/IR/Instructions.h"
  20. #include "llvm/IR/IntrinsicInst.h"
  21. #include "llvm/IR/InstIterator.h"
  22. #include "llvm/IR/Module.h"
  23. #include "llvm/IR/PassManager.h"
  24. #include "llvm/ADT/BitVector.h"
  25. #include "llvm/Pass.h"
  26. #include "llvm/Transforms/Utils/Local.h"
  27. #include <memory>
  28. #include <unordered_set>
  29. using namespace llvm;
  30. using namespace hlsl;
  31. struct ResourceID {
  32. DXIL::ResourceClass Class; // Resource class.
  33. unsigned ID; // Resource ID, as specified on entry.
  34. bool operator<(const ResourceID& other) const {
  35. if (Class < other.Class) return true;
  36. if (Class > other.Class) return false;
  37. if (ID < other.ID) return true;
  38. return false;
  39. }
  40. };
  41. struct RemapEntry {
  42. ResourceID ResID; // Resource identity, as specified on entry.
  43. DxilResourceBase *Resource; // In-memory resource representation.
  44. unsigned Index; // Index in resource vector - new ID for the resource.
  45. };
  46. typedef std::map<ResourceID, RemapEntry> RemapEntryCollection;
  47. class DxilCondenseResources : public ModulePass {
  48. private:
  49. RemapEntryCollection m_rewrites;
  50. public:
  51. static char ID; // Pass identification, replacement for typeid
  52. explicit DxilCondenseResources() : ModulePass(ID) {}
  53. const char *getPassName() const override { return "DXIL Condense Resources"; }
  54. bool runOnModule(Module &M) override {
  55. DxilModule &DM = M.GetOrCreateDxilModule();
  56. // Switch tbuffers to SRVs, as they have been treated as cbuffers up to this point.
  57. if (DM.GetCBuffers().size())
  58. PatchTBuffers(DM);
  59. // Remove unused resource.
  60. DM.RemoveUnusedResources();
  61. // Make sure all resource types are dense; build a map of rewrites.
  62. if (BuildRewriteMap(DM)) {
  63. // Rewrite all instructions that refer to resources in the map.
  64. ApplyRewriteMap(DM);
  65. }
  66. bool hasResource = DM.GetCBuffers().size() ||
  67. DM.GetUAVs().size() || DM.GetSRVs().size() || DM.GetSamplers().size();
  68. if (hasResource) {
  69. if (!DM.GetShaderModel()->IsLib()) {
  70. AllocateDxilResources(DM);
  71. PatchCreateHandle(DM);
  72. } else {
  73. PatchCreateHandleForLib(DM);
  74. }
  75. }
  76. return true;
  77. }
  78. // Build m_rewrites, returns 'true' if any rewrites are needed.
  79. bool BuildRewriteMap(DxilModule &DM);
  80. DxilResourceBase &GetFirstRewrite() const {
  81. DXASSERT_NOMSG(!m_rewrites.empty());
  82. return *m_rewrites.begin()->second.Resource;
  83. }
  84. private:
  85. void ApplyRewriteMap(DxilModule &DM);
  86. void AllocateDxilResources(DxilModule &DM);
  87. // Add lowbound to create handle range index.
  88. void PatchCreateHandle(DxilModule &DM);
  89. // Add lowbound to create handle range index for library.
  90. void PatchCreateHandleForLib(DxilModule &DM);
  91. // Switch CBuffer for SRV for TBuffers.
  92. void PatchTBuffers(DxilModule &DM);
  93. };
  94. void DxilCondenseResources::ApplyRewriteMap(DxilModule &DM) {
  95. for (Function &F : DM.GetModule()->functions()) {
  96. if (F.isDeclaration()) {
  97. continue;
  98. }
  99. for (inst_iterator iter = inst_begin(F), E = inst_end(F); iter != E; ++iter) {
  100. llvm::Instruction &I = *iter;
  101. DxilInst_CreateHandle CH(&I);
  102. if (!CH)
  103. continue;
  104. ResourceID RId;
  105. RId.Class = (DXIL::ResourceClass)CH.get_resourceClass_val();
  106. RId.ID = (unsigned)llvm::dyn_cast<llvm::ConstantInt>(CH.get_rangeId())
  107. ->getZExtValue();
  108. RemapEntryCollection::iterator it = m_rewrites.find(RId);
  109. if (it == m_rewrites.end()) {
  110. continue;
  111. }
  112. CallInst *CI = cast<CallInst>(&I);
  113. Value *newRangeID = DM.GetOP()->GetU32Const(it->second.Index);
  114. CI->setArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx,
  115. newRangeID);
  116. }
  117. }
  118. for (auto &entry : m_rewrites) {
  119. entry.second.Resource->SetID(entry.second.Index);
  120. }
  121. }
  122. template <typename TResource>
  123. static void BuildRewrites(const std::vector<std::unique_ptr<TResource>> &Rs,
  124. RemapEntryCollection &C) {
  125. const unsigned s = (unsigned)Rs.size();
  126. for (unsigned i = 0; i < s; ++i) {
  127. const std::unique_ptr<TResource> &R = Rs[i];
  128. if (R->GetID() != i) {
  129. ResourceID RId = {R->GetClass(), R->GetID()};
  130. RemapEntry RE = {RId, R.get(), i};
  131. C[RId] = RE;
  132. }
  133. }
  134. }
  135. bool DxilCondenseResources::BuildRewriteMap(DxilModule &DM) {
  136. BuildRewrites(DM.GetCBuffers(), m_rewrites);
  137. BuildRewrites(DM.GetSRVs(), m_rewrites);
  138. BuildRewrites(DM.GetUAVs(), m_rewrites);
  139. BuildRewrites(DM.GetSamplers(), m_rewrites);
  140. return !m_rewrites.empty();
  141. }
  142. namespace {
  143. template<typename T>
  144. static void AllocateDxilResource(const std::vector<std::unique_ptr<T> > &resourceList, LLVMContext &Ctx) {
  145. SpacesAllocator<unsigned, T> SAlloc;
  146. for (auto &res : resourceList) {
  147. const unsigned space = res->GetSpaceID();
  148. typename SpacesAllocator<unsigned, T>::Allocator &alloc = SAlloc.Get(space);
  149. if (res->IsAllocated()) {
  150. const unsigned reg = res->GetLowerBound();
  151. const T *conflict = nullptr;
  152. if (res->IsUnbounded()) {
  153. const T *unbounded = alloc.GetUnbounded();
  154. if (unbounded) {
  155. Ctx.emitError(
  156. Twine("more than one unbounded resource (") +
  157. unbounded->GetGlobalName() +
  158. (" and ") + res->GetGlobalName() +
  159. (") in space ") + Twine(space));
  160. } else {
  161. conflict = alloc.Insert(res.get(), reg, res->GetUpperBound());
  162. if (!conflict)
  163. alloc.SetUnbounded(res.get());
  164. }
  165. } else {
  166. conflict = alloc.Insert(res.get(), reg, res->GetUpperBound());
  167. }
  168. if (conflict) {
  169. Ctx.emitError(
  170. ((res->IsUnbounded()) ? Twine("unbounded ") : Twine("")) +
  171. Twine("resource ") + res->GetGlobalName() +
  172. Twine(" at register ") + Twine(reg) +
  173. Twine(" overlaps with resource ") + conflict->GetGlobalName() +
  174. Twine(" at register ") + Twine(conflict->GetLowerBound()) +
  175. Twine(", space ") + Twine(space));
  176. }
  177. }
  178. }
  179. // Allocate.
  180. const unsigned space = 0;
  181. typename SpacesAllocator<unsigned, T>::Allocator &alloc0 = SAlloc.Get(space);
  182. for (auto &res : resourceList) {
  183. if (!res->IsAllocated()) {
  184. DXASSERT(res->GetSpaceID() == 0, "otherwise non-zero space has no user register assignment");
  185. unsigned reg = 0;
  186. bool success = false;
  187. if (res->IsUnbounded()) {
  188. const T *unbounded = alloc0.GetUnbounded();
  189. if (unbounded) {
  190. Ctx.emitError(
  191. Twine("more than one unbounded resource (") +
  192. unbounded->GetGlobalName() +
  193. Twine(" and ") + res->GetGlobalName() +
  194. Twine(") in space ") + Twine(space));
  195. } else {
  196. success = alloc0.AllocateUnbounded(res.get(), reg);
  197. if (success)
  198. alloc0.SetUnbounded(res.get());
  199. }
  200. } else {
  201. success = alloc0.Allocate(res.get(), res->GetRangeSize(), reg);
  202. }
  203. if (success) {
  204. res->SetLowerBound(reg);
  205. } else {
  206. Ctx.emitError(
  207. ((res->IsUnbounded()) ? Twine("unbounded ") : Twine("")) +
  208. Twine("resource ") + res->GetGlobalName() +
  209. Twine(" could not be allocated"));
  210. }
  211. }
  212. }
  213. }
  214. void PatchLowerBoundOfCreateHandle(CallInst *handle, DxilModule &DM) {
  215. DxilInst_CreateHandle createHandle(handle);
  216. DXASSERT_NOMSG(createHandle);
  217. DXIL::ResourceClass ResClass =
  218. static_cast<DXIL::ResourceClass>(createHandle.get_resourceClass_val());
  219. // Dynamic rangeId is not supported - skip and let validation report the
  220. // error.
  221. if (!isa<ConstantInt>(createHandle.get_rangeId()))
  222. return;
  223. unsigned rangeId =
  224. cast<ConstantInt>(createHandle.get_rangeId())->getLimitedValue();
  225. DxilResourceBase *res = nullptr;
  226. switch (ResClass) {
  227. case DXIL::ResourceClass::SRV:
  228. res = &DM.GetSRV(rangeId);
  229. break;
  230. case DXIL::ResourceClass::UAV:
  231. res = &DM.GetUAV(rangeId);
  232. break;
  233. case DXIL::ResourceClass::CBuffer:
  234. res = &DM.GetCBuffer(rangeId);
  235. break;
  236. case DXIL::ResourceClass::Sampler:
  237. res = &DM.GetSampler(rangeId);
  238. break;
  239. default:
  240. DXASSERT(0, "invalid res class");
  241. return;
  242. }
  243. IRBuilder<> Builder(handle);
  244. unsigned lowBound = res->GetLowerBound();
  245. if (lowBound) {
  246. Value *Index = createHandle.get_index();
  247. if (ConstantInt *cIndex = dyn_cast<ConstantInt>(Index)) {
  248. unsigned newIdx = lowBound + cIndex->getLimitedValue();
  249. handle->setArgOperand(DXIL::OperandIndex::kCreateHandleResIndexOpIdx,
  250. Builder.getInt32(newIdx));
  251. } else {
  252. Value *newIdx = Builder.CreateAdd(Index, Builder.getInt32(lowBound));
  253. handle->setArgOperand(DXIL::OperandIndex::kCreateHandleResIndexOpIdx,
  254. newIdx);
  255. }
  256. }
  257. }
  258. static void PatchTBufferCreateHandle(CallInst *handle, DxilModule &DM, std::unordered_set<unsigned> &tbufferIDs) {
  259. DxilInst_CreateHandle createHandle(handle);
  260. DXASSERT_NOMSG(createHandle);
  261. DXIL::ResourceClass ResClass = static_cast<DXIL::ResourceClass>(createHandle.get_resourceClass_val());
  262. if (ResClass != DXIL::ResourceClass::CBuffer)
  263. return;
  264. Value *resID = createHandle.get_rangeId();
  265. DXASSERT(isa<ConstantInt>(resID), "cannot handle dynamic resID for cbuffer CreateHandle");
  266. if (!isa<ConstantInt>(resID))
  267. return;
  268. unsigned rangeId = cast<ConstantInt>(resID)->getLimitedValue();
  269. DxilResourceBase *res = &DM.GetCBuffer(rangeId);
  270. // For TBuffer, we need to switch resource type from CBuffer to SRV
  271. if (res->GetKind() == DXIL::ResourceKind::TBuffer) {
  272. // Track cbuffers IDs that are actually tbuffers
  273. tbufferIDs.insert(rangeId);
  274. hlsl::OP *hlslOP = DM.GetOP();
  275. llvm::LLVMContext &Ctx = DM.GetCtx();
  276. // Temporarily add SRV size to rangeID to guarantee unique new SRV ID
  277. Value *newRangeID = hlslOP->GetU32Const(rangeId + DM.GetSRVs().size());
  278. handle->setArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx,
  279. newRangeID);
  280. // switch create handle to SRV
  281. handle->setArgOperand(DXIL::OperandIndex::kCreateHandleResClassOpIdx,
  282. hlslOP->GetU8Const(
  283. static_cast<std::underlying_type<DxilResourceBase::Class>::type>(
  284. DXIL::ResourceClass::SRV)));
  285. Type *doubleTy = Type::getDoubleTy(Ctx);
  286. Type *i64Ty = Type::getInt64Ty(Ctx);
  287. // Replace corresponding cbuffer loads with typed buffer loads
  288. for (auto U = handle->user_begin(); U != handle->user_end(); ) {
  289. CallInst *I = cast<CallInst>(*(U++));
  290. DXASSERT(I && OP::IsDxilOpFuncCallInst(I), "otherwise unexpected user of CreateHandle value");
  291. DXIL::OpCode opcode = OP::GetDxilOpFuncCallInst(I);
  292. if (opcode == DXIL::OpCode::CBufferLoadLegacy) {
  293. DxilInst_CBufferLoadLegacy cbLoad(I);
  294. // Replace with appropriate buffer load instruction
  295. IRBuilder<> Builder(I);
  296. opcode = OP::OpCode::BufferLoad;
  297. Type *Ty = Type::getInt32Ty(Ctx);
  298. Function *BufLoad = hlslOP->GetOpFunc(opcode, Ty);
  299. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  300. Value *undefI = UndefValue::get(Type::getInt32Ty(Ctx));
  301. Value *offset = cbLoad.get_regIndex();
  302. CallInst* load = Builder.CreateCall(BufLoad, {opArg, handle, offset, undefI});
  303. // Find extractelement uses of cbuffer load and replace + generate bitcast as necessary
  304. for (auto LU = I->user_begin(); LU != I->user_end(); ) {
  305. ExtractValueInst *evInst = dyn_cast<ExtractValueInst>(*(LU++));
  306. DXASSERT(evInst && evInst->getNumIndices() == 1, "user of cbuffer load result should be extractvalue");
  307. uint64_t idx = evInst->getIndices()[0];
  308. Type *EltTy = evInst->getType();
  309. IRBuilder<> EEBuilder(evInst);
  310. Value *result = nullptr;
  311. if (EltTy != Ty) {
  312. // extract two values and DXIL::OpCode::MakeDouble or construct i64
  313. if ((EltTy == doubleTy) || (EltTy == i64Ty)) {
  314. DXASSERT(idx < 2, "64-bit component index out of range");
  315. // This assumes big endian order in tbuffer elements (is this correct?)
  316. Value *low = EEBuilder.CreateExtractValue(load, idx * 2);
  317. Value *high = EEBuilder.CreateExtractValue(load, idx * 2 + 1);
  318. if (EltTy == doubleTy) {
  319. opcode = OP::OpCode::MakeDouble;
  320. Function *MakeDouble = hlslOP->GetOpFunc(opcode, doubleTy);
  321. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  322. result = EEBuilder.CreateCall(MakeDouble, {opArg, low, high});
  323. } else {
  324. high = EEBuilder.CreateZExt(high, i64Ty);
  325. low = EEBuilder.CreateZExt(low, i64Ty);
  326. high = EEBuilder.CreateShl(high, hlslOP->GetU64Const(32));
  327. result = EEBuilder.CreateOr(high, low);
  328. }
  329. } else {
  330. result = EEBuilder.CreateExtractValue(load, idx);
  331. result = EEBuilder.CreateBitCast(result, EltTy);
  332. }
  333. } else {
  334. result = EEBuilder.CreateExtractValue(load, idx);
  335. }
  336. evInst->replaceAllUsesWith(result);
  337. evInst->eraseFromParent();
  338. }
  339. } else if (opcode == DXIL::OpCode::CBufferLoad) {
  340. // TODO: Handle this, or prevent this for tbuffer
  341. DXASSERT(false, "otherwise CBufferLoad used for tbuffer rather than CBufferLoadLegacy");
  342. } else {
  343. DXASSERT(false, "otherwise unexpected user of CreateHandle value");
  344. }
  345. I->eraseFromParent();
  346. }
  347. }
  348. }
  349. }
  350. void DxilCondenseResources::AllocateDxilResources(DxilModule &DM) {
  351. AllocateDxilResource(DM.GetCBuffers(), DM.GetCtx());
  352. AllocateDxilResource(DM.GetSamplers(), DM.GetCtx());
  353. AllocateDxilResource(DM.GetUAVs(), DM.GetCtx());
  354. AllocateDxilResource(DM.GetSRVs(), DM.GetCtx());
  355. }
  356. void InitTBuffer(const DxilCBuffer *pSource, DxilResource *pDest) {
  357. pDest->SetKind(pSource->GetKind());
  358. pDest->SetCompType(DXIL::ComponentType::U32);
  359. pDest->SetSampleCount(0);
  360. pDest->SetElementStride(0);
  361. pDest->SetGloballyCoherent(false);
  362. pDest->SetHasCounter(false);
  363. pDest->SetRW(false);
  364. pDest->SetROV(false);
  365. pDest->SetID(pSource->GetID());
  366. pDest->SetSpaceID(pSource->GetSpaceID());
  367. pDest->SetLowerBound(pSource->GetLowerBound());
  368. pDest->SetRangeSize(pSource->GetRangeSize());
  369. pDest->SetGlobalSymbol(pSource->GetGlobalSymbol());
  370. pDest->SetGlobalName(pSource->GetGlobalName());
  371. pDest->SetHandle(pSource->GetHandle());
  372. }
  373. void DxilCondenseResources::PatchTBuffers(DxilModule &DM) {
  374. Function *createHandle = DM.GetOP()->GetOpFunc(DXIL::OpCode::CreateHandle,
  375. Type::getVoidTy(DM.GetCtx()));
  376. std::unordered_set<unsigned> tbufferIDs;
  377. for (User *U : createHandle->users()) {
  378. PatchTBufferCreateHandle(cast<CallInst>(U), DM, tbufferIDs);
  379. }
  380. // move tbuffer resources to SRVs
  381. unsigned offset = DM.GetSRVs().size();
  382. for (auto it = DM.GetCBuffers().begin(); it != DM.GetCBuffers().end(); it++) {
  383. DxilCBuffer *CB = it->get();
  384. unsigned resID = CB->GetID();
  385. if (tbufferIDs.find(resID) != tbufferIDs.end()) {
  386. auto srv = make_unique<DxilResource>();
  387. InitTBuffer(CB, srv.get());
  388. srv->SetID(resID + offset);
  389. DM.AddSRV(std::move(srv));
  390. // cbuffer should get cleaned up since it's now unused.
  391. }
  392. }
  393. }
  394. void DxilCondenseResources::PatchCreateHandle(DxilModule &DM) {
  395. Function *createHandle = DM.GetOP()->GetOpFunc(DXIL::OpCode::CreateHandle,
  396. Type::getVoidTy(DM.GetCtx()));
  397. for (User *U : createHandle->users()) {
  398. PatchLowerBoundOfCreateHandle(cast<CallInst>(U), DM);
  399. }
  400. }
  401. static Value *PatchRangeIDForLib(DxilModule &DM, IRBuilder<> &Builder,
  402. Value *rangeIdVal,
  403. std::unordered_map<PHINode *, Value *> &phiMap,
  404. DXIL::ResourceClass ResClass) {
  405. Value *linkRangeID = nullptr;
  406. if (isa<ConstantInt>(rangeIdVal)) {
  407. unsigned rangeId = cast<ConstantInt>(rangeIdVal)->getLimitedValue();
  408. const DxilModule::ResourceLinkInfo &linkInfo =
  409. DM.GetResourceLinkInfo(ResClass, rangeId);
  410. linkRangeID = Builder.CreateLoad(linkInfo.ResRangeID);
  411. } else {
  412. if (PHINode *phi = dyn_cast<PHINode>(rangeIdVal)) {
  413. auto it = phiMap.find(phi);
  414. if (it == phiMap.end()) {
  415. unsigned numOperands = phi->getNumOperands();
  416. PHINode *phiRangeID = Builder.CreatePHI(phi->getType(), numOperands);
  417. phiMap[phi] = phiRangeID;
  418. std::vector<Value *> rangeIDs(numOperands);
  419. for (unsigned i = 0; i < numOperands; i++) {
  420. Value *V = phi->getOperand(i);
  421. BasicBlock *BB = phi->getIncomingBlock(i);
  422. IRBuilder<> Builder(BB->getTerminator());
  423. rangeIDs[i] = PatchRangeIDForLib(DM, Builder, V, phiMap, ResClass);
  424. }
  425. for (unsigned i = 0; i < numOperands; i++) {
  426. Value *V = rangeIDs[i];
  427. BasicBlock *BB = phi->getIncomingBlock(i);
  428. phiRangeID->addIncoming(V, BB);
  429. }
  430. linkRangeID = phiRangeID;
  431. } else {
  432. linkRangeID = it->second;
  433. }
  434. } else if (SelectInst *si = dyn_cast<SelectInst>(rangeIdVal)) {
  435. IRBuilder<> Builder(si);
  436. Value *trueVal =
  437. PatchRangeIDForLib(DM, Builder, si->getTrueValue(), phiMap, ResClass);
  438. Value *falseVal = PatchRangeIDForLib(DM, Builder, si->getFalseValue(),
  439. phiMap, ResClass);
  440. linkRangeID = Builder.CreateSelect(si->getCondition(), trueVal, falseVal);
  441. } else if (CastInst *cast = dyn_cast<CastInst>(rangeIdVal)) {
  442. if (cast->getOpcode() == CastInst::CastOps::ZExt &&
  443. cast->getOperand(0)->getType() == Type::getInt1Ty(DM.GetCtx())) {
  444. // select cond, 1, 0.
  445. IRBuilder<> Builder(cast);
  446. Value *trueVal = PatchRangeIDForLib(
  447. DM, Builder, ConstantInt::get(cast->getType(), 1), phiMap,
  448. ResClass);
  449. Value *falseVal = PatchRangeIDForLib(
  450. DM, Builder, ConstantInt::get(cast->getType(), 0), phiMap,
  451. ResClass);
  452. linkRangeID =
  453. Builder.CreateSelect(cast->getOperand(0), trueVal, falseVal);
  454. }
  455. }
  456. }
  457. return linkRangeID;
  458. }
  459. void DxilCondenseResources::PatchCreateHandleForLib(DxilModule &DM) {
  460. Function *createHandle = DM.GetOP()->GetOpFunc(DXIL::OpCode::CreateHandle,
  461. Type::getVoidTy(DM.GetCtx()));
  462. DM.CreateResourceLinkInfo();
  463. for (User *U : createHandle->users()) {
  464. CallInst *handle = cast<CallInst>(U);
  465. DxilInst_CreateHandle createHandle(handle);
  466. DXASSERT_NOMSG(createHandle);
  467. DXIL::ResourceClass ResClass =
  468. static_cast<DXIL::ResourceClass>(createHandle.get_resourceClass_val());
  469. std::unordered_map<PHINode *, Value*> phiMap;
  470. Value *rangeID = createHandle.get_rangeId();
  471. IRBuilder<> Builder(handle);
  472. Value *linkRangeID = PatchRangeIDForLib(
  473. DM, Builder, rangeID, phiMap, ResClass);
  474. // Dynamic rangeId is not supported - skip and let validation report the
  475. // error.
  476. if (!linkRangeID)
  477. continue;
  478. // Update rangeID to linkinfo rangeID.
  479. handle->setArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx,
  480. linkRangeID);
  481. if (rangeID->user_empty() && isa<Instruction>(rangeID)) {
  482. cast<Instruction>(rangeID)->eraseFromParent();
  483. }
  484. }
  485. }
  486. char DxilCondenseResources::ID = 0;
  487. bool llvm::AreDxilResourcesDense(llvm::Module *M, hlsl::DxilResourceBase **ppNonDense) {
  488. DxilModule &DM = M->GetOrCreateDxilModule();
  489. DxilCondenseResources Pass;
  490. if (Pass.BuildRewriteMap(DM)) {
  491. *ppNonDense = &Pass.GetFirstRewrite();
  492. return false;
  493. }
  494. else {
  495. *ppNonDense = nullptr;
  496. return true;
  497. }
  498. }
  499. ModulePass *llvm::createDxilCondenseResourcesPass() {
  500. return new DxilCondenseResources();
  501. }
  502. INITIALIZE_PASS(DxilCondenseResources, "hlsl-dxil-condense", "DXIL Condense Resources", false, false)