DxilPreparePasses.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilPreparePasses.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. // Passes to prepare DxilModule. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "dxc/HLSL/DxilGenerationPass.h"
  12. #include "dxc/DXIL/DxilOperations.h"
  13. #include "dxc/HLSL/HLOperations.h"
  14. #include "dxc/DXIL/DxilModule.h"
  15. #include "dxc/Support/Global.h"
  16. #include "dxc/DXIL/DxilTypeSystem.h"
  17. #include "dxc/DXIL/DxilUtil.h"
  18. #include "dxc/DXIL/DxilEntryProps.h"
  19. #include "dxc/DXIL/DxilFunctionProps.h"
  20. #include "dxc/DXIL/DxilInstructions.h"
  21. #include "dxc/DXIL/DxilConstants.h"
  22. #include "dxc/HlslIntrinsicOp.h"
  23. #include "llvm/IR/GetElementPtrTypeIterator.h"
  24. #include "llvm/IR/IRBuilder.h"
  25. #include "llvm/IR/Instructions.h"
  26. #include "llvm/IR/InstIterator.h"
  27. #include "llvm/IR/IntrinsicInst.h"
  28. #include "llvm/Analysis/PostDominators.h"
  29. #include "llvm/IR/Module.h"
  30. #include "llvm/IR/DebugInfo.h"
  31. #include "llvm/IR/DIBuilder.h"
  32. #include "llvm/IR/PassManager.h"
  33. #include "llvm/ADT/BitVector.h"
  34. #include "llvm/ADT/SetVector.h"
  35. #include "llvm/Pass.h"
  36. #include "llvm/Transforms/Utils/Local.h"
  37. #include "llvm/Analysis/AssumptionCache.h"
  38. #include "llvm/Analysis/DxilValueCache.h"
  39. #include "llvm/Analysis/LoopInfo.h"
  40. #include <memory>
  41. #include <unordered_set>
  42. using namespace llvm;
  43. using namespace hlsl;
  44. namespace {
  45. class InvalidateUndefResources : public ModulePass {
  46. public:
  47. static char ID;
  48. explicit InvalidateUndefResources() : ModulePass(ID) {
  49. initializeScalarizerPass(*PassRegistry::getPassRegistry());
  50. }
  51. const char *getPassName() const override { return "Invalidate undef resources"; }
  52. bool runOnModule(Module &M) override;
  53. };
  54. }
  55. char InvalidateUndefResources::ID = 0;
  56. ModulePass *llvm::createInvalidateUndefResourcesPass() { return new InvalidateUndefResources(); }
  57. INITIALIZE_PASS(InvalidateUndefResources, "invalidate-undef-resource", "Invalidate undef resources", false, false)
  58. bool InvalidateUndefResources::runOnModule(Module &M) {
  59. // Undef resources typically indicate uninitialized locals being used
  60. // in some code path, which we should catch and report. However, some
  61. // code patterns in large shaders cause dead undef resources to momentarily,
  62. // which is not an error. We must wait until cleanup passes
  63. // have run to know whether we must produce an error.
  64. // However, we can't leave the undef values in because they could eliminated,
  65. // such as by reading from resources seen in a code path that was not taken.
  66. // We avoid the problem by replacing undef values by another invalid
  67. // value that we can identify later.
  68. for (auto &F : M.functions()) {
  69. if (GetHLOpcodeGroupByName(&F) == HLOpcodeGroup::HLCreateHandle) {
  70. Type *ResTy = F.getFunctionType()->getParamType(
  71. HLOperandIndex::kCreateHandleResourceOpIdx);
  72. UndefValue *UndefRes = UndefValue::get(ResTy);
  73. if (!UndefRes->use_empty()) {
  74. Constant *InvalidRes = ConstantAggregateZero::get(ResTy);
  75. UndefRes->replaceAllUsesWith(InvalidRes);
  76. }
  77. }
  78. }
  79. return false;
  80. }
  81. ///////////////////////////////////////////////////////////////////////////////
  82. namespace {
  83. class SimplifyInst : public FunctionPass {
  84. public:
  85. static char ID;
  86. SimplifyInst() : FunctionPass(ID) {
  87. initializeScalarizerPass(*PassRegistry::getPassRegistry());
  88. }
  89. bool runOnFunction(Function &F) override;
  90. private:
  91. };
  92. }
  93. char SimplifyInst::ID = 0;
  94. FunctionPass *llvm::createSimplifyInstPass() { return new SimplifyInst(); }
  95. INITIALIZE_PASS(SimplifyInst, "simplify-inst", "Simplify Instructions", false, false)
  96. bool SimplifyInst::runOnFunction(Function &F) {
  97. for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
  98. BasicBlock *BB = BBI;
  99. llvm::SimplifyInstructionsInBlock(BB, nullptr);
  100. }
  101. return true;
  102. }
  103. ///////////////////////////////////////////////////////////////////////////////
  104. namespace {
  105. class DxilDeadFunctionElimination : public ModulePass {
  106. public:
  107. static char ID; // Pass identification, replacement for typeid
  108. explicit DxilDeadFunctionElimination () : ModulePass(ID) {}
  109. const char *getPassName() const override { return "Remove all unused function except entry from DxilModule"; }
  110. bool runOnModule(Module &M) override {
  111. if (M.HasDxilModule()) {
  112. DxilModule &DM = M.GetDxilModule();
  113. bool IsLib = DM.GetShaderModel()->IsLib();
  114. // Remove unused functions except entry and patch constant func.
  115. // For library profile, only remove unused external functions.
  116. Function *EntryFunc = DM.GetEntryFunction();
  117. Function *PatchConstantFunc = DM.GetPatchConstantFunction();
  118. return dxilutil::RemoveUnusedFunctions(M, EntryFunc, PatchConstantFunc,
  119. IsLib);
  120. }
  121. return false;
  122. }
  123. };
  124. }
  125. char DxilDeadFunctionElimination::ID = 0;
  126. ModulePass *llvm::createDxilDeadFunctionEliminationPass() {
  127. return new DxilDeadFunctionElimination();
  128. }
  129. INITIALIZE_PASS(DxilDeadFunctionElimination, "dxil-dfe", "Remove all unused function except entry from DxilModule", false, false)
  130. ///////////////////////////////////////////////////////////////////////////////
  131. bool CleanupSharedMemoryAddrSpaceCast(Module &M);
  132. namespace {
  133. static void TransferEntryFunctionAttributes(Function *F, Function *NewFunc) {
  134. // Keep necessary function attributes
  135. AttributeSet attributeSet = F->getAttributes();
  136. StringRef attrKind, attrValue;
  137. if (attributeSet.hasAttribute(AttributeSet::FunctionIndex, DXIL::kFP32DenormKindString)) {
  138. Attribute attribute = attributeSet.getAttribute(AttributeSet::FunctionIndex, DXIL::kFP32DenormKindString);
  139. DXASSERT(attribute.isStringAttribute(), "otherwise we have wrong fp-denorm-mode attribute.");
  140. attrKind = attribute.getKindAsString();
  141. attrValue = attribute.getValueAsString();
  142. }
  143. if (F == NewFunc) {
  144. NewFunc->removeAttributes(AttributeSet::FunctionIndex, attributeSet);
  145. }
  146. if (!attrKind.empty() && !attrValue.empty())
  147. NewFunc->addFnAttr(attrKind, attrValue);
  148. }
  149. // If this returns non-null, the old function F has been stripped and can be deleted.
  150. static Function *StripFunctionParameter(Function *F, DxilModule &DM,
  151. DenseMap<const Function *, DISubprogram *> &FunctionDIs) {
  152. if (F->arg_empty() && F->getReturnType()->isVoidTy()) {
  153. // This will strip non-entry function attributes
  154. TransferEntryFunctionAttributes(F, F);
  155. return nullptr;
  156. }
  157. Module &M = *DM.GetModule();
  158. Type *VoidTy = Type::getVoidTy(M.getContext());
  159. FunctionType *FT = FunctionType::get(VoidTy, false);
  160. for (auto &arg : F->args()) {
  161. if (!arg.user_empty())
  162. return nullptr;
  163. DbgDeclareInst *DDI = llvm::FindAllocaDbgDeclare(&arg);
  164. if (DDI) {
  165. DDI->eraseFromParent();
  166. }
  167. }
  168. Function *NewFunc = Function::Create(FT, F->getLinkage());
  169. M.getFunctionList().insert(F, NewFunc);
  170. // Splice the body of the old function right into the new function.
  171. NewFunc->getBasicBlockList().splice(NewFunc->begin(), F->getBasicBlockList());
  172. TransferEntryFunctionAttributes(F, NewFunc);
  173. // Patch the pointer to LLVM function in debug info descriptor.
  174. auto DI = FunctionDIs.find(F);
  175. if (DI != FunctionDIs.end()) {
  176. DISubprogram *SP = DI->second;
  177. SP->replaceFunction(NewFunc);
  178. // Ensure the map is updated so it can be reused on subsequent argument
  179. // promotions of the same function.
  180. FunctionDIs.erase(DI);
  181. FunctionDIs[NewFunc] = SP;
  182. }
  183. NewFunc->takeName(F);
  184. if (DM.HasDxilFunctionProps(F)) {
  185. DM.ReplaceDxilEntryProps(F, NewFunc);
  186. }
  187. DM.GetTypeSystem().EraseFunctionAnnotation(F);
  188. DM.GetTypeSystem().AddFunctionAnnotation(NewFunc);
  189. return NewFunc;
  190. }
  191. void CheckInBoundForTGSM(GlobalVariable &GV, const DataLayout &DL) {
  192. for (User *U : GV.users()) {
  193. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  194. bool allImmIndex = true;
  195. for (auto Idx = GEP->idx_begin(), E = GEP->idx_end(); Idx != E; Idx++) {
  196. if (!isa<ConstantInt>(Idx)) {
  197. allImmIndex = false;
  198. break;
  199. }
  200. }
  201. if (!allImmIndex)
  202. GEP->setIsInBounds(false);
  203. else {
  204. Value *Ptr = GEP->getPointerOperand();
  205. unsigned size =
  206. DL.getTypeAllocSize(Ptr->getType()->getPointerElementType());
  207. unsigned valSize =
  208. DL.getTypeAllocSize(GEP->getType()->getPointerElementType());
  209. SmallVector<Value *, 8> Indices(GEP->idx_begin(), GEP->idx_end());
  210. unsigned offset =
  211. DL.getIndexedOffset(GEP->getPointerOperandType(), Indices);
  212. if ((offset + valSize) > size)
  213. GEP->setIsInBounds(false);
  214. }
  215. }
  216. }
  217. }
  218. static bool GetUnsignedVal(Value *V, uint32_t *pValue) {
  219. ConstantInt *CI = dyn_cast<ConstantInt>(V);
  220. if (!CI) return false;
  221. uint64_t u = CI->getZExtValue();
  222. if (u > UINT32_MAX) return false;
  223. *pValue = (uint32_t)u;
  224. return true;
  225. }
  226. static void MarkUsedSignatureElements(Function *F, DxilModule &DM) {
  227. DXASSERT_NOMSG(F != nullptr);
  228. // For every loadInput/storeOutput, update the corresponding ReadWriteMask.
  229. // F is a pointer to a Function instance
  230. for (llvm::inst_iterator I = llvm::inst_begin(F), E = llvm::inst_end(F); I != E; ++I) {
  231. DxilInst_LoadInput LI(&*I);
  232. DxilInst_StoreOutput SO(&*I);
  233. DxilInst_LoadPatchConstant LPC(&*I);
  234. DxilInst_StorePatchConstant SPC(&*I);
  235. DxilInst_StoreVertexOutput SVO(&*I);
  236. DxilInst_StorePrimitiveOutput SPO(&*I);
  237. DxilSignature *pSig;
  238. uint32_t col, row, sigId;
  239. bool bDynIdx = false;
  240. if (LI) {
  241. if (!GetUnsignedVal(LI.get_inputSigId(), &sigId)) continue;
  242. if (!GetUnsignedVal(LI.get_colIndex(), &col)) continue;
  243. if (!GetUnsignedVal(LI.get_rowIndex(), &row)) bDynIdx = true;
  244. pSig = &DM.GetInputSignature();
  245. }
  246. else if (SO) {
  247. if (!GetUnsignedVal(SO.get_outputSigId(), &sigId)) continue;
  248. if (!GetUnsignedVal(SO.get_colIndex(), &col)) continue;
  249. if (!GetUnsignedVal(SO.get_rowIndex(), &row)) bDynIdx = true;
  250. pSig = &DM.GetOutputSignature();
  251. }
  252. else if (SPC) {
  253. if (!GetUnsignedVal(SPC.get_outputSigID(), &sigId)) continue;
  254. if (!GetUnsignedVal(SPC.get_col(), &col)) continue;
  255. if (!GetUnsignedVal(SPC.get_row(), &row)) bDynIdx = true;
  256. pSig = &DM.GetPatchConstOrPrimSignature();
  257. }
  258. else if (LPC) {
  259. if (!GetUnsignedVal(LPC.get_inputSigId(), &sigId)) continue;
  260. if (!GetUnsignedVal(LPC.get_col(), &col)) continue;
  261. if (!GetUnsignedVal(LPC.get_row(), &row)) bDynIdx = true;
  262. pSig = &DM.GetPatchConstOrPrimSignature();
  263. }
  264. else if (SVO) {
  265. if (!GetUnsignedVal(SVO.get_outputSigId(), &sigId)) continue;
  266. if (!GetUnsignedVal(SVO.get_colIndex(), &col)) continue;
  267. if (!GetUnsignedVal(SVO.get_rowIndex(), &row)) bDynIdx = true;
  268. pSig = &DM.GetOutputSignature();
  269. }
  270. else if (SPO) {
  271. if (!GetUnsignedVal(SPO.get_outputSigId(), &sigId)) continue;
  272. if (!GetUnsignedVal(SPO.get_colIndex(), &col)) continue;
  273. if (!GetUnsignedVal(SPO.get_rowIndex(), &row)) bDynIdx = true;
  274. pSig = &DM.GetPatchConstOrPrimSignature();
  275. }
  276. else {
  277. continue;
  278. }
  279. // Consider being more fine-grained about masks.
  280. // We report sometimes-read on input as always-read.
  281. auto &El = pSig->GetElement(sigId);
  282. unsigned UsageMask = El.GetUsageMask();
  283. unsigned colBit = 1 << col;
  284. if (!(colBit & UsageMask)) {
  285. El.SetUsageMask(UsageMask | colBit);
  286. }
  287. if (bDynIdx && (El.GetDynIdxCompMask() & colBit) == 0) {
  288. El.SetDynIdxCompMask(El.GetDynIdxCompMask() | colBit);
  289. }
  290. }
  291. }
  292. class DxilFinalizeModule : public ModulePass {
  293. public:
  294. static char ID; // Pass identification, replacement for typeid
  295. explicit DxilFinalizeModule() : ModulePass(ID) {}
  296. const char *getPassName() const override { return "HLSL DXIL Finalize Module"; }
  297. void patchValidation_1_1(Module &M) {
  298. for (iplist<Function>::iterator F : M.getFunctionList()) {
  299. for (Function::iterator BBI = F->begin(), BBE = F->end(); BBI != BBE;
  300. ++BBI) {
  301. BasicBlock *BB = BBI;
  302. for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
  303. ++II) {
  304. Instruction *I = II;
  305. if (I->hasMetadataOtherThanDebugLoc()) {
  306. SmallVector<std::pair<unsigned, MDNode*>, 2> MDs;
  307. I->getAllMetadataOtherThanDebugLoc(MDs);
  308. for (auto &MD : MDs) {
  309. unsigned kind = MD.first;
  310. // Remove Metadata which validation_1_0 not allowed.
  311. bool bNeedPatch = kind == LLVMContext::MD_tbaa ||
  312. kind == LLVMContext::MD_prof ||
  313. (kind > LLVMContext::MD_fpmath &&
  314. kind <= LLVMContext::MD_dereferenceable_or_null);
  315. if (bNeedPatch)
  316. I->setMetadata(kind, nullptr);
  317. }
  318. }
  319. }
  320. }
  321. }
  322. }
  323. void RemoveAnnotateHandle(hlsl::OP *hlslOP) {
  324. for (auto it : hlslOP->GetOpFuncList(DXIL::OpCode::AnnotateHandle)) {
  325. Function *F = it.second;
  326. if (!F)
  327. continue;
  328. for (auto uit = F->user_begin(); uit != F->user_end();) {
  329. CallInst *CI = cast<CallInst>(*(uit++));
  330. DxilInst_AnnotateHandle annoteHdl(CI);
  331. Value *hdl = annoteHdl.get_res();
  332. CI->replaceAllUsesWith(hdl);
  333. CI->eraseFromParent();
  334. }
  335. }
  336. }
  337. // Replace all fromOpcode call instructions with toOpcode equivalents
  338. void ReplaceIntrinsics(Module &M, hlsl::OP *hlslOp, DXIL::OpCode fromOpcode, DXIL::OpCode toOpcode) {
  339. for (auto it : hlslOp->GetOpFuncList(fromOpcode)) {
  340. Function *F = it.second;
  341. if (!F)
  342. continue;
  343. Type *Ty = OP::GetOverloadType(fromOpcode, F);
  344. for (auto uit = F->user_begin(), E = F->user_end(); uit != E;) {
  345. CallInst *CI = cast<CallInst>(*(uit++));
  346. IRBuilder<> Builder(CI);
  347. std::vector<Value*> args;
  348. args.emplace_back(hlslOp->GetU32Const((unsigned)toOpcode));
  349. for (unsigned i = 1; i < CI->getNumArgOperands(); i++)
  350. args.emplace_back(CI->getOperand(i));
  351. Function *newF = hlslOp->GetOpFunc(toOpcode, Ty);
  352. CallInst *NewCI = Builder.CreateCall(newF, args);
  353. CI->replaceAllUsesWith(NewCI);
  354. CI->eraseFromParent();
  355. }
  356. }
  357. }
  358. ///////////////////////////////////////////////////
  359. // IsHelperLane() lowering for SM < 6.6
  360. // Identify pattern icmp_eq(0, dx.coverage())
  361. bool IsCmpZOfCoverage(Value *V, hlsl::OP *hlslOP) {
  362. if (ICmpInst *IC = dyn_cast<ICmpInst>(V)) {
  363. if (IC->getPredicate() == ICmpInst::ICMP_EQ) {
  364. Value *V0 = IC->getOperand(0);
  365. Value *V1 = IC->getOperand(1);
  366. if (!isa<ConstantInt>(V0))
  367. std::swap(V0, V1);
  368. if (ConstantInt *C = dyn_cast<ConstantInt>(V0)) {
  369. if (CallInst *CI = dyn_cast<CallInst>(V1)) {
  370. // compare dx.op.coverage with zero
  371. if (C->isZero() &&
  372. hlslOP->IsDxilOpFuncCallInst(CI, DXIL::OpCode::Coverage)) {
  373. return true;
  374. }
  375. }
  376. }
  377. }
  378. }
  379. return false;
  380. }
  381. // Identify init as use in entry block that either:
  382. // - non-PS: store i32 0
  383. // - PS: store zext(icmp_eq(0, dx.coverage()))
  384. bool IsInitOfIsHelperGV(User *U, hlsl::OP *hlslOP) {
  385. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  386. BasicBlock *BB = SI->getParent();
  387. if (BB == &BB->getParent()->getEntryBlock()) {
  388. Value *V = SI->getValueOperand();
  389. if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
  390. if (C->isZero()) {
  391. return true;
  392. }
  393. } else if (ZExtInst *ZEI = dyn_cast<ZExtInst>(V)) {
  394. if (IsCmpZOfCoverage(ZEI->getOperand(0), hlslOP)) {
  395. return true;
  396. }
  397. }
  398. }
  399. }
  400. return false;
  401. }
  402. void RemoveFnIfIsHelperInit(User *U, hlsl::OP *hlslOP,
  403. SmallSetVector<Function *, 4> &psEntries) {
  404. if (Instruction *I = dyn_cast<Instruction>(U)) {
  405. // Early out: only check if in function still in set
  406. Function *F = I->getParent()->getParent();
  407. if (!psEntries.count(F))
  408. return;
  409. if (IsInitOfIsHelperGV(I, hlslOP)) {
  410. psEntries.remove(F);
  411. }
  412. }
  413. }
  414. // Init IsHelper GV to zext(!dx.op.coverage()) in PS entry points
  415. void InitIsHelperGV(Module &M) {
  416. GlobalVariable *GV =
  417. M.getGlobalVariable(DXIL::kDxIsHelperGlobalName, /*AllowLocal*/ true);
  418. if (!GV)
  419. return;
  420. DxilModule &DM = M.GetDxilModule();
  421. hlsl::OP *hlslOP = DM.GetOP();
  422. const ShaderModel *pSM = DM.GetShaderModel();
  423. // If PS, and GV is ExternalLinkage, change to InternalLinkage
  424. // This can happen after link to final PS.
  425. if (pSM->IsPS() && GV->getLinkage() == GlobalValue::ExternalLinkage) {
  426. GV->setLinkage(GlobalValue::InternalLinkage);
  427. }
  428. // add PS entry points to set
  429. SmallSetVector<Function*, 4> psEntries;
  430. if (pSM->IsPS()) {
  431. psEntries.insert(DM.GetEntryFunction());
  432. } else if (pSM->IsLib()) {
  433. for (auto &F : M.functions()) {
  434. if (DM.HasDxilEntryProps(&F)) {
  435. if (DM.GetDxilEntryProps(&F).props.IsPS()) {
  436. psEntries.insert(&F);
  437. }
  438. }
  439. }
  440. }
  441. // iterate users of GV to skip entries that already init GV
  442. for (auto &U : GV->uses()) {
  443. RemoveFnIfIsHelperInit(U.getUser(), DM.GetOP(), psEntries);
  444. }
  445. // store zext(!dx.op.coverage())
  446. Type *I32Ty = Type::getInt32Ty(hlslOP->GetCtx());
  447. Constant *C0 = hlslOP->GetI32Const(0);
  448. Constant *OpArg = hlslOP->GetI32Const((int)DXIL::OpCode::Coverage);
  449. Function *CoverageF = nullptr;
  450. for (auto *F : psEntries) {
  451. if (!CoverageF)
  452. CoverageF = hlslOP->GetOpFunc(DXIL::OpCode::Coverage, I32Ty);
  453. IRBuilder<> Builder(F->getEntryBlock().getFirstInsertionPt());
  454. Value *V = Builder.CreateCall(CoverageF, {OpArg});
  455. V = Builder.CreateICmpEQ(C0, V);
  456. V = Builder.CreateZExt(V, I32Ty);
  457. Builder.CreateStore(V, GV);
  458. }
  459. }
  460. GlobalVariable *GetIsHelperGV(Module &M) {
  461. return M.getGlobalVariable(DXIL::kDxIsHelperGlobalName, /*AllowLocal*/ true);
  462. }
  463. GlobalVariable *GetOrCreateIsHelperGV(Module &M, hlsl::OP *hlslOP) {
  464. GlobalVariable *GV = GetIsHelperGV(M);
  465. if (GV)
  466. return GV;
  467. DxilModule &DM = M.GetDxilModule();
  468. const ShaderModel *pSM = DM.GetShaderModel();
  469. GV = new GlobalVariable(M, IntegerType::get(M.getContext(), 32),
  470. /*constant*/ false,
  471. pSM->IsLib() ? GlobalValue::ExternalLinkage
  472. : GlobalValue::InternalLinkage,
  473. /*Initializer*/ hlslOP->GetI32Const(0),
  474. DXIL::kDxIsHelperGlobalName);
  475. return GV;
  476. }
  477. // Replace IsHelperLane() with false (for non-lib, non-PS SM)
  478. void ReplaceIsHelperWithConstFalse(hlsl::OP *hlslOP) {
  479. Constant *False = hlslOP->GetI1Const(0);
  480. bool bDone = false;
  481. while (!bDone) {
  482. bDone = true;
  483. for (auto it : hlslOP->GetOpFuncList(DXIL::OpCode::IsHelperLane)) {
  484. Function *F = it.second;
  485. if (!F)
  486. continue;
  487. for (auto uit = F->user_begin(); uit != F->user_end();) {
  488. CallInst *CI = dyn_cast<CallInst>(*(uit++));
  489. CI->replaceAllUsesWith(False);
  490. CI->eraseFromParent();
  491. }
  492. hlslOP->RemoveFunction(F);
  493. F->eraseFromParent();
  494. bDone = false;
  495. break;
  496. }
  497. }
  498. }
  499. void ConvertIsHelperToLoadGV(hlsl::OP *hlslOP) {
  500. GlobalVariable *GV = nullptr;
  501. Type *I1Ty = Type::getInt1Ty(hlslOP->GetCtx());
  502. bool bDone = false;
  503. while (!bDone) {
  504. bDone = true;
  505. for (auto it : hlslOP->GetOpFuncList(DXIL::OpCode::IsHelperLane)) {
  506. Function *F = it.second;
  507. if (!F)
  508. continue;
  509. for (auto uit = F->user_begin(); uit != F->user_end();) {
  510. CallInst *CI = cast<CallInst>(*(uit++));
  511. if (!GV)
  512. GV = GetOrCreateIsHelperGV(*F->getParent(), hlslOP);
  513. IRBuilder<> Builder(CI);
  514. Value *V = Builder.CreateLoad(GV);
  515. V = Builder.CreateTrunc(V, I1Ty);
  516. CI->replaceAllUsesWith(V);
  517. CI->eraseFromParent();
  518. }
  519. hlslOP->RemoveFunction(F);
  520. F->eraseFromParent();
  521. bDone = false;
  522. break;
  523. }
  524. }
  525. }
  526. void ConvertDiscardToStoreGV(hlsl::OP *hlslOP) {
  527. GlobalVariable *GV = nullptr;
  528. Type *I32Ty = Type::getInt32Ty(hlslOP->GetCtx());
  529. for (auto it : hlslOP->GetOpFuncList(DXIL::OpCode::Discard)) {
  530. Function *F = it.second;
  531. if (!F)
  532. continue;
  533. for (auto uit = F->user_begin(); uit != F->user_end();) {
  534. CallInst *CI = cast<CallInst>(*(uit++));
  535. if (!GV)
  536. GV = GetIsHelperGV(*F->getParent());
  537. // If we don't already have a global for this,
  538. // we didn't have any IsHelper() calls, so no need to add one now.
  539. if (!GV)
  540. return;
  541. IRBuilder<> Builder(CI);
  542. Value *Cond =
  543. Builder.CreateZExt(DxilInst_Discard(CI).get_condition(), I32Ty);
  544. Builder.CreateStore(Cond, GV);
  545. }
  546. }
  547. }
  548. ///////////////////////////////////////////////////
  549. void patchDxil_1_6(Module &M, hlsl::OP *hlslOP, unsigned ValMajor, unsigned ValMinor) {
  550. RemoveAnnotateHandle(hlslOP);
  551. // Convert IsHelperLane() on down-level targets
  552. const ShaderModel *pSM = M.GetDxilModule().GetShaderModel();
  553. if (pSM->IsLib() || pSM->IsPS()) {
  554. ConvertIsHelperToLoadGV(hlslOP);
  555. ConvertDiscardToStoreGV(hlslOP);
  556. InitIsHelperGV(M);
  557. // Set linkage of dx.ishelper to internal for validator version < 1.6
  558. // This means IsHelperLane() fallback code will not return correct result
  559. // in an exported function linked to a PS in another library in this case.
  560. // But it won't pass validation otherwise.
  561. if (pSM->IsLib() && DXIL::CompareVersions(ValMajor, ValMinor, 1, 6) < 1) {
  562. if (GlobalVariable *GV = GetIsHelperGV(M)) {
  563. GV->setLinkage(GlobalValue::InternalLinkage);
  564. }
  565. }
  566. } else {
  567. ReplaceIsHelperWithConstFalse(hlslOP);
  568. }
  569. }
  570. // Replace llvm.lifetime.start/.end intrinsics with undef or zeroinitializer
  571. // stores (for earlier validator versions) unless the pointer is a global
  572. // that has an initializer.
  573. // This works around losing scoping information in earlier shader models
  574. // that do not support the intrinsics natively.
  575. void patchLifetimeIntrinsics(Module &M, unsigned ValMajor, unsigned ValMinor, bool forceZeroStoreLifetimes) {
  576. // Get the declarations. This may introduce them if there were none before.
  577. Value *StartDecl = Intrinsic::getDeclaration(&M, Intrinsic::lifetime_start);
  578. Value *EndDecl = Intrinsic::getDeclaration(&M, Intrinsic::lifetime_end);
  579. // Collect all calls to both intrinsics.
  580. std::vector<CallInst*> intrinsicCalls;
  581. for (Use &U : StartDecl->uses()) {
  582. // All users must be call instructions.
  583. CallInst *CI = dyn_cast<CallInst>(U.getUser());
  584. DXASSERT(CI,
  585. "Expected user of lifetime.start intrinsic to be a CallInst");
  586. intrinsicCalls.push_back(CI);
  587. }
  588. for (Use &U : EndDecl->uses()) {
  589. // All users must be call instructions.
  590. CallInst *CI = dyn_cast<CallInst>(U.getUser());
  591. DXASSERT(CI, "Expected user of lifetime.end intrinsic to be a CallInst");
  592. intrinsicCalls.push_back(CI);
  593. }
  594. // Replace each intrinsic with an undef store.
  595. for (CallInst *CI : intrinsicCalls) {
  596. // Find the corresponding pointer (bitcast from alloca, global value, an
  597. // argument, ...).
  598. Value *voidPtr = CI->getArgOperand(1);
  599. DXASSERT(voidPtr->getType()->isPointerTy() &&
  600. voidPtr->getType()->getPointerElementType()->isIntegerTy(8),
  601. "Expected operand of lifetime intrinsic to be of type i8*" );
  602. Value *ptr = nullptr;
  603. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(voidPtr)) {
  604. // This can happen if a local variable/array is promoted to a constant
  605. // global. In this case we must not introduce a store, since that would
  606. // overwrite the constant values in the initializer. Thus, we simply
  607. // remove the intrinsic.
  608. DXASSERT(CE->getOpcode() == Instruction::BitCast,
  609. "expected operand of lifetime intrinsic to be a bitcast");
  610. } else {
  611. // Otherwise, it must be a normal bitcast.
  612. DXASSERT(isa<BitCastInst>(voidPtr),
  613. "Expected operand of lifetime intrinsic to be a bitcast");
  614. BitCastInst *BC = cast<BitCastInst>(voidPtr);
  615. ptr = BC->getOperand(0);
  616. // If the original pointer is a global with initializer, do not replace
  617. // the intrinsic with a store.
  618. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(ptr))
  619. if (GV->hasInitializer() || GV->isExternallyInitialized())
  620. ptr = nullptr;
  621. }
  622. if (ptr) {
  623. // Determine the type to use when storing undef.
  624. DXASSERT(ptr->getType()->isPointerTy(),
  625. "Expected type of operand of lifetime intrinsic bitcast operand to be a pointer");
  626. Type *T = ptr->getType()->getPointerElementType();
  627. // Store undef at the location of the start/end intrinsic.
  628. // If we are targeting validator version < 6.6 we cannot store undef
  629. // since it causes a validation error. As a workaround we store 0, which
  630. // achieves mostly the same as storing undef but can cause overhead in
  631. // some situations.
  632. // We also allow to force zeroinitializer through a flag.
  633. if (forceZeroStoreLifetimes || ValMajor < 1 || (ValMajor == 1 && ValMinor < 6))
  634. IRBuilder<>(CI).CreateStore(Constant::getNullValue(T), ptr);
  635. else
  636. IRBuilder<>(CI).CreateStore(UndefValue::get(T), ptr);
  637. }
  638. // Erase the intrinsic call and, if it has no uses anymore, the bitcast as
  639. // well.
  640. DXASSERT_NOMSG(CI->use_empty());
  641. CI->eraseFromParent();
  642. // Erase the bitcast inst if it is not a ConstantExpr.
  643. if (BitCastInst *BC = dyn_cast<BitCastInst>(voidPtr))
  644. if (BC->use_empty())
  645. BC->eraseFromParent();
  646. }
  647. // Erase the intrinsic declarations.
  648. DXASSERT_NOMSG(StartDecl->use_empty());
  649. DXASSERT_NOMSG(EndDecl->use_empty());
  650. cast<Function>(StartDecl)->eraseFromParent();
  651. cast<Function>(EndDecl)->eraseFromParent();
  652. }
  653. bool runOnModule(Module &M) override {
  654. if (M.HasDxilModule()) {
  655. DxilModule &DM = M.GetDxilModule();
  656. unsigned ValMajor = 0;
  657. unsigned ValMinor = 0;
  658. DM.GetValidatorVersion(ValMajor, ValMinor);
  659. unsigned DxilMajor = 0;
  660. unsigned DxilMinor = 0;
  661. DM.GetDxilVersion(DxilMajor, DxilMinor);
  662. bool IsLib = DM.GetShaderModel()->IsLib();
  663. // Skip validation patch for lib.
  664. if (!IsLib) {
  665. if (DXIL::CompareVersions(ValMajor, ValMinor, 1, 1) <= 0) {
  666. patchValidation_1_1(M);
  667. }
  668. // Set used masks for signature elements
  669. MarkUsedSignatureElements(DM.GetEntryFunction(), DM);
  670. if (DM.GetShaderModel()->IsHS())
  671. MarkUsedSignatureElements(DM.GetPatchConstantFunction(), DM);
  672. }
  673. // Replace lifetime intrinsics if requested or necessary.
  674. const bool forceZeroStoreLifetimes = DM.GetForceZeroStoreLifetimes();
  675. if (forceZeroStoreLifetimes ||
  676. DXIL::CompareVersions(DxilMajor, DxilMinor, 1, 6) < 0) {
  677. patchLifetimeIntrinsics(M, ValMajor, ValMinor, forceZeroStoreLifetimes);
  678. }
  679. hlsl::OP *hlslOP = DM.GetOP();
  680. // Basic down-conversions for Dxil < 1.6
  681. if (DXIL::CompareVersions(DxilMajor, DxilMinor, 1, 6) < 0) {
  682. patchDxil_1_6(M, hlslOP, ValMajor, ValMinor);
  683. }
  684. // Patch all existing dxil versions for some future one
  685. // that differentiates immediate and programmable gathers
  686. ReplaceIntrinsics(M, hlslOP, OP::OpCode::TextureGatherImm, OP::OpCode::TextureGather);
  687. ReplaceIntrinsics(M, hlslOP, OP::OpCode::TextureGatherCmpImm, OP::OpCode::TextureGatherCmp);
  688. // Remove store undef output.
  689. RemoveStoreUndefOutput(M, hlslOP);
  690. // Turn dx.break() conditional into global
  691. LowerDxBreak(M);
  692. RemoveUnusedStaticGlobal(M);
  693. // Remove unnecessary address space casts.
  694. CleanupSharedMemoryAddrSpaceCast(M);
  695. // Clear inbound for GEP which has none-const index.
  696. LegalizeSharedMemoryGEPInbound(M);
  697. // Strip parameters of entry function.
  698. StripEntryParameters(M, DM, IsLib);
  699. // Update flags to reflect any changes.
  700. DM.CollectShaderFlagsForModule();
  701. // Update Validator Version
  702. DM.UpgradeToMinValidatorVersion();
  703. // Clear intermediate options that shouldn't be in the final DXIL
  704. DM.ClearIntermediateOptions();
  705. // Remove unused AllocateRayQuery calls
  706. RemoveUnusedRayQuery(M);
  707. if (IsLib && DXIL::CompareVersions(ValMajor, ValMinor, 1, 4) <= 0) {
  708. // 1.4 validator requires function annotations for all functions
  709. AddFunctionAnnotationForInitializers(M, DM);
  710. }
  711. // Fix DIExpression fragments that cover whole variables
  712. LegalizeDbgFragments(M);
  713. return true;
  714. }
  715. return false;
  716. }
  717. private:
  718. void RemoveUnusedStaticGlobal(Module &M) {
  719. // Remove unused internal global.
  720. std::vector<GlobalVariable *> staticGVs;
  721. for (GlobalVariable &GV : M.globals()) {
  722. if (dxilutil::IsStaticGlobal(&GV) ||
  723. dxilutil::IsSharedMemoryGlobal(&GV)) {
  724. staticGVs.emplace_back(&GV);
  725. }
  726. }
  727. for (GlobalVariable *GV : staticGVs) {
  728. bool onlyStoreUse = true;
  729. for (User *user : GV->users()) {
  730. if (isa<StoreInst>(user))
  731. continue;
  732. if (isa<ConstantExpr>(user) && user->user_empty())
  733. continue;
  734. onlyStoreUse = false;
  735. break;
  736. }
  737. if (onlyStoreUse) {
  738. for (auto UserIt = GV->user_begin(); UserIt != GV->user_end();) {
  739. Value *User = *(UserIt++);
  740. if (Instruction *I = dyn_cast<Instruction>(User)) {
  741. I->eraseFromParent();
  742. } else {
  743. ConstantExpr *CE = cast<ConstantExpr>(User);
  744. CE->dropAllReferences();
  745. }
  746. }
  747. GV->eraseFromParent();
  748. }
  749. }
  750. }
  751. static bool BitPieceCoversEntireVar(DIExpression *expr, DILocalVariable *var, DITypeIdentifierMap &TypeIdentifierMap) {
  752. if (expr->isBitPiece()) {
  753. DIType *ty = var->getType().resolve(TypeIdentifierMap);
  754. return expr->getBitPieceOffset() == 0 && expr->getBitPieceSize() == ty->getSizeInBits();
  755. }
  756. return false;
  757. }
  758. static void LegalizeDbgFragmentsForDbgIntrinsic(Function *f, DITypeIdentifierMap &TypeIdentifierMap) {
  759. Intrinsic::ID intrinsic = f->getIntrinsicID();
  760. DIBuilder dib(*f->getParent());
  761. if (intrinsic == Intrinsic::dbg_value) {
  762. for (auto it = f->user_begin(), end = f->user_end(); it != end;) {
  763. User *u = *(it++);
  764. DbgValueInst *di = cast<DbgValueInst>(u);
  765. Value *value = di->getValue();
  766. if (!value) {
  767. di->eraseFromParent();
  768. continue;
  769. }
  770. DIExpression *expr = di->getExpression();
  771. DILocalVariable *var = di->getVariable();
  772. if (BitPieceCoversEntireVar(expr, var, TypeIdentifierMap)) {
  773. dib.insertDbgValueIntrinsic(value, 0, var, DIExpression::get(di->getContext(), {}), di->getDebugLoc(), di);
  774. di->eraseFromParent();
  775. }
  776. }
  777. }
  778. else if (intrinsic == Intrinsic::dbg_declare) {
  779. for (auto it = f->user_begin(), end = f->user_end(); it != end;) {
  780. User *u = *(it++);
  781. DbgDeclareInst *di = cast<DbgDeclareInst>(u);
  782. Value *addr = di->getAddress();
  783. if (!addr) {
  784. di->eraseFromParent();
  785. continue;
  786. }
  787. DIExpression *expr = di->getExpression();
  788. DILocalVariable *var = di->getVariable();
  789. if (BitPieceCoversEntireVar(expr, var, TypeIdentifierMap)) {
  790. dib.insertDeclare(addr, var, DIExpression::get(di->getContext(), {}), di->getDebugLoc(), di);
  791. di->eraseFromParent();
  792. }
  793. }
  794. }
  795. }
  796. static void LegalizeDbgFragments(Module &M) {
  797. DITypeIdentifierMap TypeIdentifierMap;
  798. if (Function *f = M.getFunction(Intrinsic::getName(Intrinsic::dbg_value))) {
  799. LegalizeDbgFragmentsForDbgIntrinsic(f, TypeIdentifierMap);
  800. }
  801. if (Function *f = M.getFunction(Intrinsic::getName(Intrinsic::dbg_declare))) {
  802. LegalizeDbgFragmentsForDbgIntrinsic(f, TypeIdentifierMap);
  803. }
  804. }
  805. void RemoveStoreUndefOutput(Module &M, hlsl::OP *hlslOP) {
  806. for (iplist<Function>::iterator F : M.getFunctionList()) {
  807. if (!hlslOP->IsDxilOpFunc(F))
  808. continue;
  809. DXIL::OpCodeClass opClass;
  810. bool bHasOpClass = hlslOP->GetOpCodeClass(F, opClass);
  811. DXASSERT_LOCALVAR(bHasOpClass, bHasOpClass, "else not a dxil op func");
  812. if (opClass != DXIL::OpCodeClass::StoreOutput)
  813. continue;
  814. for (auto it = F->user_begin(); it != F->user_end();) {
  815. CallInst *CI = dyn_cast<CallInst>(*(it++));
  816. if (!CI)
  817. continue;
  818. Value *V = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputValOpIdx);
  819. // Remove the store of undef.
  820. if (isa<UndefValue>(V))
  821. CI->eraseFromParent();
  822. }
  823. }
  824. }
  825. void LegalizeSharedMemoryGEPInbound(Module &M) {
  826. const DataLayout &DL = M.getDataLayout();
  827. // Clear inbound for GEP which has none-const index.
  828. for (GlobalVariable &GV : M.globals()) {
  829. if (dxilutil::IsSharedMemoryGlobal(&GV)) {
  830. CheckInBoundForTGSM(GV, DL);
  831. }
  832. }
  833. }
  834. void StripEntryParameters(Module &M, DxilModule &DM, bool IsLib) {
  835. DenseMap<const Function *, DISubprogram *> FunctionDIs =
  836. makeSubprogramMap(M);
  837. // Strip parameters of entry function.
  838. if (!IsLib) {
  839. if (Function *OldPatchConstantFunc = DM.GetPatchConstantFunction()) {
  840. Function *NewPatchConstantFunc =
  841. StripFunctionParameter(OldPatchConstantFunc, DM, FunctionDIs);
  842. if (NewPatchConstantFunc) {
  843. DM.SetPatchConstantFunction(NewPatchConstantFunc);
  844. // Erase once the DxilModule doesn't track the old function anymore
  845. DXASSERT(DM.IsPatchConstantShader(NewPatchConstantFunc) && !DM.IsPatchConstantShader(OldPatchConstantFunc),
  846. "Error while migrating to parameter-stripped patch constant function.");
  847. OldPatchConstantFunc->eraseFromParent();
  848. }
  849. }
  850. if (Function *OldEntryFunc = DM.GetEntryFunction()) {
  851. StringRef Name = DM.GetEntryFunctionName();
  852. OldEntryFunc->setName(Name);
  853. Function *NewEntryFunc = StripFunctionParameter(OldEntryFunc, DM, FunctionDIs);
  854. if (NewEntryFunc) {
  855. DM.SetEntryFunction(NewEntryFunc);
  856. OldEntryFunc->eraseFromParent();
  857. }
  858. }
  859. } else {
  860. std::vector<Function *> entries;
  861. // Handle when multiple hull shaders point to the same patch constant function
  862. MapVector<Function*, llvm::SmallVector<Function*, 2>> PatchConstantFuncUsers;
  863. for (iplist<Function>::iterator F : M.getFunctionList()) {
  864. if (DM.IsEntryThatUsesSignatures(F)) {
  865. auto *FT = F->getFunctionType();
  866. // Only do this when has parameters.
  867. if (FT->getNumParams() > 0 || !FT->getReturnType()->isVoidTy()) {
  868. entries.emplace_back(F);
  869. }
  870. DxilFunctionProps& props = DM.GetDxilFunctionProps(F);
  871. if (props.IsHS() && props.ShaderProps.HS.patchConstantFunc) {
  872. FunctionType* PatchConstantFuncTy = props.ShaderProps.HS.patchConstantFunc->getFunctionType();
  873. if (PatchConstantFuncTy->getNumParams() > 0 || !PatchConstantFuncTy->getReturnType()->isVoidTy()) {
  874. // Accumulate all hull shaders using a given patch constant function,
  875. // so we can update it once and fix all hull shaders, without having an intermediary
  876. // state where some hull shaders point to a destroyed patch constant function.
  877. PatchConstantFuncUsers[props.ShaderProps.HS.patchConstantFunc].emplace_back(F);
  878. }
  879. }
  880. }
  881. }
  882. // Strip patch constant functions first
  883. for (auto &PatchConstantFuncEntry : PatchConstantFuncUsers) {
  884. Function* OldPatchConstantFunc = PatchConstantFuncEntry.first;
  885. Function* NewPatchConstantFunc = StripFunctionParameter(OldPatchConstantFunc, DM, FunctionDIs);
  886. if (NewPatchConstantFunc) {
  887. // Update all user hull shaders
  888. for (Function *HullShaderFunc : PatchConstantFuncEntry.second)
  889. DM.SetPatchConstantFunctionForHS(HullShaderFunc, NewPatchConstantFunc);
  890. // Erase once the DxilModule doesn't track the old function anymore
  891. DXASSERT(DM.IsPatchConstantShader(NewPatchConstantFunc) && !DM.IsPatchConstantShader(OldPatchConstantFunc),
  892. "Error while migrating to parameter-stripped patch constant function.");
  893. OldPatchConstantFunc->eraseFromParent();
  894. }
  895. }
  896. for (Function *OldEntry : entries) {
  897. Function *NewEntry = StripFunctionParameter(OldEntry, DM, FunctionDIs);
  898. if (NewEntry) OldEntry->eraseFromParent();
  899. }
  900. }
  901. }
  902. void AddFunctionAnnotationForInitializers(Module &M, DxilModule &DM) {
  903. if (GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors")) {
  904. if (isa<ConstantAggregateZero>(GV->getInitializer())) {
  905. DXASSERT_NOMSG(GV->user_empty());
  906. GV->eraseFromParent();
  907. return;
  908. }
  909. ConstantArray *init = cast<ConstantArray>(GV->getInitializer());
  910. for (auto V : init->operand_values()) {
  911. if (isa<ConstantAggregateZero>(V))
  912. continue;
  913. ConstantStruct *CS = cast<ConstantStruct>(V);
  914. if (isa<ConstantPointerNull>(CS->getOperand(1)))
  915. continue;
  916. Function *F = cast<Function>(CS->getOperand(1));
  917. if (DM.GetTypeSystem().GetFunctionAnnotation(F) == nullptr)
  918. DM.GetTypeSystem().AddFunctionAnnotation(F);
  919. }
  920. }
  921. }
  922. void RemoveUnusedRayQuery(Module &M) {
  923. hlsl::OP *hlslOP = M.GetDxilModule().GetOP();
  924. llvm::Function *AllocFn = hlslOP->GetOpFunc(
  925. DXIL::OpCode::AllocateRayQuery, Type::getVoidTy(M.getContext()));
  926. SmallVector<CallInst*, 4> DeadInsts;
  927. for (auto U : AllocFn->users()) {
  928. if (CallInst *CI = dyn_cast<CallInst>(U)) {
  929. if (CI->user_empty()) {
  930. DeadInsts.emplace_back(CI);
  931. }
  932. }
  933. }
  934. for (auto CI : DeadInsts) {
  935. CI->eraseFromParent();
  936. }
  937. if (AllocFn->user_empty()) {
  938. AllocFn->eraseFromParent();
  939. }
  940. }
  941. // Convert all uses of dx.break() into per-function load/cmp of dx.break.cond global constant
  942. void LowerDxBreak(Module &M) {
  943. if (Function *BreakFunc = M.getFunction(DXIL::kDxBreakFuncName)) {
  944. if (!BreakFunc->use_empty()) {
  945. llvm::Type *i32Ty = llvm::Type::getInt32Ty(M.getContext());
  946. Type *i32ArrayTy = ArrayType::get(i32Ty, 1);
  947. unsigned int Values[1] = { 0 };
  948. Constant *InitialValue = ConstantDataArray::get(M.getContext(), Values);
  949. Constant *GV = new GlobalVariable(M, i32ArrayTy, true,
  950. GlobalValue::InternalLinkage,
  951. InitialValue, DXIL::kDxBreakCondName);
  952. Constant *Indices[] = { ConstantInt::get(i32Ty, 0), ConstantInt::get(i32Ty, 0) };
  953. Constant *Gep = ConstantExpr::getGetElementPtr(nullptr, GV, Indices);
  954. SmallDenseMap<llvm::Function*, llvm::ICmpInst*, 16> DxBreakCmpMap;
  955. // Replace all uses of dx.break with references to the constant global
  956. for (auto I = BreakFunc->user_begin(), E = BreakFunc->user_end(); I != E;) {
  957. User *U = *I++;
  958. CallInst *CI = cast<CallInst>(U);
  959. Function *F = CI->getParent()->getParent();
  960. ICmpInst *Cmp = DxBreakCmpMap.lookup(F);
  961. if (!Cmp) {
  962. Instruction *IP = dxilutil::FindAllocaInsertionPt(F);
  963. LoadInst *LI = new LoadInst(Gep, nullptr, false, IP);
  964. Cmp = new ICmpInst(IP, ICmpInst::ICMP_EQ, LI, llvm::ConstantInt::get(i32Ty,0));
  965. DxBreakCmpMap[F] = Cmp;
  966. }
  967. CI->replaceAllUsesWith(Cmp);
  968. CI->eraseFromParent();
  969. }
  970. }
  971. BreakFunc->eraseFromParent();
  972. }
  973. for (Function &F : M) {
  974. for (BasicBlock &BB : F) {
  975. if (BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
  976. BI->setMetadata(DXIL::kDxBreakMDName, nullptr);
  977. }
  978. }
  979. }
  980. }
  981. };
  982. }
  983. char DxilFinalizeModule::ID = 0;
  984. ModulePass *llvm::createDxilFinalizeModulePass() {
  985. return new DxilFinalizeModule();
  986. }
  987. INITIALIZE_PASS(DxilFinalizeModule, "hlsl-dxilfinalize", "HLSL DXIL Finalize Module", false, false)
  988. ///////////////////////////////////////////////////////////////////////////////
  989. namespace {
  990. typedef MapVector< PHINode*, SmallVector<Value*,8> > PHIReplacementMap;
  991. bool RemoveAddrSpaceCasts(Value *Val, Value *NewVal,
  992. PHIReplacementMap &phiReplacements,
  993. DenseMap<Value*, Value*> &valueMap) {
  994. bool bChanged = false;
  995. for (auto itU = Val->use_begin(), itEnd = Val->use_end(); itU != itEnd; ) {
  996. Use &use = *(itU++);
  997. User *user = use.getUser();
  998. Value *userReplacement = user;
  999. bool bConstructReplacement = false;
  1000. bool bCleanupInst = false;
  1001. auto valueMapIter = valueMap.find(user);
  1002. if (valueMapIter != valueMap.end())
  1003. userReplacement = valueMapIter->second;
  1004. else if (Val != NewVal)
  1005. bConstructReplacement = true;
  1006. if (ConstantExpr* CE = dyn_cast<ConstantExpr>(user)) {
  1007. if (CE->getOpcode() == Instruction::BitCast) {
  1008. if (bConstructReplacement) {
  1009. // Replicate bitcast in target address space
  1010. Type* NewTy = PointerType::get(
  1011. CE->getType()->getPointerElementType(),
  1012. NewVal->getType()->getPointerAddressSpace());
  1013. userReplacement = ConstantExpr::getBitCast(cast<Constant>(NewVal), NewTy);
  1014. }
  1015. } else if (CE->getOpcode() == Instruction::GetElementPtr) {
  1016. if (bConstructReplacement) {
  1017. // Replicate GEP in target address space
  1018. GEPOperator *GEP = cast<GEPOperator>(CE);
  1019. SmallVector<Value*, 8> idxList(GEP->idx_begin(), GEP->idx_end());
  1020. userReplacement = ConstantExpr::getGetElementPtr(
  1021. nullptr, cast<Constant>(NewVal), idxList, GEP->isInBounds());
  1022. }
  1023. } else if (CE->getOpcode() == Instruction::AddrSpaceCast) {
  1024. userReplacement = NewVal;
  1025. bConstructReplacement = false;
  1026. } else {
  1027. DXASSERT(false, "RemoveAddrSpaceCasts: unhandled pointer ConstantExpr");
  1028. }
  1029. } else if (Instruction *I = dyn_cast<Instruction>(user)) {
  1030. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(user)) {
  1031. if (bConstructReplacement) {
  1032. IRBuilder<> Builder(GEP);
  1033. SmallVector<Value*, 8> idxList(GEP->idx_begin(), GEP->idx_end());
  1034. if (GEP->isInBounds())
  1035. userReplacement = Builder.CreateInBoundsGEP(NewVal, idxList, GEP->getName());
  1036. else
  1037. userReplacement = Builder.CreateGEP(NewVal, idxList, GEP->getName());
  1038. }
  1039. } else if (BitCastInst *BC = dyn_cast<BitCastInst>(user)) {
  1040. if (bConstructReplacement) {
  1041. IRBuilder<> Builder(BC);
  1042. Type* NewTy = PointerType::get(
  1043. BC->getType()->getPointerElementType(),
  1044. NewVal->getType()->getPointerAddressSpace());
  1045. userReplacement = Builder.CreateBitCast(NewVal, NewTy);
  1046. }
  1047. } else if (PHINode *PHI = dyn_cast<PHINode>(user)) {
  1048. // set replacement phi values for PHI pass
  1049. unsigned numValues = PHI->getNumIncomingValues();
  1050. auto &phiValues = phiReplacements[PHI];
  1051. if (phiValues.empty())
  1052. phiValues.resize(numValues, nullptr);
  1053. for (unsigned idx = 0; idx < numValues; ++idx) {
  1054. if (phiValues[idx] == nullptr &&
  1055. PHI->getIncomingValue(idx) == Val) {
  1056. phiValues[idx] = NewVal;
  1057. bChanged = true;
  1058. }
  1059. }
  1060. continue;
  1061. } else if (isa<AddrSpaceCastInst>(user)) {
  1062. userReplacement = NewVal;
  1063. bConstructReplacement = false;
  1064. bCleanupInst = true;
  1065. } else if (isa<CallInst>(user)) {
  1066. continue;
  1067. } else {
  1068. if (Val != NewVal) {
  1069. use.set(NewVal);
  1070. bChanged = true;
  1071. }
  1072. continue;
  1073. }
  1074. }
  1075. if (bConstructReplacement && user != userReplacement)
  1076. valueMap[user] = userReplacement;
  1077. bChanged |= RemoveAddrSpaceCasts(user, userReplacement, phiReplacements,
  1078. valueMap);
  1079. if (bCleanupInst && user->use_empty()) {
  1080. // Clean up old instruction if it's now unused.
  1081. // Safe during this use iteration when only one use of V in instruction.
  1082. if (Instruction *I = dyn_cast<Instruction>(user))
  1083. I->eraseFromParent();
  1084. bChanged = true;
  1085. }
  1086. }
  1087. return bChanged;
  1088. }
  1089. }
  1090. bool CleanupSharedMemoryAddrSpaceCast(Module &M) {
  1091. bool bChanged = false;
  1092. // Eliminate address space casts if possible
  1093. // Collect phi nodes so we can replace iteratively after pass over GVs
  1094. PHIReplacementMap phiReplacements;
  1095. DenseMap<Value*, Value*> valueMap;
  1096. for (GlobalVariable &GV : M.globals()) {
  1097. if (dxilutil::IsSharedMemoryGlobal(&GV)) {
  1098. bChanged |= RemoveAddrSpaceCasts(&GV, &GV, phiReplacements,
  1099. valueMap);
  1100. }
  1101. }
  1102. bool bConverged = false;
  1103. while (!phiReplacements.empty() && !bConverged) {
  1104. bConverged = true;
  1105. for (auto &phiReplacement : phiReplacements) {
  1106. PHINode *PHI = phiReplacement.first;
  1107. unsigned origAddrSpace = PHI->getType()->getPointerAddressSpace();
  1108. unsigned incomingAddrSpace = UINT_MAX;
  1109. bool bReplacePHI = true;
  1110. bool bRemovePHI = false;
  1111. for (auto V : phiReplacement.second) {
  1112. if (nullptr == V) {
  1113. // cannot replace phi (yet)
  1114. bReplacePHI = false;
  1115. break;
  1116. }
  1117. unsigned addrSpace = V->getType()->getPointerAddressSpace();
  1118. if (incomingAddrSpace == UINT_MAX) {
  1119. incomingAddrSpace = addrSpace;
  1120. } else if (addrSpace != incomingAddrSpace) {
  1121. bRemovePHI = true;
  1122. break;
  1123. }
  1124. }
  1125. if (origAddrSpace == incomingAddrSpace)
  1126. bRemovePHI = true;
  1127. if (bRemovePHI) {
  1128. // Cannot replace phi. Remove it and restart.
  1129. phiReplacements.erase(PHI);
  1130. bConverged = false;
  1131. break;
  1132. }
  1133. if (!bReplacePHI)
  1134. continue;
  1135. auto &NewVal = valueMap[PHI];
  1136. PHINode *NewPHI = nullptr;
  1137. if (NewVal) {
  1138. NewPHI = cast<PHINode>(NewVal);
  1139. } else {
  1140. IRBuilder<> Builder(PHI);
  1141. NewPHI = Builder.CreatePHI(
  1142. PointerType::get(PHI->getType()->getPointerElementType(),
  1143. incomingAddrSpace),
  1144. PHI->getNumIncomingValues(),
  1145. PHI->getName());
  1146. NewVal = NewPHI;
  1147. for (unsigned idx = 0; idx < PHI->getNumIncomingValues(); idx++) {
  1148. NewPHI->addIncoming(phiReplacement.second[idx],
  1149. PHI->getIncomingBlock(idx));
  1150. }
  1151. }
  1152. if (RemoveAddrSpaceCasts(PHI, NewPHI, phiReplacements,
  1153. valueMap)) {
  1154. bConverged = false;
  1155. bChanged = true;
  1156. break;
  1157. }
  1158. if (PHI->use_empty()) {
  1159. phiReplacements.erase(PHI);
  1160. bConverged = false;
  1161. bChanged = true;
  1162. break;
  1163. }
  1164. }
  1165. }
  1166. // Cleanup unused replacement instructions
  1167. SmallVector<WeakVH, 8> cleanupInsts;
  1168. for (auto it : valueMap) {
  1169. if (isa<Instruction>(it.first))
  1170. cleanupInsts.push_back(it.first);
  1171. if (isa<Instruction>(it.second))
  1172. cleanupInsts.push_back(it.second);
  1173. }
  1174. for (auto V : cleanupInsts) {
  1175. if (!V)
  1176. continue;
  1177. if (PHINode *PHI = dyn_cast<PHINode>(V))
  1178. RecursivelyDeleteDeadPHINode(PHI);
  1179. else if (Instruction *I = dyn_cast<Instruction>(V))
  1180. RecursivelyDeleteTriviallyDeadInstructions(I);
  1181. }
  1182. return bChanged;
  1183. }
  1184. class DxilCleanupAddrSpaceCast : public ModulePass {
  1185. public:
  1186. static char ID; // Pass identification, replacement for typeid
  1187. explicit DxilCleanupAddrSpaceCast() : ModulePass(ID) {}
  1188. const char *getPassName() const override { return "HLSL DXIL Cleanup Address Space Cast"; }
  1189. bool runOnModule(Module &M) override {
  1190. return CleanupSharedMemoryAddrSpaceCast(M);
  1191. }
  1192. };
  1193. char DxilCleanupAddrSpaceCast::ID = 0;
  1194. ModulePass *llvm::createDxilCleanupAddrSpaceCastPass() {
  1195. return new DxilCleanupAddrSpaceCast();
  1196. }
  1197. INITIALIZE_PASS(DxilCleanupAddrSpaceCast, "hlsl-dxil-cleanup-addrspacecast", "HLSL DXIL Cleanup Address Space Cast", false, false)
  1198. ///////////////////////////////////////////////////////////////////////////////
  1199. namespace {
  1200. class DxilEmitMetadata : public ModulePass {
  1201. public:
  1202. static char ID; // Pass identification, replacement for typeid
  1203. explicit DxilEmitMetadata() : ModulePass(ID) {}
  1204. const char *getPassName() const override { return "HLSL DXIL Metadata Emit"; }
  1205. bool runOnModule(Module &M) override {
  1206. if (M.HasDxilModule()) {
  1207. DxilModule::ClearDxilMetadata(M);
  1208. patchIsFrontfaceTy(M);
  1209. M.GetDxilModule().EmitDxilMetadata();
  1210. return true;
  1211. }
  1212. return false;
  1213. }
  1214. private:
  1215. void patchIsFrontfaceTy(Module &M);
  1216. };
  1217. void patchIsFrontface(DxilSignatureElement &Elt, bool bForceUint) {
  1218. // If force to uint, change i1 to u32.
  1219. // If not force to uint, change u32 to i1.
  1220. if (bForceUint && Elt.GetCompType() == CompType::Kind::I1)
  1221. Elt.SetCompType(CompType::Kind::U32);
  1222. else if (!bForceUint && Elt.GetCompType() == CompType::Kind::U32)
  1223. Elt.SetCompType(CompType::Kind::I1);
  1224. }
  1225. void patchIsFrontface(DxilSignature &sig, bool bForceUint) {
  1226. for (auto &Elt : sig.GetElements()) {
  1227. if (Elt->GetSemantic()->GetKind() == Semantic::Kind::IsFrontFace) {
  1228. patchIsFrontface(*Elt, bForceUint);
  1229. }
  1230. }
  1231. }
  1232. void DxilEmitMetadata::patchIsFrontfaceTy(Module &M) {
  1233. DxilModule &DM = M.GetDxilModule();
  1234. const ShaderModel *pSM = DM.GetShaderModel();
  1235. if (!pSM->IsGS() && !pSM->IsPS())
  1236. return;
  1237. unsigned ValMajor, ValMinor;
  1238. DM.GetValidatorVersion(ValMajor, ValMinor);
  1239. bool bForceUint = ValMajor == 0 || (ValMajor >= 1 && ValMinor >= 2);
  1240. if (pSM->IsPS()) {
  1241. patchIsFrontface(DM.GetInputSignature(), bForceUint);
  1242. } else if (pSM->IsGS()) {
  1243. patchIsFrontface(DM.GetOutputSignature(), bForceUint);
  1244. }
  1245. }
  1246. }
  1247. char DxilEmitMetadata::ID = 0;
  1248. ModulePass *llvm::createDxilEmitMetadataPass() {
  1249. return new DxilEmitMetadata();
  1250. }
  1251. INITIALIZE_PASS(DxilEmitMetadata, "hlsl-dxilemit", "HLSL DXIL Metadata Emit", false, false)
  1252. ///////////////////////////////////////////////////////////////////////////////
  1253. namespace {
  1254. const StringRef UniNoWaveSensitiveGradientErrMsg =
  1255. "Gradient operations are not affected by wave-sensitive data or control "
  1256. "flow.";
  1257. class DxilValidateWaveSensitivity : public ModulePass {
  1258. public:
  1259. static char ID; // Pass identification, replacement for typeid
  1260. explicit DxilValidateWaveSensitivity() : ModulePass(ID) {}
  1261. const char *getPassName() const override {
  1262. return "HLSL DXIL wave sensitiveity validation";
  1263. }
  1264. bool runOnModule(Module &M) override {
  1265. // Only check ps and lib profile.
  1266. DxilModule &DM = M.GetDxilModule();
  1267. const ShaderModel *pSM = DM.GetShaderModel();
  1268. if (!pSM->IsPS() && !pSM->IsLib())
  1269. return false;
  1270. SmallVector<CallInst *, 16> gradientOps;
  1271. SmallVector<CallInst *, 16> barriers;
  1272. SmallVector<CallInst *, 16> waveOps;
  1273. for (auto &F : M) {
  1274. if (!F.isDeclaration())
  1275. continue;
  1276. for (User *U : F.users()) {
  1277. CallInst *CI = dyn_cast<CallInst>(U);
  1278. if (!CI)
  1279. continue;
  1280. Function *FCalled = CI->getCalledFunction();
  1281. if (!FCalled || !FCalled->isDeclaration())
  1282. continue;
  1283. if (!hlsl::OP::IsDxilOpFunc(FCalled))
  1284. continue;
  1285. DXIL::OpCode dxilOpcode = hlsl::OP::GetDxilOpFuncCallInst(CI);
  1286. if (OP::IsDxilOpWave(dxilOpcode)) {
  1287. waveOps.emplace_back(CI);
  1288. }
  1289. if (OP::IsDxilOpGradient(dxilOpcode)) {
  1290. gradientOps.push_back(CI);
  1291. }
  1292. if (dxilOpcode == DXIL::OpCode::Barrier) {
  1293. barriers.push_back(CI);
  1294. }
  1295. }
  1296. }
  1297. // Skip if not have wave op.
  1298. if (waveOps.empty())
  1299. return false;
  1300. // Skip if no gradient op.
  1301. if (gradientOps.empty())
  1302. return false;
  1303. for (auto &F : M) {
  1304. if (F.isDeclaration())
  1305. continue;
  1306. DenseSet<Instruction *> localGradientArgs;
  1307. for (CallInst *CI : gradientOps) {
  1308. if (CI->getParent()->getParent() == &F) {
  1309. for (Value *V : CI->arg_operands()) {
  1310. // TODO: only check operand which used for gradient calculation.
  1311. Instruction *vI = dyn_cast<Instruction>(V);
  1312. if (!vI)
  1313. continue;
  1314. localGradientArgs.insert(vI);
  1315. }
  1316. }
  1317. }
  1318. if (localGradientArgs.empty())
  1319. continue;
  1320. PostDominatorTree PDT;
  1321. PDT.runOnFunction(F);
  1322. std::unique_ptr<WaveSensitivityAnalysis> WaveVal(
  1323. WaveSensitivityAnalysis::create(PDT));
  1324. WaveVal->Analyze(&F);
  1325. for (Instruction *gradArg : localGradientArgs) {
  1326. // Check operand of gradient ops, not gradientOps itself.
  1327. if (WaveVal->IsWaveSensitive(gradArg)) {
  1328. dxilutil::EmitWarningOnInstruction(gradArg,
  1329. UniNoWaveSensitiveGradientErrMsg);
  1330. }
  1331. }
  1332. }
  1333. return false;
  1334. }
  1335. };
  1336. }
  1337. char DxilValidateWaveSensitivity::ID = 0;
  1338. ModulePass *llvm::createDxilValidateWaveSensitivityPass() {
  1339. return new DxilValidateWaveSensitivity();
  1340. }
  1341. INITIALIZE_PASS(DxilValidateWaveSensitivity, "hlsl-validate-wave-sensitivity", "HLSL DXIL wave sensitiveity validation", false, false)
  1342. namespace {
  1343. // Cull blocks from BreakBBs that containing instructions that are sensitive to the wave-sensitive Inst
  1344. // Sensitivity entails being an eventual user of the Inst and also belonging to a block with
  1345. // a break conditional on dx.break that breaks out of a loop that contains WaveCI
  1346. // LInfo is needed to determine loop contents. Visited is needed to prevent infinite looping.
  1347. static void CullSensitiveBlocks(LoopInfo *LInfo, Loop *WaveLoop, BasicBlock *LastBB, Instruction *Inst,
  1348. std::unordered_set<Instruction *> &Visited,
  1349. SmallDenseMap<BasicBlock *, Instruction *, 16> &BreakBBs) {
  1350. BasicBlock *BB = Inst->getParent();
  1351. Loop *BreakLoop = LInfo->getLoopFor(BB);
  1352. // If this instruction isn't in a loop, there is no need to track its sensitivity further
  1353. if (!BreakLoop || BreakBBs.empty())
  1354. return;
  1355. // To prevent infinite looping, only visit each instruction once
  1356. if (!Visited.insert(Inst).second)
  1357. return;
  1358. // If this BB wasn't already just processed, handle it now
  1359. if (LastBB != BB) {
  1360. // Determine if the instruction's block has an artificially-conditional break
  1361. // and breaks out of a loop that contains the waveCI
  1362. BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  1363. if (BI && BI->isConditional() && BreakLoop->contains(WaveLoop))
  1364. BreakBBs.erase(BB);
  1365. }
  1366. // Recurse on the users
  1367. for (User *U : Inst->users()) {
  1368. Instruction *I = cast<Instruction>(U);
  1369. CullSensitiveBlocks(LInfo, WaveLoop, BB, I, Visited, BreakBBs);
  1370. }
  1371. }
  1372. // Collect blocks that end in a dx.break dependent branch by tracing the descendants of BreakFunc
  1373. // that are found in ThisFunc and store the block and call instruction in BreakBBs
  1374. static void CollectBreakBlocks(Function *BreakFunc, Function *ThisFunc,
  1375. SmallDenseMap<BasicBlock *, Instruction *, 16> &BreakBBs) {
  1376. for (User *U : BreakFunc->users()) {
  1377. SmallVector<User *, 16> WorkList;
  1378. Instruction *CI = cast<Instruction>(U);
  1379. // If this user doesn't pertain to the current function, skip it.
  1380. if (CI->getParent()->getParent() != ThisFunc)
  1381. continue;
  1382. WorkList.append(CI->user_begin(), CI->user_end());
  1383. while (!WorkList.empty()) {
  1384. Instruction *I = dyn_cast<Instruction>(WorkList.pop_back_val());
  1385. // When we find a Branch that depends on dx.break, save it and stop
  1386. // This should almost always be the first user of the Call Inst
  1387. // If not, iterate on the users
  1388. if (BranchInst *BI = dyn_cast<BranchInst>(I))
  1389. BreakBBs[BI->getParent()] = CI;
  1390. else
  1391. WorkList.append(I->user_begin(), I->user_end());
  1392. }
  1393. }
  1394. }
  1395. // A pass to remove conditions from breaks that do not contain instructions that
  1396. // depend on wave operations that are in the loop that the break leaves.
  1397. class CleanupDxBreak : public FunctionPass {
  1398. public:
  1399. static char ID; // Pass identification, replacement for typeid
  1400. explicit CleanupDxBreak() : FunctionPass(ID) {}
  1401. const char *getPassName() const override { return "HLSL Remove unnecessary dx.break conditions"; }
  1402. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1403. AU.addRequired<LoopInfoWrapperPass>();
  1404. }
  1405. LoopInfo *LInfo;
  1406. bool runOnFunction(Function &F) override {
  1407. if (F.isDeclaration())
  1408. return false;
  1409. Module *M = F.getEntryBlock().getModule();
  1410. Function *BreakFunc = M->getFunction(DXIL::kDxBreakFuncName);
  1411. if (!BreakFunc)
  1412. return false;
  1413. LInfo = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  1414. // Collect the blocks that depend on dx.break and the instructions that call dx.break()
  1415. SmallDenseMap<BasicBlock *, Instruction *, 16> BreakBBs;
  1416. CollectBreakBlocks(BreakFunc, &F, BreakBBs);
  1417. if (BreakBBs.empty())
  1418. return false;
  1419. // Collect all wave calls in this function and group by loop
  1420. SmallDenseMap<Loop *, SmallVector<CallInst *, 8>, 16> WaveCalls;
  1421. for (Function &IF : M->functions()) {
  1422. HLOpcodeGroup opgroup = hlsl::GetHLOpcodeGroup(&IF);
  1423. // Only consider wave-sensitive intrinsics or extintrinsics
  1424. if (IF.isDeclaration() && IsHLWaveSensitive(&IF) && !BreakBBs.empty() &&
  1425. (opgroup == HLOpcodeGroup::HLIntrinsic || opgroup == HLOpcodeGroup::HLExtIntrinsic)) {
  1426. // For each user of the function, trace all its users to remove the blocks
  1427. for (User *U : IF.users()) {
  1428. CallInst *CI = cast<CallInst>(U);
  1429. if (CI->getParent()->getParent() == &F) {
  1430. Loop *WaveLoop = LInfo->getLoopFor(CI->getParent());
  1431. WaveCalls[WaveLoop].emplace_back(CI);
  1432. }
  1433. }
  1434. }
  1435. }
  1436. // For each wave operation, remove all the dx.break blocks that are sensitive to it
  1437. for (DenseMap<Loop*, SmallVector<CallInst *, 8>>::iterator I =
  1438. WaveCalls.begin(), E = WaveCalls.end();
  1439. I != E; ++I) {
  1440. Loop *loop = I->first;
  1441. std::unordered_set<Instruction *> Visited;
  1442. for (CallInst *CI : I->second) {
  1443. CullSensitiveBlocks(LInfo, loop, nullptr, CI, Visited, BreakBBs);
  1444. }
  1445. }
  1446. bool Changed = false;
  1447. // Revert artificially conditional breaks in non-wave-sensitive blocks that remain in BreakBBs
  1448. Constant *C = ConstantInt::get(Type::getInt1Ty(M->getContext()), 1);
  1449. for (auto &BB : BreakBBs) {
  1450. // Replace the call instruction with a constant boolen
  1451. BB.second->replaceAllUsesWith(C);
  1452. BB.second->eraseFromParent();
  1453. Changed = true;
  1454. }
  1455. return Changed;
  1456. }
  1457. };
  1458. }
  1459. char CleanupDxBreak::ID = 0;
  1460. INITIALIZE_PASS_BEGIN(CleanupDxBreak, "hlsl-cleanup-dxbreak", "HLSL Remove unnecessary dx.break conditions", false, false)
  1461. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  1462. INITIALIZE_PASS_END(CleanupDxBreak, "hlsl-cleanup-dxbreak", "HLSL Remove unnecessary dx.break conditions", false, false)
  1463. FunctionPass *llvm::createCleanupDxBreakPass() {
  1464. return new CleanupDxBreak();
  1465. }