CGHLSLMSFinishCodeGen.cpp 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // CGHLSLMSFinishCodeGen.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. // Impliment FinishCodeGen. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "llvm/IR/Function.h"
  12. #include "llvm/IR/IRBuilder.h"
  13. #include "llvm/IR/Module.h"
  14. #include "llvm/IR/Type.h"
  15. #include "llvm/IR/Instructions.h"
  16. #include "llvm/IR/InstIterator.h"
  17. #include "llvm/IR/GetElementPtrTypeIterator.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/StringRef.h"
  20. #include "llvm/Analysis/DxilValueCache.h"
  21. #include "llvm/Transforms/Utils/ValueMapper.h"
  22. #include "llvm/Transforms/Utils/Cloning.h"
  23. #include "CodeGenModule.h"
  24. #include "clang/Frontend/CodeGenOptions.h"
  25. #include "clang/Basic/LangOptions.h"
  26. #include "clang/Parse/ParseHLSL.h" // root sig would be in Parser if part of lang
  27. #include "dxc/HLSL/HLModule.h"
  28. #include "dxc/HLSL/HLSLExtensionsCodegenHelper.h"
  29. #include "dxc/DXIL/DxilOperations.h"
  30. #include "dxc/HlslIntrinsicOp.h"
  31. #include "dxc/DXIL/DxilUtil.h"
  32. #include "dxc/HLSL/DxilExportMap.h"
  33. #include "dxc/DXIL/DxilResourceProperties.h"
  34. #include "dxc/DXIL/DxilTypeSystem.h"
  35. #include "dxc/DXIL/DxilConstants.h"
  36. #include "dxc/DxilRootSignature/DxilRootSignature.h"
  37. #include "dxc/HLSL/DxilGenerationPass.h"
  38. #include "dxc/HLSL/HLMatrixType.h"
  39. #include <vector>
  40. #include <memory>
  41. #include "CGHLSLMSHelper.h"
  42. using namespace llvm;
  43. using namespace hlsl;
  44. using namespace CGHLSLMSHelper;
  45. namespace {
  46. Value *CreateHandleFromResPtr(Value *ResPtr, HLModule &HLM,
  47. llvm::Type *HandleTy, IRBuilder<> &Builder) {
  48. Module &M = *HLM.GetModule();
  49. // Load to make sure resource only have Ld/St use so mem2reg could remove
  50. // temp resource.
  51. Value *ldObj = Builder.CreateLoad(ResPtr);
  52. Value *args[] = {ldObj};
  53. CallInst *Handle = HLM.EmitHLOperationCall(
  54. Builder, HLOpcodeGroup::HLCreateHandle, 0, HandleTy, args, M);
  55. return Handle;
  56. }
  57. Value *CreateAnnotateHandle(HLModule &HLM, Value *Handle,
  58. DxilResourceProperties &RP, llvm::Type *ResTy,
  59. IRBuilder<> &Builder) {
  60. Constant *RPConstant = resource_helper::getAsConstant(
  61. RP, HLM.GetOP()->GetResourcePropertiesType(), *HLM.GetShaderModel());
  62. return HLM.EmitHLOperationCall(
  63. Builder, HLOpcodeGroup::HLAnnotateHandle,
  64. (unsigned)HLOpcodeGroup::HLAnnotateHandle, Handle->getType(),
  65. {Handle, Builder.getInt8((uint8_t)RP.Class),
  66. Builder.getInt8((uint8_t)RP.Kind), RPConstant, UndefValue::get(ResTy)},
  67. *HLM.GetModule());
  68. }
  69. void LowerGetResourceFromHeap(
  70. HLModule &HLM, std::vector<std::pair<Function *, unsigned>> &intrinsicMap) {
  71. llvm::Module &M = *HLM.GetModule();
  72. llvm::Type *HandleTy = HLM.GetOP()->GetHandleType();
  73. unsigned GetResFromHeapOp =
  74. static_cast<unsigned>(IntrinsicOp::IOP_CreateResourceFromHeap);
  75. DenseMap<Instruction *, Instruction *> ResourcePtrToHandlePtrMap;
  76. for (auto it : intrinsicMap) {
  77. unsigned opcode = it.second;
  78. if (opcode != GetResFromHeapOp)
  79. continue;
  80. Function *F = it.first;
  81. HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  82. if (group != HLOpcodeGroup::HLIntrinsic)
  83. continue;
  84. for (auto uit = F->user_begin(); uit != F->user_end();) {
  85. CallInst *CI = cast<CallInst>(*(uit++));
  86. Instruction *ResPtr = cast<Instruction>(CI->getArgOperand(0));
  87. Value *Index = CI->getArgOperand(1);
  88. IRBuilder<> Builder(CI);
  89. // Make a handle from GetResFromHeap.
  90. Value *Handle =
  91. HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLIntrinsic,
  92. GetResFromHeapOp, HandleTy, {Index}, M);
  93. // Find the handle ptr for res ptr.
  94. auto it = ResourcePtrToHandlePtrMap.find(ResPtr);
  95. Instruction *HandlePtr = nullptr;
  96. if (it != ResourcePtrToHandlePtrMap.end()) {
  97. HandlePtr = it->second;
  98. } else {
  99. IRBuilder<> AllocaBuilder(
  100. ResPtr->getParent()->getParent()->getEntryBlock().begin());
  101. HandlePtr = AllocaBuilder.CreateAlloca(HandleTy);
  102. ResourcePtrToHandlePtrMap[ResPtr] = HandlePtr;
  103. }
  104. // Store handle to handle ptr.
  105. Builder.CreateStore(Handle, HandlePtr);
  106. CI->eraseFromParent();
  107. }
  108. }
  109. // Replace load of Resource ptr into load of handel ptr.
  110. for (auto it : ResourcePtrToHandlePtrMap) {
  111. Instruction *resPtr = it.first;
  112. Instruction *handlePtr = it.second;
  113. for (auto uit = resPtr->user_begin(); uit != resPtr->user_end();) {
  114. User *U = *(uit++);
  115. BitCastInst *BCI = cast<BitCastInst>(U);
  116. DXASSERT(
  117. dxilutil::IsHLSLResourceType(BCI->getType()->getPointerElementType()),
  118. "illegal cast of resource ptr");
  119. for (auto cuit = BCI->user_begin(); cuit != BCI->user_end();) {
  120. LoadInst *LI = cast<LoadInst>(*(cuit++));
  121. IRBuilder<> Builder(LI);
  122. Value *Handle = Builder.CreateLoad(handlePtr);
  123. Value *Res =
  124. HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLCast,
  125. (unsigned)HLCastOpcode::HandleToResCast,
  126. LI->getType(), {Handle}, M);
  127. LI->replaceAllUsesWith(Res);
  128. LI->eraseFromParent();
  129. }
  130. BCI->eraseFromParent();
  131. }
  132. resPtr->eraseFromParent();
  133. }
  134. }
  135. void ReplaceBoolVectorSubscript(CallInst *CI) {
  136. Value *Ptr = CI->getArgOperand(0);
  137. Value *Idx = CI->getArgOperand(1);
  138. Value *IdxList[] = {ConstantInt::get(Idx->getType(), 0), Idx};
  139. for (auto It = CI->user_begin(), E = CI->user_end(); It != E;) {
  140. Instruction *user = cast<Instruction>(*(It++));
  141. IRBuilder<> Builder(user);
  142. Value *GEP = Builder.CreateInBoundsGEP(Ptr, IdxList);
  143. if (LoadInst *LI = dyn_cast<LoadInst>(user)) {
  144. Value *NewLd = Builder.CreateLoad(GEP);
  145. Value *cast = Builder.CreateZExt(NewLd, LI->getType());
  146. LI->replaceAllUsesWith(cast);
  147. LI->eraseFromParent();
  148. } else {
  149. // Must be a store inst here.
  150. StoreInst *SI = cast<StoreInst>(user);
  151. Value *V = SI->getValueOperand();
  152. Value *cast =
  153. Builder.CreateICmpNE(V, llvm::ConstantInt::get(V->getType(), 0));
  154. Builder.CreateStore(cast, GEP);
  155. SI->eraseFromParent();
  156. }
  157. }
  158. CI->eraseFromParent();
  159. }
  160. void ReplaceBoolVectorSubscript(Function *F) {
  161. for (auto It = F->user_begin(), E = F->user_end(); It != E;) {
  162. User *user = *(It++);
  163. CallInst *CI = cast<CallInst>(user);
  164. ReplaceBoolVectorSubscript(CI);
  165. }
  166. }
  167. // Add function body for intrinsic if possible.
  168. Function *CreateOpFunction(llvm::Module &M, Function *F,
  169. llvm::FunctionType *funcTy, HLOpcodeGroup group,
  170. unsigned opcode) {
  171. Function *opFunc = nullptr;
  172. AttributeSet attribs = F->getAttributes().getFnAttributes();
  173. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  174. if (group == HLOpcodeGroup::HLIntrinsic) {
  175. IntrinsicOp intriOp = static_cast<IntrinsicOp>(opcode);
  176. switch (intriOp) {
  177. case IntrinsicOp::MOP_Append:
  178. case IntrinsicOp::MOP_Consume: {
  179. bool bAppend = intriOp == IntrinsicOp::MOP_Append;
  180. llvm::Type *handleTy = funcTy->getParamType(HLOperandIndex::kHandleOpIdx);
  181. // Don't generate body for OutputStream::Append.
  182. if (bAppend && HLModule::IsStreamOutputPtrType(handleTy)) {
  183. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode, attribs);
  184. break;
  185. }
  186. opFunc = GetOrCreateHLFunctionWithBody(M, funcTy, group, opcode,
  187. bAppend ? "append" : "consume");
  188. llvm::Type *counterTy = llvm::Type::getInt32Ty(M.getContext());
  189. llvm::FunctionType *IncCounterFuncTy =
  190. llvm::FunctionType::get(counterTy, {opcodeTy, handleTy}, false);
  191. unsigned counterOpcode =
  192. bAppend ? (unsigned)IntrinsicOp::MOP_IncrementCounter
  193. : (unsigned)IntrinsicOp::MOP_DecrementCounter;
  194. Function *incCounterFunc =
  195. GetOrCreateHLFunction(M, IncCounterFuncTy, group, counterOpcode, attribs);
  196. llvm::Type *idxTy = counterTy;
  197. llvm::Type *valTy =
  198. bAppend ? funcTy->getParamType(HLOperandIndex::kAppendValOpIndex)
  199. : funcTy->getReturnType();
  200. // Return type for subscript should be pointer type, hence in memory
  201. // representation
  202. llvm::Type *subscriptTy = valTy;
  203. bool isBoolScalarOrVector = false;
  204. if (!subscriptTy->isPointerTy()) {
  205. if (subscriptTy->getScalarType()->isIntegerTy(1)) {
  206. isBoolScalarOrVector = true;
  207. llvm::Type *memReprType =
  208. llvm::IntegerType::get(subscriptTy->getContext(), 32);
  209. subscriptTy =
  210. subscriptTy->isVectorTy()
  211. ? llvm::VectorType::get(memReprType,
  212. subscriptTy->getVectorNumElements())
  213. : memReprType;
  214. }
  215. subscriptTy = llvm::PointerType::get(subscriptTy, 0);
  216. }
  217. llvm::FunctionType *SubscriptFuncTy = llvm::FunctionType::get(
  218. subscriptTy, {opcodeTy, handleTy, idxTy}, false);
  219. Function *subscriptFunc =
  220. GetOrCreateHLFunction(M, SubscriptFuncTy, HLOpcodeGroup::HLSubscript,
  221. (unsigned)HLSubscriptOpcode::DefaultSubscript, attribs);
  222. BasicBlock *BB =
  223. BasicBlock::Create(opFunc->getContext(), "Entry", opFunc);
  224. IRBuilder<> Builder(BB);
  225. auto argIter = opFunc->args().begin();
  226. // Skip the opcode arg.
  227. argIter++;
  228. Argument *thisArg = argIter++;
  229. // int counter = IncrementCounter/DecrementCounter(Buf);
  230. Value *incCounterOpArg = ConstantInt::get(idxTy, counterOpcode);
  231. Value *counter =
  232. Builder.CreateCall(incCounterFunc, {incCounterOpArg, thisArg});
  233. // Buf[counter];
  234. Value *subscriptOpArg = ConstantInt::get(
  235. idxTy, (unsigned)HLSubscriptOpcode::DefaultSubscript);
  236. Value *subscript =
  237. Builder.CreateCall(subscriptFunc, {subscriptOpArg, thisArg, counter});
  238. if (bAppend) {
  239. Argument *valArg = argIter;
  240. // Buf[counter] = val;
  241. if (valTy->isPointerTy()) {
  242. unsigned size = M.getDataLayout().getTypeAllocSize(
  243. subscript->getType()->getPointerElementType());
  244. Builder.CreateMemCpy(subscript, valArg, size, 1);
  245. } else {
  246. Value *storedVal = valArg;
  247. // Convert to memory representation
  248. if (isBoolScalarOrVector)
  249. storedVal = Builder.CreateZExt(
  250. storedVal, subscriptTy->getPointerElementType(), "frombool");
  251. Builder.CreateStore(storedVal, subscript);
  252. }
  253. Builder.CreateRetVoid();
  254. } else {
  255. // return Buf[counter];
  256. if (valTy->isPointerTy())
  257. Builder.CreateRet(subscript);
  258. else {
  259. Value *retVal = Builder.CreateLoad(subscript);
  260. // Convert to register representation
  261. if (isBoolScalarOrVector)
  262. retVal = Builder.CreateICmpNE(
  263. retVal, Constant::getNullValue(retVal->getType()), "tobool");
  264. Builder.CreateRet(retVal);
  265. }
  266. }
  267. } break;
  268. case IntrinsicOp::IOP_sincos: {
  269. opFunc =
  270. GetOrCreateHLFunctionWithBody(M, funcTy, group, opcode, "sincos");
  271. llvm::Type *valTy =
  272. funcTy->getParamType(HLOperandIndex::kTrinaryOpSrc0Idx);
  273. llvm::FunctionType *sinFuncTy =
  274. llvm::FunctionType::get(valTy, {opcodeTy, valTy}, false);
  275. unsigned sinOp = static_cast<unsigned>(IntrinsicOp::IOP_sin);
  276. unsigned cosOp = static_cast<unsigned>(IntrinsicOp::IOP_cos);
  277. Function *sinFunc = GetOrCreateHLFunction(M, sinFuncTy, group, sinOp, attribs);
  278. Function *cosFunc = GetOrCreateHLFunction(M, sinFuncTy, group, cosOp, attribs);
  279. BasicBlock *BB =
  280. BasicBlock::Create(opFunc->getContext(), "Entry", opFunc);
  281. IRBuilder<> Builder(BB);
  282. auto argIter = opFunc->args().begin();
  283. // Skip the opcode arg.
  284. argIter++;
  285. Argument *valArg = argIter++;
  286. Argument *sinPtrArg = argIter++;
  287. Argument *cosPtrArg = argIter++;
  288. Value *sinOpArg = ConstantInt::get(opcodeTy, sinOp);
  289. Value *sinVal = Builder.CreateCall(sinFunc, {sinOpArg, valArg});
  290. Builder.CreateStore(sinVal, sinPtrArg);
  291. Value *cosOpArg = ConstantInt::get(opcodeTy, cosOp);
  292. Value *cosVal = Builder.CreateCall(cosFunc, {cosOpArg, valArg});
  293. Builder.CreateStore(cosVal, cosPtrArg);
  294. // Ret.
  295. Builder.CreateRetVoid();
  296. } break;
  297. default:
  298. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode, attribs);
  299. break;
  300. }
  301. } else if (group == HLOpcodeGroup::HLExtIntrinsic) {
  302. llvm::StringRef fnName = F->getName();
  303. llvm::StringRef groupName = GetHLOpcodeGroupNameByAttr(F);
  304. opFunc =
  305. GetOrCreateHLFunction(M, funcTy, group, &groupName, &fnName, opcode, attribs);
  306. } else {
  307. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode, attribs);
  308. }
  309. return opFunc;
  310. }
  311. DxilResourceProperties GetResourcePropsFromIntrinsicObjectArg(
  312. Value *arg, HLModule &HLM, DxilTypeSystem &typeSys,
  313. DenseMap<Value *, DxilResourceProperties> &valToResPropertiesMap) {
  314. DxilResourceProperties RP;
  315. RP.Class = DXIL::ResourceClass::Invalid;
  316. auto RPIt = valToResPropertiesMap.find(arg);
  317. if (RPIt != valToResPropertiesMap.end()) {
  318. RP = RPIt->second;
  319. } else {
  320. // Must be GEP.
  321. GEPOperator *GEP = cast<GEPOperator>(arg);
  322. // Find RP from GEP.
  323. Value *Ptr = GEP->getPointerOperand();
  324. // When Ptr is array of resource, check if it is another GEP.
  325. while (
  326. dxilutil::IsHLSLResourceType(dxilutil::GetArrayEltTy(Ptr->getType()))) {
  327. if (GEPOperator *ParentGEP = dyn_cast<GEPOperator>(Ptr)) {
  328. GEP = ParentGEP;
  329. Ptr = GEP->getPointerOperand();
  330. } else {
  331. break;
  332. }
  333. }
  334. RPIt = valToResPropertiesMap.find(Ptr);
  335. // When ptr is array of resource, ptr could be in
  336. // valToResPropertiesMap.
  337. if (RPIt != valToResPropertiesMap.end()) {
  338. RP = RPIt->second;
  339. } else {
  340. DxilStructAnnotation *Anno = nullptr;
  341. for (auto gepIt = gep_type_begin(GEP), E = gep_type_end(GEP); gepIt != E;
  342. ++gepIt) {
  343. if (StructType *ST = dyn_cast<StructType>(*gepIt)) {
  344. Anno = typeSys.GetStructAnnotation(ST);
  345. DXASSERT(Anno, "missing type annotation");
  346. unsigned Index =
  347. cast<ConstantInt>(gepIt.getOperand())->getLimitedValue();
  348. DxilFieldAnnotation &fieldAnno = Anno->GetFieldAnnotation(Index);
  349. if (fieldAnno.HasResourceAttribute()) {
  350. MDNode *resAttrib = fieldAnno.GetResourceAttribute();
  351. DxilResourceBase R(DXIL::ResourceClass::Invalid);
  352. HLM.LoadDxilResourceBaseFromMDNode(resAttrib, R);
  353. switch (R.GetClass()) {
  354. case DXIL::ResourceClass::SRV:
  355. case DXIL::ResourceClass::UAV: {
  356. DxilResource Res;
  357. HLM.LoadDxilResourceFromMDNode(resAttrib, Res);
  358. RP = resource_helper::loadFromResourceBase(&Res);
  359. } break;
  360. case DXIL::ResourceClass::Sampler: {
  361. DxilSampler Sampler;
  362. HLM.LoadDxilSamplerFromMDNode(resAttrib, Sampler);
  363. RP = resource_helper::loadFromResourceBase(&Sampler);
  364. } break;
  365. default:
  366. DXASSERT(0, "invalid resource attribute in filed annotation");
  367. break;
  368. }
  369. break;
  370. }
  371. }
  372. }
  373. }
  374. }
  375. DXASSERT(RP.Class != DXIL::ResourceClass::Invalid,
  376. "invalid resource properties");
  377. return RP;
  378. }
  379. void AddOpcodeParamForIntrinsic(
  380. HLModule &HLM, Function *F, unsigned opcode, llvm::Type *HandleTy,
  381. DenseMap<Value *, DxilResourceProperties> &valToResPropertiesMap) {
  382. llvm::Module &M = *HLM.GetModule();
  383. llvm::FunctionType *oldFuncTy = F->getFunctionType();
  384. SmallVector<llvm::Type *, 4> paramTyList;
  385. // Add the opcode param
  386. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  387. paramTyList.emplace_back(opcodeTy);
  388. paramTyList.append(oldFuncTy->param_begin(), oldFuncTy->param_end());
  389. for (unsigned i = 1; i < paramTyList.size(); i++) {
  390. llvm::Type *Ty = paramTyList[i];
  391. if (Ty->isPointerTy()) {
  392. Ty = Ty->getPointerElementType();
  393. if (dxilutil::IsHLSLResourceType(Ty)) {
  394. // Use handle type for resource type.
  395. // This will make sure temp object variable only used by createHandle.
  396. paramTyList[i] = HandleTy;
  397. }
  398. }
  399. }
  400. HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  401. if (group == HLOpcodeGroup::HLSubscript &&
  402. opcode == static_cast<unsigned>(HLSubscriptOpcode::VectorSubscript)) {
  403. llvm::FunctionType *FT = F->getFunctionType();
  404. llvm::Type *VecArgTy = FT->getParamType(0);
  405. llvm::VectorType *VType =
  406. cast<llvm::VectorType>(VecArgTy->getPointerElementType());
  407. llvm::Type *Ty = VType->getElementType();
  408. DXASSERT(Ty->isIntegerTy(), "Only bool could use VectorSubscript");
  409. llvm::IntegerType *ITy = cast<IntegerType>(Ty);
  410. DXASSERT_LOCALVAR(ITy, ITy->getBitWidth() == 1,
  411. "Only bool could use VectorSubscript");
  412. // The return type is i8*.
  413. // Replace all uses with i1*.
  414. ReplaceBoolVectorSubscript(F);
  415. return;
  416. }
  417. bool isDoubleSubscriptFunc =
  418. group == HLOpcodeGroup::HLSubscript &&
  419. opcode == static_cast<unsigned>(HLSubscriptOpcode::DoubleSubscript);
  420. llvm::Type *RetTy = oldFuncTy->getReturnType();
  421. if (isDoubleSubscriptFunc) {
  422. CallInst *doubleSub = cast<CallInst>(*F->user_begin());
  423. // Change currentIdx type into coord type.
  424. auto U = doubleSub->user_begin();
  425. Value *user = *U;
  426. CallInst *secSub = cast<CallInst>(user);
  427. unsigned coordIdx = HLOperandIndex::kSubscriptIndexOpIdx;
  428. // opcode operand not add yet, so the index need -1.
  429. if (GetHLOpcodeGroupByName(secSub->getCalledFunction()) ==
  430. HLOpcodeGroup::NotHL)
  431. coordIdx -= 1;
  432. Value *coord = secSub->getArgOperand(coordIdx);
  433. llvm::Type *coordTy = coord->getType();
  434. paramTyList[HLOperandIndex::kSubscriptIndexOpIdx] = coordTy;
  435. // Add the sampleIdx or mipLevel parameter to the end.
  436. paramTyList.emplace_back(opcodeTy);
  437. // Change return type to be resource ret type.
  438. // opcode operand not add yet, so the index need -1.
  439. Value *objPtr =
  440. doubleSub->getArgOperand(HLOperandIndex::kSubscriptObjectOpIdx - 1);
  441. // Must be a GEP
  442. GEPOperator *objGEP = cast<GEPOperator>(objPtr);
  443. gep_type_iterator GEPIt = gep_type_begin(objGEP), E = gep_type_end(objGEP);
  444. llvm::Type *resTy = nullptr;
  445. while (GEPIt != E) {
  446. if (dxilutil::IsHLSLResourceType(*GEPIt)) {
  447. resTy = *GEPIt;
  448. break;
  449. }
  450. GEPIt++;
  451. }
  452. DXASSERT(resTy, "must find the resource type");
  453. // Change object type to handle type.
  454. paramTyList[HLOperandIndex::kSubscriptObjectOpIdx] = HandleTy;
  455. // Change RetTy into pointer of resource reture type.
  456. RetTy = cast<StructType>(resTy)->getElementType(0)->getPointerTo();
  457. }
  458. llvm::FunctionType *funcTy =
  459. llvm::FunctionType::get(RetTy, paramTyList, oldFuncTy->isVarArg());
  460. Function *opFunc = CreateOpFunction(M, F, funcTy, group, opcode);
  461. StringRef lower = hlsl::GetHLLowerStrategy(F);
  462. if (!lower.empty())
  463. hlsl::SetHLLowerStrategy(opFunc, lower);
  464. DxilTypeSystem &typeSys = HLM.GetTypeSystem();
  465. for (auto user = F->user_begin(); user != F->user_end();) {
  466. // User must be a call.
  467. CallInst *oldCI = cast<CallInst>(*(user++));
  468. SmallVector<Value *, 4> opcodeParamList;
  469. Value *opcodeConst = Constant::getIntegerValue(opcodeTy, APInt(32, opcode));
  470. opcodeParamList.emplace_back(opcodeConst);
  471. opcodeParamList.append(oldCI->arg_operands().begin(),
  472. oldCI->arg_operands().end());
  473. IRBuilder<> Builder(oldCI);
  474. if (isDoubleSubscriptFunc) {
  475. // Change obj to the resource pointer.
  476. Value *objVal = opcodeParamList[HLOperandIndex::kSubscriptObjectOpIdx];
  477. GEPOperator *objGEP = cast<GEPOperator>(objVal);
  478. SmallVector<Value *, 8> IndexList;
  479. IndexList.append(objGEP->idx_begin(), objGEP->idx_end());
  480. Value *lastIndex = IndexList.back();
  481. ConstantInt *constIndex = cast<ConstantInt>(lastIndex);
  482. DXASSERT_LOCALVAR(constIndex, constIndex->getLimitedValue() == 1,
  483. "last index must 1");
  484. // Remove the last index.
  485. IndexList.pop_back();
  486. objVal = objGEP->getPointerOperand();
  487. DxilResourceProperties RP = GetResourcePropsFromIntrinsicObjectArg(
  488. objVal, HLM, typeSys, valToResPropertiesMap);
  489. if (IndexList.size() > 1)
  490. objVal = Builder.CreateInBoundsGEP(objVal, IndexList);
  491. Value *Handle = CreateHandleFromResPtr(objVal, HLM, HandleTy, Builder);
  492. Type *ResTy = objVal->getType()->getPointerElementType();
  493. Handle = CreateAnnotateHandle(HLM, Handle, RP, ResTy, Builder);
  494. // Change obj to the resource pointer.
  495. opcodeParamList[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  496. // Set idx and mipIdx.
  497. Value *mipIdx = opcodeParamList[HLOperandIndex::kSubscriptIndexOpIdx];
  498. auto U = oldCI->user_begin();
  499. Value *user = *U;
  500. CallInst *secSub = cast<CallInst>(user);
  501. unsigned idxOpIndex = HLOperandIndex::kSubscriptIndexOpIdx;
  502. if (GetHLOpcodeGroupByName(secSub->getCalledFunction()) ==
  503. HLOpcodeGroup::NotHL)
  504. idxOpIndex--;
  505. Value *idx = secSub->getArgOperand(idxOpIndex);
  506. DXASSERT(secSub->hasOneUse(), "subscript should only has one use");
  507. // Add the sampleIdx or mipLevel parameter to the end.
  508. opcodeParamList[HLOperandIndex::kSubscriptIndexOpIdx] = idx;
  509. opcodeParamList.emplace_back(mipIdx);
  510. // Insert new call before secSub to make sure idx is ready to use.
  511. Builder.SetInsertPoint(secSub);
  512. }
  513. for (unsigned i = 1; i < opcodeParamList.size(); i++) {
  514. Value *arg = opcodeParamList[i];
  515. llvm::Type *Ty = arg->getType();
  516. if (Ty->isPointerTy()) {
  517. Ty = Ty->getPointerElementType();
  518. if (dxilutil::IsHLSLResourceType(Ty)) {
  519. DxilResourceProperties RP = GetResourcePropsFromIntrinsicObjectArg(
  520. arg, HLM, typeSys, valToResPropertiesMap);
  521. // Use object type directly, not by pointer.
  522. // This will make sure temp object variable only used by ld/st.
  523. if (GEPOperator *argGEP = dyn_cast<GEPOperator>(arg)) {
  524. std::vector<Value *> idxList(argGEP->idx_begin(),
  525. argGEP->idx_end());
  526. // Create instruction to avoid GEPOperator.
  527. GetElementPtrInst *GEP = GetElementPtrInst::CreateInBounds(
  528. argGEP->getPointerOperand(), idxList);
  529. Builder.Insert(GEP);
  530. arg = GEP;
  531. }
  532. llvm::Type *ResTy = arg->getType()->getPointerElementType();
  533. Value *Handle = CreateHandleFromResPtr(arg, HLM, HandleTy, Builder);
  534. Handle = CreateAnnotateHandle(HLM, Handle, RP, ResTy, Builder);
  535. opcodeParamList[i] = Handle;
  536. }
  537. }
  538. }
  539. Value *CI = Builder.CreateCall(opFunc, opcodeParamList);
  540. if (!isDoubleSubscriptFunc) {
  541. // replace new call and delete the old call
  542. oldCI->replaceAllUsesWith(CI);
  543. oldCI->eraseFromParent();
  544. } else {
  545. // For double script.
  546. // Replace single users use with new CI.
  547. auto U = oldCI->user_begin();
  548. Value *user = *U;
  549. CallInst *secSub = cast<CallInst>(user);
  550. secSub->replaceAllUsesWith(CI);
  551. secSub->eraseFromParent();
  552. oldCI->eraseFromParent();
  553. }
  554. }
  555. // delete the function
  556. F->eraseFromParent();
  557. }
  558. void AddOpcodeParamForIntrinsics(
  559. HLModule &HLM, std::vector<std::pair<Function *, unsigned>> &intrinsicMap,
  560. DenseMap<Value *, DxilResourceProperties> &valToResPropertiesMap) {
  561. llvm::Type *HandleTy = HLM.GetOP()->GetHandleType();
  562. for (auto mapIter : intrinsicMap) {
  563. Function *F = mapIter.first;
  564. if (F->user_empty()) {
  565. // delete the function
  566. F->eraseFromParent();
  567. continue;
  568. }
  569. unsigned opcode = mapIter.second;
  570. AddOpcodeParamForIntrinsic(HLM, F, opcode, HandleTy, valToResPropertiesMap);
  571. }
  572. }
  573. }
  574. namespace {
  575. // Returns true a global value is being updated
  576. bool GlobalHasStoreUserRec(Value *V, std::set<Value *> &visited) {
  577. bool isWriteEnabled = false;
  578. if (V && visited.find(V) == visited.end()) {
  579. visited.insert(V);
  580. for (User *U : V->users()) {
  581. if (isa<StoreInst>(U)) {
  582. return true;
  583. } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
  584. Function *F = CI->getCalledFunction();
  585. if (!F->isIntrinsic()) {
  586. HLOpcodeGroup hlGroup = GetHLOpcodeGroup(F);
  587. switch (hlGroup) {
  588. case HLOpcodeGroup::NotHL:
  589. return true;
  590. case HLOpcodeGroup::HLMatLoadStore: {
  591. HLMatLoadStoreOpcode opCode =
  592. static_cast<HLMatLoadStoreOpcode>(hlsl::GetHLOpcode(CI));
  593. if (opCode == HLMatLoadStoreOpcode::ColMatStore ||
  594. opCode == HLMatLoadStoreOpcode::RowMatStore)
  595. return true;
  596. break;
  597. }
  598. case HLOpcodeGroup::HLCast:
  599. case HLOpcodeGroup::HLSubscript:
  600. if (GlobalHasStoreUserRec(U, visited))
  601. return true;
  602. break;
  603. default:
  604. break;
  605. }
  606. }
  607. } else if (isa<GEPOperator>(U) || isa<PHINode>(U) || isa<SelectInst>(U)) {
  608. if (GlobalHasStoreUserRec(U, visited))
  609. return true;
  610. }
  611. }
  612. }
  613. return isWriteEnabled;
  614. }
  615. // Returns true if any of the direct user of a global is a store inst
  616. // otherwise recurse through the remaining users and check if any GEP
  617. // exists and which in turn has a store inst as user.
  618. bool GlobalHasStoreUser(GlobalVariable *GV) {
  619. std::set<Value *> visited;
  620. Value *V = cast<Value>(GV);
  621. return GlobalHasStoreUserRec(V, visited);
  622. }
  623. GlobalVariable *CreateStaticGlobal(llvm::Module *M, GlobalVariable *GV) {
  624. Constant *GC = M->getOrInsertGlobal(GV->getName().str() + ".static.copy",
  625. GV->getType()->getPointerElementType());
  626. GlobalVariable *NGV = cast<GlobalVariable>(GC);
  627. if (GV->hasInitializer()) {
  628. NGV->setInitializer(GV->getInitializer());
  629. } else {
  630. // The copy being static, it should be initialized per llvm rules
  631. NGV->setInitializer(
  632. Constant::getNullValue(GV->getType()->getPointerElementType()));
  633. }
  634. // static global should have internal linkage
  635. NGV->setLinkage(GlobalValue::InternalLinkage);
  636. return NGV;
  637. }
  638. void CreateWriteEnabledStaticGlobals(llvm::Module *M, llvm::Function *EF) {
  639. std::vector<GlobalVariable *> worklist;
  640. for (GlobalVariable &GV : M->globals()) {
  641. if (!GV.isConstant() && GV.getLinkage() != GlobalValue::InternalLinkage &&
  642. // skip globals which are HLSL objects or group shared
  643. !dxilutil::IsHLSLObjectType(GV.getType()->getPointerElementType()) &&
  644. !dxilutil::IsSharedMemoryGlobal(&GV)) {
  645. if (GlobalHasStoreUser(&GV))
  646. worklist.emplace_back(&GV);
  647. // TODO: Ensure that constant globals aren't using initializer
  648. GV.setConstant(true);
  649. }
  650. }
  651. IRBuilder<> Builder(
  652. dxilutil::FirstNonAllocaInsertionPt(&EF->getEntryBlock()));
  653. for (GlobalVariable *GV : worklist) {
  654. GlobalVariable *NGV = CreateStaticGlobal(M, GV);
  655. GV->replaceAllUsesWith(NGV);
  656. // insert memcpy in all entryblocks
  657. uint64_t size = M->getDataLayout().getTypeAllocSize(
  658. GV->getType()->getPointerElementType());
  659. Builder.CreateMemCpy(NGV, GV, size, 1);
  660. }
  661. }
  662. } // namespace
  663. namespace {
  664. void SetEntryFunction(HLModule &HLM, Function *Entry,
  665. clang::CodeGen::CodeGenModule &CGM) {
  666. if (Entry == nullptr) {
  667. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  668. unsigned DiagID = Diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
  669. "cannot find entry function %0");
  670. Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLEntryFunction;
  671. return;
  672. }
  673. HLM.SetEntryFunction(Entry);
  674. }
  675. Function *CloneFunction(Function *Orig, const llvm::Twine &Name,
  676. llvm::Module *llvmModule, hlsl::DxilTypeSystem &TypeSys,
  677. hlsl::DxilTypeSystem &SrcTypeSys) {
  678. Function *F = Function::Create(Orig->getFunctionType(),
  679. GlobalValue::LinkageTypes::ExternalLinkage,
  680. Name, llvmModule);
  681. SmallVector<ReturnInst *, 2> Returns;
  682. ValueToValueMapTy vmap;
  683. // Map params.
  684. auto entryParamIt = F->arg_begin();
  685. for (Argument &param : Orig->args()) {
  686. vmap[&param] = (entryParamIt++);
  687. }
  688. llvm::CloneFunctionInto(F, Orig, vmap, /*ModuleLevelChagnes*/ false, Returns);
  689. TypeSys.CopyFunctionAnnotation(F, Orig, SrcTypeSys);
  690. return F;
  691. }
  692. // Clone shader entry function to be called by other functions.
  693. // The original function will be used as shader entry.
  694. void CloneShaderEntry(Function *ShaderF, StringRef EntryName, HLModule &HLM) {
  695. Function *F = CloneFunction(ShaderF, "", HLM.GetModule(), HLM.GetTypeSystem(),
  696. HLM.GetTypeSystem());
  697. F->takeName(ShaderF);
  698. F->setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  699. // Set to name before mangled.
  700. ShaderF->setName(EntryName);
  701. DxilFunctionAnnotation *annot = HLM.GetFunctionAnnotation(F);
  702. DxilParameterAnnotation &cloneRetAnnot = annot->GetRetTypeAnnotation();
  703. // Clear semantic for cloned one.
  704. cloneRetAnnot.SetSemanticString("");
  705. cloneRetAnnot.SetSemanticIndexVec({});
  706. for (unsigned i = 0; i < annot->GetNumParameters(); i++) {
  707. DxilParameterAnnotation &cloneParamAnnot = annot->GetParameterAnnotation(i);
  708. // Clear semantic for cloned one.
  709. cloneParamAnnot.SetSemanticString("");
  710. cloneParamAnnot.SetSemanticIndexVec({});
  711. }
  712. }
  713. } // namespace
  714. namespace {
  715. bool IsPatchConstantFunction(
  716. const Function *F, StringMap<PatchConstantInfo> &patchConstantFunctionMap) {
  717. DXASSERT_NOMSG(F != nullptr);
  718. for (auto &&p : patchConstantFunctionMap) {
  719. if (p.second.Func == F)
  720. return true;
  721. }
  722. return false;
  723. }
  724. void SetPatchConstantFunctionWithAttr(
  725. const EntryFunctionInfo &EntryFunc,
  726. const clang::HLSLPatchConstantFuncAttr *PatchConstantFuncAttr,
  727. StringMap<PatchConstantInfo> &patchConstantFunctionMap,
  728. std::unordered_map<Function *, std::unique_ptr<DxilFunctionProps>>
  729. &patchConstantFunctionPropsMap,
  730. HLModule &HLM, clang::CodeGen::CodeGenModule &CGM) {
  731. StringRef funcName = PatchConstantFuncAttr->getFunctionName();
  732. auto Entry = patchConstantFunctionMap.find(funcName);
  733. if (Entry == patchConstantFunctionMap.end()) {
  734. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  735. unsigned DiagID = Diags.getCustomDiagID(
  736. clang::DiagnosticsEngine::Error, "Cannot find patchconstantfunc %0.");
  737. Diags.Report(PatchConstantFuncAttr->getLocation(), DiagID) << funcName;
  738. return;
  739. }
  740. if (Entry->second.NumOverloads != 1) {
  741. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  742. unsigned DiagID =
  743. Diags.getCustomDiagID(clang::DiagnosticsEngine::Warning,
  744. "Multiple overloads of patchconstantfunc %0.");
  745. unsigned NoteID = Diags.getCustomDiagID(clang::DiagnosticsEngine::Note,
  746. "This overload was selected.");
  747. Diags.Report(PatchConstantFuncAttr->getLocation(), DiagID) << funcName;
  748. Diags.Report(Entry->second.SL, NoteID);
  749. }
  750. Function *patchConstFunc = Entry->second.Func;
  751. DXASSERT(
  752. HLM.HasDxilFunctionProps(EntryFunc.Func),
  753. " else AddHLSLFunctionInfo did not save the dxil function props for the "
  754. "HS entry.");
  755. DxilFunctionProps *HSProps = &HLM.GetDxilFunctionProps(EntryFunc.Func);
  756. HLM.SetPatchConstantFunctionForHS(EntryFunc.Func, patchConstFunc);
  757. DXASSERT_NOMSG(patchConstantFunctionPropsMap.count(patchConstFunc));
  758. // Check no inout parameter for patch constant function.
  759. DxilFunctionAnnotation *patchConstFuncAnnotation =
  760. HLM.GetFunctionAnnotation(patchConstFunc);
  761. for (unsigned i = 0; i < patchConstFuncAnnotation->GetNumParameters(); i++) {
  762. if (patchConstFuncAnnotation->GetParameterAnnotation(i)
  763. .GetParamInputQual() == DxilParamInputQual::Inout) {
  764. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  765. unsigned DiagID = Diags.getCustomDiagID(
  766. clang::DiagnosticsEngine::Error,
  767. "Patch Constant function %0 should not have inout param.");
  768. Diags.Report(Entry->second.SL, DiagID) << funcName;
  769. }
  770. }
  771. // Input/Output control point validation.
  772. if (patchConstantFunctionPropsMap.count(patchConstFunc)) {
  773. const DxilFunctionProps &patchProps =
  774. *patchConstantFunctionPropsMap[patchConstFunc];
  775. if (patchProps.ShaderProps.HS.inputControlPoints != 0 &&
  776. patchProps.ShaderProps.HS.inputControlPoints !=
  777. HSProps->ShaderProps.HS.inputControlPoints) {
  778. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  779. unsigned DiagID =
  780. Diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
  781. "Patch constant function's input patch input "
  782. "should have %0 elements, but has %1.");
  783. Diags.Report(Entry->second.SL, DiagID)
  784. << HSProps->ShaderProps.HS.inputControlPoints
  785. << patchProps.ShaderProps.HS.inputControlPoints;
  786. }
  787. if (patchProps.ShaderProps.HS.outputControlPoints != 0 &&
  788. patchProps.ShaderProps.HS.outputControlPoints !=
  789. HSProps->ShaderProps.HS.outputControlPoints) {
  790. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  791. unsigned DiagID =
  792. Diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
  793. "Patch constant function's output patch input "
  794. "should have %0 elements, but has %1.");
  795. Diags.Report(Entry->second.SL, DiagID)
  796. << HSProps->ShaderProps.HS.outputControlPoints
  797. << patchProps.ShaderProps.HS.outputControlPoints;
  798. }
  799. }
  800. }
  801. void SetPatchConstantFunction(
  802. const EntryFunctionInfo &EntryFunc,
  803. std::unordered_map<Function *, const clang::HLSLPatchConstantFuncAttr *>
  804. &HSEntryPatchConstantFuncAttr,
  805. StringMap<PatchConstantInfo> &patchConstantFunctionMap,
  806. std::unordered_map<Function *, std::unique_ptr<DxilFunctionProps>>
  807. &patchConstantFunctionPropsMap,
  808. HLModule &HLM, clang::CodeGen::CodeGenModule &CGM) {
  809. auto AttrsIter = HSEntryPatchConstantFuncAttr.find(EntryFunc.Func);
  810. DXASSERT(AttrsIter != HSEntryPatchConstantFuncAttr.end(),
  811. "we have checked this in AddHLSLFunctionInfo()");
  812. SetPatchConstantFunctionWithAttr(EntryFunc, AttrsIter->second,
  813. patchConstantFunctionMap,
  814. patchConstantFunctionPropsMap, HLM, CGM);
  815. }
  816. } // namespace
  817. namespace {
  818. // For case like:
  819. // cbuffer A {
  820. // float a;
  821. // int b;
  822. //}
  823. //
  824. // const static struct {
  825. // float a;
  826. // int b;
  827. //} ST = { a, b };
  828. // Replace user of ST with a and b.
  829. bool ReplaceConstStaticGlobalUser(GEPOperator *GEP,
  830. std::vector<Constant *> &InitList,
  831. IRBuilder<> &Builder) {
  832. if (GEP->getNumIndices() < 2) {
  833. // Don't use sub element.
  834. return false;
  835. }
  836. SmallVector<Value *, 4> idxList;
  837. auto iter = GEP->idx_begin();
  838. idxList.emplace_back(*(iter++));
  839. ConstantInt *subIdx = dyn_cast<ConstantInt>(*(iter++));
  840. DXASSERT(subIdx, "else dynamic indexing on struct field");
  841. unsigned subIdxImm = subIdx->getLimitedValue();
  842. DXASSERT(subIdxImm < InitList.size(), "else struct index out of bound");
  843. Constant *subPtr = InitList[subIdxImm];
  844. // Move every idx to idxList except idx for InitList.
  845. while (iter != GEP->idx_end()) {
  846. idxList.emplace_back(*(iter++));
  847. }
  848. Value *NewGEP = Builder.CreateGEP(subPtr, idxList);
  849. GEP->replaceAllUsesWith(NewGEP);
  850. return true;
  851. }
  852. } // namespace
  853. namespace CGHLSLMSHelper {
  854. void ReplaceConstStaticGlobals(
  855. std::unordered_map<GlobalVariable *, std::vector<Constant *>>
  856. &staticConstGlobalInitListMap,
  857. std::unordered_map<GlobalVariable *, Function *>
  858. &staticConstGlobalCtorMap) {
  859. for (auto &iter : staticConstGlobalInitListMap) {
  860. GlobalVariable *GV = iter.first;
  861. std::vector<Constant *> &InitList = iter.second;
  862. LLVMContext &Ctx = GV->getContext();
  863. // Do the replace.
  864. bool bPass = true;
  865. for (User *U : GV->users()) {
  866. IRBuilder<> Builder(Ctx);
  867. if (GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(U)) {
  868. Builder.SetInsertPoint(GEPInst);
  869. bPass &= ReplaceConstStaticGlobalUser(cast<GEPOperator>(GEPInst),
  870. InitList, Builder);
  871. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  872. bPass &= ReplaceConstStaticGlobalUser(GEP, InitList, Builder);
  873. } else {
  874. DXASSERT(false, "invalid user of const static global");
  875. }
  876. }
  877. // Clear the Ctor which is useless now.
  878. if (bPass) {
  879. Function *Ctor = staticConstGlobalCtorMap[GV];
  880. Ctor->getBasicBlockList().clear();
  881. BasicBlock *Entry = BasicBlock::Create(Ctx, "", Ctor);
  882. IRBuilder<> Builder(Entry);
  883. Builder.CreateRetVoid();
  884. }
  885. }
  886. }
  887. }
  888. namespace {
  889. Value *CastLdValue(Value *Ptr, llvm::Type *FromTy, llvm::Type *ToTy,
  890. IRBuilder<> &Builder) {
  891. if (ToTy->isVectorTy()) {
  892. unsigned vecSize = ToTy->getVectorNumElements();
  893. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  894. Value *V = Builder.CreateLoad(Ptr);
  895. // ScalarToVec1Splat
  896. // Change scalar into vec1.
  897. Value *Vec1 = UndefValue::get(ToTy);
  898. return Builder.CreateInsertElement(Vec1, V, (uint64_t)0);
  899. } else if (vecSize == 1 && FromTy->isIntegerTy() &&
  900. ToTy->getVectorElementType()->isIntegerTy(1)) {
  901. // load(bitcast i32* to <1 x i1>*)
  902. // Rewrite to
  903. // insertelement(icmp ne (load i32*), 0)
  904. Value *IntV = Builder.CreateLoad(Ptr);
  905. Value *BoolV = Builder.CreateICmpNE(
  906. IntV, ConstantInt::get(IntV->getType(), 0), "tobool");
  907. Value *Vec1 = UndefValue::get(ToTy);
  908. return Builder.CreateInsertElement(Vec1, BoolV, (uint64_t)0);
  909. } else if (FromTy->isVectorTy() && vecSize == 1) {
  910. Value *V = Builder.CreateLoad(Ptr);
  911. // VectorTrunc
  912. // Change vector into vec1.
  913. int mask[] = {0};
  914. return Builder.CreateShuffleVector(V, V, mask);
  915. } else if (FromTy->isArrayTy()) {
  916. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  917. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  918. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  919. // ArrayToVector.
  920. Value *NewLd = UndefValue::get(ToTy);
  921. Value *zeroIdx = Builder.getInt32(0);
  922. for (unsigned i = 0; i < vecSize; i++) {
  923. Value *GEP =
  924. Builder.CreateInBoundsGEP(Ptr, {zeroIdx, Builder.getInt32(i)});
  925. Value *Elt = Builder.CreateLoad(GEP);
  926. NewLd = Builder.CreateInsertElement(NewLd, Elt, i);
  927. }
  928. return NewLd;
  929. }
  930. }
  931. } else if (FromTy == Builder.getInt1Ty()) {
  932. Value *V = Builder.CreateLoad(Ptr);
  933. // BoolCast
  934. DXASSERT_NOMSG(ToTy->isIntegerTy());
  935. return Builder.CreateZExt(V, ToTy);
  936. }
  937. return nullptr;
  938. }
  939. Value *CastStValue(Value *Ptr, Value *V, llvm::Type *FromTy, llvm::Type *ToTy,
  940. IRBuilder<> &Builder) {
  941. if (ToTy->isVectorTy()) {
  942. unsigned vecSize = ToTy->getVectorNumElements();
  943. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  944. // ScalarToVec1Splat
  945. // Change vec1 back to scalar.
  946. Value *Elt = Builder.CreateExtractElement(V, (uint64_t)0);
  947. return Elt;
  948. } else if (FromTy->isVectorTy() && vecSize == 1) {
  949. // VectorTrunc
  950. // Change vec1 into vector.
  951. // Should not happen.
  952. // Reported error at Sema::ImpCastExprToType.
  953. DXASSERT_NOMSG(0);
  954. } else if (FromTy->isArrayTy()) {
  955. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  956. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  957. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  958. // ArrayToVector.
  959. Value *zeroIdx = Builder.getInt32(0);
  960. for (unsigned i = 0; i < vecSize; i++) {
  961. Value *Elt = Builder.CreateExtractElement(V, i);
  962. Value *GEP =
  963. Builder.CreateInBoundsGEP(Ptr, {zeroIdx, Builder.getInt32(i)});
  964. Builder.CreateStore(Elt, GEP);
  965. }
  966. // The store already done.
  967. // Return null to ignore use of the return value.
  968. return nullptr;
  969. }
  970. }
  971. } else if (FromTy == Builder.getInt1Ty()) {
  972. // BoolCast
  973. // Change i1 to ToTy.
  974. DXASSERT_NOMSG(ToTy->isIntegerTy());
  975. Value *CastV = Builder.CreateICmpNE(V, ConstantInt::get(V->getType(), 0));
  976. return CastV;
  977. }
  978. return nullptr;
  979. }
  980. bool SimplifyBitCastLoad(LoadInst *LI, llvm::Type *FromTy, llvm::Type *ToTy,
  981. Value *Ptr) {
  982. IRBuilder<> Builder(LI);
  983. // Cast FromLd to ToTy.
  984. Value *CastV = CastLdValue(Ptr, FromTy, ToTy, Builder);
  985. if (CastV) {
  986. LI->replaceAllUsesWith(CastV);
  987. return true;
  988. } else {
  989. return false;
  990. }
  991. }
  992. bool SimplifyBitCastStore(StoreInst *SI, llvm::Type *FromTy, llvm::Type *ToTy,
  993. Value *Ptr) {
  994. IRBuilder<> Builder(SI);
  995. Value *V = SI->getValueOperand();
  996. // Cast Val to FromTy.
  997. Value *CastV = CastStValue(Ptr, V, FromTy, ToTy, Builder);
  998. if (CastV) {
  999. Builder.CreateStore(CastV, Ptr);
  1000. return true;
  1001. } else {
  1002. return false;
  1003. }
  1004. }
  1005. bool SimplifyBitCastGEP(GEPOperator *GEP, llvm::Type *FromTy, llvm::Type *ToTy,
  1006. Value *Ptr) {
  1007. if (ToTy->isVectorTy()) {
  1008. unsigned vecSize = ToTy->getVectorNumElements();
  1009. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  1010. // ScalarToVec1Splat
  1011. GEP->replaceAllUsesWith(Ptr);
  1012. return true;
  1013. } else if (FromTy->isVectorTy() && vecSize == 1) {
  1014. // VectorTrunc
  1015. DXASSERT_NOMSG(
  1016. !isa<llvm::VectorType>(GEP->getType()->getPointerElementType()));
  1017. IRBuilder<> Builder(FromTy->getContext());
  1018. if (Instruction *I = dyn_cast<Instruction>(GEP))
  1019. Builder.SetInsertPoint(I);
  1020. std::vector<Value *> idxList(GEP->idx_begin(), GEP->idx_end());
  1021. Value *NewGEP = Builder.CreateInBoundsGEP(Ptr, idxList);
  1022. GEP->replaceAllUsesWith(NewGEP);
  1023. return true;
  1024. } else if (FromTy->isArrayTy()) {
  1025. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  1026. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  1027. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  1028. // ArrayToVector.
  1029. }
  1030. }
  1031. } else if (FromTy == llvm::Type::getInt1Ty(FromTy->getContext())) {
  1032. // BoolCast
  1033. }
  1034. return false;
  1035. }
  1036. typedef SmallPtrSet<Instruction *, 4> SmallInstSet;
  1037. void SimplifyBitCast(BitCastOperator *BC, SmallInstSet &deadInsts) {
  1038. Value *Ptr = BC->getOperand(0);
  1039. llvm::Type *FromTy = Ptr->getType();
  1040. llvm::Type *ToTy = BC->getType();
  1041. if (!FromTy->isPointerTy() || !ToTy->isPointerTy())
  1042. return;
  1043. FromTy = FromTy->getPointerElementType();
  1044. ToTy = ToTy->getPointerElementType();
  1045. // Take care case like %2 = bitcast %struct.T* %1 to <1 x float>*.
  1046. bool GEPCreated = false;
  1047. if (FromTy->isStructTy()) {
  1048. IRBuilder<> Builder(FromTy->getContext());
  1049. if (Instruction *I = dyn_cast<Instruction>(BC))
  1050. Builder.SetInsertPoint(I);
  1051. Value *zeroIdx = Builder.getInt32(0);
  1052. unsigned nestLevel = 1;
  1053. while (llvm::StructType *ST = dyn_cast<llvm::StructType>(FromTy)) {
  1054. if (ST->getNumElements() == 0)
  1055. break;
  1056. FromTy = ST->getElementType(0);
  1057. nestLevel++;
  1058. }
  1059. std::vector<Value *> idxList(nestLevel, zeroIdx);
  1060. Ptr = Builder.CreateGEP(Ptr, idxList);
  1061. GEPCreated = true;
  1062. }
  1063. for (User *U : BC->users()) {
  1064. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  1065. if (SimplifyBitCastLoad(LI, FromTy, ToTy, Ptr)) {
  1066. LI->dropAllReferences();
  1067. deadInsts.insert(LI);
  1068. }
  1069. } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  1070. if (SimplifyBitCastStore(SI, FromTy, ToTy, Ptr)) {
  1071. SI->dropAllReferences();
  1072. deadInsts.insert(SI);
  1073. }
  1074. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  1075. if (SimplifyBitCastGEP(GEP, FromTy, ToTy, Ptr))
  1076. if (Instruction *I = dyn_cast<Instruction>(GEP)) {
  1077. I->dropAllReferences();
  1078. deadInsts.insert(I);
  1079. }
  1080. } else if (dyn_cast<CallInst>(U)) {
  1081. // Skip function call.
  1082. } else if (dyn_cast<BitCastInst>(U)) {
  1083. // Skip bitcast.
  1084. } else if (dyn_cast<AddrSpaceCastInst>(U)) {
  1085. // Skip addrspacecast.
  1086. } else {
  1087. DXASSERT(0, "not support yet");
  1088. }
  1089. }
  1090. // We created a GEP instruction but didn't end up consuming it, so delete it.
  1091. if (GEPCreated && Ptr->use_empty()) {
  1092. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
  1093. GEP->eraseFromParent();
  1094. else
  1095. cast<Constant>(Ptr)->destroyConstant();
  1096. }
  1097. }
  1098. typedef float(__cdecl *FloatUnaryEvalFuncType)(float);
  1099. typedef double(__cdecl *DoubleUnaryEvalFuncType)(double);
  1100. typedef APInt(__cdecl *IntBinaryEvalFuncType)(const APInt &, const APInt &);
  1101. typedef float(__cdecl *FloatBinaryEvalFuncType)(float, float);
  1102. typedef double(__cdecl *DoubleBinaryEvalFuncType)(double, double);
  1103. Value *EvalUnaryIntrinsic(ConstantFP *fpV, FloatUnaryEvalFuncType floatEvalFunc,
  1104. DoubleUnaryEvalFuncType doubleEvalFunc) {
  1105. llvm::Type *Ty = fpV->getType();
  1106. Value *Result = nullptr;
  1107. if (Ty->isDoubleTy()) {
  1108. double dV = fpV->getValueAPF().convertToDouble();
  1109. Value *dResult = ConstantFP::get(Ty, doubleEvalFunc(dV));
  1110. Result = dResult;
  1111. } else {
  1112. DXASSERT_NOMSG(Ty->isFloatTy());
  1113. float fV = fpV->getValueAPF().convertToFloat();
  1114. Value *dResult = ConstantFP::get(Ty, floatEvalFunc(fV));
  1115. Result = dResult;
  1116. }
  1117. return Result;
  1118. }
  1119. Value *EvalBinaryIntrinsic(Constant *cV0, Constant *cV1,
  1120. FloatBinaryEvalFuncType floatEvalFunc,
  1121. DoubleBinaryEvalFuncType doubleEvalFunc,
  1122. IntBinaryEvalFuncType intEvalFunc) {
  1123. llvm::Type *Ty = cV0->getType();
  1124. Value *Result = nullptr;
  1125. if (Ty->isDoubleTy()) {
  1126. ConstantFP *fpV0 = cast<ConstantFP>(cV0);
  1127. ConstantFP *fpV1 = cast<ConstantFP>(cV1);
  1128. double dV0 = fpV0->getValueAPF().convertToDouble();
  1129. double dV1 = fpV1->getValueAPF().convertToDouble();
  1130. Value *dResult = ConstantFP::get(Ty, doubleEvalFunc(dV0, dV1));
  1131. Result = dResult;
  1132. } else if (Ty->isFloatTy()) {
  1133. ConstantFP *fpV0 = cast<ConstantFP>(cV0);
  1134. ConstantFP *fpV1 = cast<ConstantFP>(cV1);
  1135. float fV0 = fpV0->getValueAPF().convertToFloat();
  1136. float fV1 = fpV1->getValueAPF().convertToFloat();
  1137. Value *dResult = ConstantFP::get(Ty, floatEvalFunc(fV0, fV1));
  1138. Result = dResult;
  1139. } else {
  1140. DXASSERT_NOMSG(Ty->isIntegerTy());
  1141. DXASSERT_NOMSG(intEvalFunc);
  1142. ConstantInt *ciV0 = cast<ConstantInt>(cV0);
  1143. ConstantInt *ciV1 = cast<ConstantInt>(cV1);
  1144. const APInt &iV0 = ciV0->getValue();
  1145. const APInt &iV1 = ciV1->getValue();
  1146. Value *dResult = ConstantInt::get(Ty, intEvalFunc(iV0, iV1));
  1147. Result = dResult;
  1148. }
  1149. return Result;
  1150. }
  1151. Value *EvalUnaryIntrinsic(CallInst *CI, FloatUnaryEvalFuncType floatEvalFunc,
  1152. DoubleUnaryEvalFuncType doubleEvalFunc) {
  1153. Value *V = CI->getArgOperand(0);
  1154. llvm::Type *Ty = CI->getType();
  1155. Value *Result = nullptr;
  1156. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  1157. Result = UndefValue::get(Ty);
  1158. Constant *CV = cast<Constant>(V);
  1159. IRBuilder<> Builder(CI);
  1160. for (unsigned i = 0; i < VT->getNumElements(); i++) {
  1161. ConstantFP *fpV = cast<ConstantFP>(CV->getAggregateElement(i));
  1162. Value *EltResult = EvalUnaryIntrinsic(fpV, floatEvalFunc, doubleEvalFunc);
  1163. Result = Builder.CreateInsertElement(Result, EltResult, i);
  1164. }
  1165. } else {
  1166. ConstantFP *fpV = cast<ConstantFP>(V);
  1167. Result = EvalUnaryIntrinsic(fpV, floatEvalFunc, doubleEvalFunc);
  1168. }
  1169. CI->replaceAllUsesWith(Result);
  1170. CI->eraseFromParent();
  1171. return Result;
  1172. }
  1173. Value *EvalBinaryIntrinsic(CallInst *CI, FloatBinaryEvalFuncType floatEvalFunc,
  1174. DoubleBinaryEvalFuncType doubleEvalFunc,
  1175. IntBinaryEvalFuncType intEvalFunc = nullptr) {
  1176. Value *V0 = CI->getArgOperand(0);
  1177. Value *V1 = CI->getArgOperand(1);
  1178. llvm::Type *Ty = CI->getType();
  1179. Value *Result = nullptr;
  1180. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  1181. Result = UndefValue::get(Ty);
  1182. Constant *CV0 = cast<Constant>(V0);
  1183. Constant *CV1 = cast<Constant>(V1);
  1184. IRBuilder<> Builder(CI);
  1185. for (unsigned i = 0; i < VT->getNumElements(); i++) {
  1186. Constant *cV0 = cast<Constant>(CV0->getAggregateElement(i));
  1187. Constant *cV1 = cast<Constant>(CV1->getAggregateElement(i));
  1188. Value *EltResult = EvalBinaryIntrinsic(cV0, cV1, floatEvalFunc,
  1189. doubleEvalFunc, intEvalFunc);
  1190. Result = Builder.CreateInsertElement(Result, EltResult, i);
  1191. }
  1192. } else {
  1193. Constant *cV0 = cast<Constant>(V0);
  1194. Constant *cV1 = cast<Constant>(V1);
  1195. Result = EvalBinaryIntrinsic(cV0, cV1, floatEvalFunc, doubleEvalFunc,
  1196. intEvalFunc);
  1197. }
  1198. CI->replaceAllUsesWith(Result);
  1199. CI->eraseFromParent();
  1200. return Result;
  1201. CI->eraseFromParent();
  1202. return Result;
  1203. }
  1204. void SimpleTransformForHLDXIRInst(Instruction *I, SmallInstSet &deadInsts) {
  1205. unsigned opcode = I->getOpcode();
  1206. switch (opcode) {
  1207. case Instruction::BitCast: {
  1208. BitCastOperator *BCI = cast<BitCastOperator>(I);
  1209. SimplifyBitCast(BCI, deadInsts);
  1210. } break;
  1211. case Instruction::Load: {
  1212. LoadInst *ldInst = cast<LoadInst>(I);
  1213. DXASSERT(!HLMatrixType::isa(ldInst->getType()),
  1214. "matrix load should use HL LdStMatrix");
  1215. Value *Ptr = ldInst->getPointerOperand();
  1216. if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(Ptr)) {
  1217. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(CE)) {
  1218. SimplifyBitCast(BCO, deadInsts);
  1219. }
  1220. }
  1221. } break;
  1222. case Instruction::Store: {
  1223. StoreInst *stInst = cast<StoreInst>(I);
  1224. Value *V = stInst->getValueOperand();
  1225. DXASSERT_LOCALVAR(V, !HLMatrixType::isa(V->getType()),
  1226. "matrix store should use HL LdStMatrix");
  1227. Value *Ptr = stInst->getPointerOperand();
  1228. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
  1229. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(CE)) {
  1230. SimplifyBitCast(BCO, deadInsts);
  1231. }
  1232. }
  1233. } break;
  1234. case Instruction::LShr:
  1235. case Instruction::AShr:
  1236. case Instruction::Shl: {
  1237. llvm::BinaryOperator *BO = cast<llvm::BinaryOperator>(I);
  1238. Value *op2 = BO->getOperand(1);
  1239. IntegerType *Ty = cast<IntegerType>(BO->getType()->getScalarType());
  1240. unsigned bitWidth = Ty->getBitWidth();
  1241. // Clamp op2 to 0 ~ bitWidth-1
  1242. if (ConstantInt *cOp2 = dyn_cast<ConstantInt>(op2)) {
  1243. unsigned iOp2 = cOp2->getLimitedValue();
  1244. unsigned clampedOp2 = iOp2 & (bitWidth - 1);
  1245. if (iOp2 != clampedOp2) {
  1246. BO->setOperand(1, ConstantInt::get(op2->getType(), clampedOp2));
  1247. }
  1248. } else {
  1249. Value *mask = ConstantInt::get(op2->getType(), bitWidth - 1);
  1250. IRBuilder<> Builder(I);
  1251. op2 = Builder.CreateAnd(op2, mask);
  1252. BO->setOperand(1, op2);
  1253. }
  1254. } break;
  1255. }
  1256. }
  1257. } // namespace
  1258. namespace CGHLSLMSHelper {
  1259. Value *TryEvalIntrinsic(CallInst *CI, IntrinsicOp intriOp) {
  1260. switch (intriOp) {
  1261. case IntrinsicOp::IOP_tan: {
  1262. return EvalUnaryIntrinsic(CI, tanf, tan);
  1263. } break;
  1264. case IntrinsicOp::IOP_tanh: {
  1265. return EvalUnaryIntrinsic(CI, tanhf, tanh);
  1266. } break;
  1267. case IntrinsicOp::IOP_sin: {
  1268. return EvalUnaryIntrinsic(CI, sinf, sin);
  1269. } break;
  1270. case IntrinsicOp::IOP_sinh: {
  1271. return EvalUnaryIntrinsic(CI, sinhf, sinh);
  1272. } break;
  1273. case IntrinsicOp::IOP_cos: {
  1274. return EvalUnaryIntrinsic(CI, cosf, cos);
  1275. } break;
  1276. case IntrinsicOp::IOP_cosh: {
  1277. return EvalUnaryIntrinsic(CI, coshf, cosh);
  1278. } break;
  1279. case IntrinsicOp::IOP_asin: {
  1280. return EvalUnaryIntrinsic(CI, asinf, asin);
  1281. } break;
  1282. case IntrinsicOp::IOP_acos: {
  1283. return EvalUnaryIntrinsic(CI, acosf, acos);
  1284. } break;
  1285. case IntrinsicOp::IOP_atan: {
  1286. return EvalUnaryIntrinsic(CI, atanf, atan);
  1287. } break;
  1288. case IntrinsicOp::IOP_atan2: {
  1289. Value *V0 = CI->getArgOperand(0);
  1290. ConstantFP *fpV0 = cast<ConstantFP>(V0);
  1291. Value *V1 = CI->getArgOperand(1);
  1292. ConstantFP *fpV1 = cast<ConstantFP>(V1);
  1293. llvm::Type *Ty = CI->getType();
  1294. Value *Result = nullptr;
  1295. if (Ty->isDoubleTy()) {
  1296. double dV0 = fpV0->getValueAPF().convertToDouble();
  1297. double dV1 = fpV1->getValueAPF().convertToDouble();
  1298. Value *atanV = ConstantFP::get(CI->getType(), atan2(dV0, dV1));
  1299. CI->replaceAllUsesWith(atanV);
  1300. Result = atanV;
  1301. } else {
  1302. DXASSERT_NOMSG(Ty->isFloatTy());
  1303. float fV0 = fpV0->getValueAPF().convertToFloat();
  1304. float fV1 = fpV1->getValueAPF().convertToFloat();
  1305. Value *atanV = ConstantFP::get(CI->getType(), atan2f(fV0, fV1));
  1306. CI->replaceAllUsesWith(atanV);
  1307. Result = atanV;
  1308. }
  1309. CI->eraseFromParent();
  1310. return Result;
  1311. } break;
  1312. case IntrinsicOp::IOP_sqrt: {
  1313. return EvalUnaryIntrinsic(CI, sqrtf, sqrt);
  1314. } break;
  1315. case IntrinsicOp::IOP_rsqrt: {
  1316. auto rsqrtF = [](float v) -> float { return 1.0 / sqrtf(v); };
  1317. auto rsqrtD = [](double v) -> double { return 1.0 / sqrt(v); };
  1318. return EvalUnaryIntrinsic(CI, rsqrtF, rsqrtD);
  1319. } break;
  1320. case IntrinsicOp::IOP_exp: {
  1321. return EvalUnaryIntrinsic(CI, expf, exp);
  1322. } break;
  1323. case IntrinsicOp::IOP_exp2: {
  1324. return EvalUnaryIntrinsic(CI, exp2f, exp2);
  1325. } break;
  1326. case IntrinsicOp::IOP_log: {
  1327. return EvalUnaryIntrinsic(CI, logf, log);
  1328. } break;
  1329. case IntrinsicOp::IOP_log10: {
  1330. return EvalUnaryIntrinsic(CI, log10f, log10);
  1331. } break;
  1332. case IntrinsicOp::IOP_log2: {
  1333. return EvalUnaryIntrinsic(CI, log2f, log2);
  1334. } break;
  1335. case IntrinsicOp::IOP_pow: {
  1336. return EvalBinaryIntrinsic(CI, powf, pow);
  1337. } break;
  1338. case IntrinsicOp::IOP_max: {
  1339. auto maxF = [](float a, float b) -> float { return a > b ? a : b; };
  1340. auto maxD = [](double a, double b) -> double { return a > b ? a : b; };
  1341. auto imaxI = [](const APInt &a, const APInt &b) -> APInt {
  1342. return a.sgt(b) ? a : b;
  1343. };
  1344. return EvalBinaryIntrinsic(CI, maxF, maxD, imaxI);
  1345. } break;
  1346. case IntrinsicOp::IOP_min: {
  1347. auto minF = [](float a, float b) -> float { return a < b ? a : b; };
  1348. auto minD = [](double a, double b) -> double { return a < b ? a : b; };
  1349. auto iminI = [](const APInt &a, const APInt &b) -> APInt {
  1350. return a.slt(b) ? a : b;
  1351. };
  1352. return EvalBinaryIntrinsic(CI, minF, minD, iminI);
  1353. } break;
  1354. case IntrinsicOp::IOP_umax: {
  1355. DXASSERT_NOMSG(
  1356. CI->getArgOperand(0)->getType()->getScalarType()->isIntegerTy());
  1357. auto umaxI = [](const APInt &a, const APInt &b) -> APInt {
  1358. return a.ugt(b) ? a : b;
  1359. };
  1360. return EvalBinaryIntrinsic(CI, nullptr, nullptr, umaxI);
  1361. } break;
  1362. case IntrinsicOp::IOP_umin: {
  1363. DXASSERT_NOMSG(
  1364. CI->getArgOperand(0)->getType()->getScalarType()->isIntegerTy());
  1365. auto uminI = [](const APInt &a, const APInt &b) -> APInt {
  1366. return a.ult(b) ? a : b;
  1367. };
  1368. return EvalBinaryIntrinsic(CI, nullptr, nullptr, uminI);
  1369. } break;
  1370. case IntrinsicOp::IOP_rcp: {
  1371. auto rcpF = [](float v) -> float { return 1.0 / v; };
  1372. auto rcpD = [](double v) -> double { return 1.0 / v; };
  1373. return EvalUnaryIntrinsic(CI, rcpF, rcpD);
  1374. } break;
  1375. case IntrinsicOp::IOP_ceil: {
  1376. return EvalUnaryIntrinsic(CI, ceilf, ceil);
  1377. } break;
  1378. case IntrinsicOp::IOP_floor: {
  1379. return EvalUnaryIntrinsic(CI, floorf, floor);
  1380. } break;
  1381. case IntrinsicOp::IOP_round: {
  1382. return EvalUnaryIntrinsic(CI, roundf, round);
  1383. } break;
  1384. case IntrinsicOp::IOP_trunc: {
  1385. return EvalUnaryIntrinsic(CI, truncf, trunc);
  1386. } break;
  1387. case IntrinsicOp::IOP_frac: {
  1388. auto fracF = [](float v) -> float { return v - floor(v); };
  1389. auto fracD = [](double v) -> double { return v - floor(v); };
  1390. return EvalUnaryIntrinsic(CI, fracF, fracD);
  1391. } break;
  1392. case IntrinsicOp::IOP_isnan: {
  1393. Value *V = CI->getArgOperand(0);
  1394. ConstantFP *fV = cast<ConstantFP>(V);
  1395. bool isNan = fV->getValueAPF().isNaN();
  1396. Constant *cNan = ConstantInt::get(CI->getType(), isNan ? 1 : 0);
  1397. CI->replaceAllUsesWith(cNan);
  1398. CI->eraseFromParent();
  1399. return cNan;
  1400. } break;
  1401. default:
  1402. return nullptr;
  1403. }
  1404. }
  1405. // Do simple transform to make later lower pass easier.
  1406. void SimpleTransformForHLDXIR(llvm::Module *pM) {
  1407. SmallInstSet deadInsts;
  1408. for (Function &F : pM->functions()) {
  1409. for (BasicBlock &BB : F.getBasicBlockList()) {
  1410. for (BasicBlock::iterator Iter = BB.begin(); Iter != BB.end();) {
  1411. Instruction *I = (Iter++);
  1412. if (deadInsts.count(I))
  1413. continue; // Skip dead instructions
  1414. SimpleTransformForHLDXIRInst(I, deadInsts);
  1415. }
  1416. }
  1417. }
  1418. for (Instruction *I : deadInsts)
  1419. I->dropAllReferences();
  1420. for (Instruction *I : deadInsts)
  1421. I->eraseFromParent();
  1422. deadInsts.clear();
  1423. for (GlobalVariable &GV : pM->globals()) {
  1424. if (dxilutil::IsStaticGlobal(&GV)) {
  1425. for (User *U : GV.users()) {
  1426. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(U)) {
  1427. SimplifyBitCast(BCO, deadInsts);
  1428. }
  1429. }
  1430. }
  1431. }
  1432. for (Instruction *I : deadInsts)
  1433. I->dropAllReferences();
  1434. for (Instruction *I : deadInsts)
  1435. I->eraseFromParent();
  1436. }
  1437. } // namespace CGHLSLMSHelper
  1438. namespace {
  1439. unsigned RoundToAlign(unsigned num, unsigned mod) {
  1440. // round num to next highest mod
  1441. if (mod != 0)
  1442. return mod * ((num + mod - 1) / mod);
  1443. return num;
  1444. }
  1445. // Here the size is CB size.
  1446. // Offset still needs to be aligned based on type since this
  1447. // is the legacy cbuffer global path.
  1448. unsigned AlignCBufferOffset(unsigned offset, unsigned size, llvm::Type *Ty,
  1449. bool bRowMajor) {
  1450. DXASSERT(!(offset & 1), "otherwise we have an invalid offset.");
  1451. bool bNeedNewRow = Ty->isArrayTy();
  1452. if (!bNeedNewRow && Ty->isStructTy()) {
  1453. if (HLMatrixType mat = HLMatrixType::dyn_cast(Ty)) {
  1454. bNeedNewRow |= !bRowMajor && mat.getNumColumns() > 1;
  1455. bNeedNewRow |= bRowMajor && mat.getNumRows() > 1;
  1456. } else {
  1457. bNeedNewRow = true;
  1458. }
  1459. }
  1460. unsigned scalarSizeInBytes = Ty->getScalarSizeInBits() / 8;
  1461. return AlignBufferOffsetInLegacy(offset, size, scalarSizeInBytes,
  1462. bNeedNewRow);
  1463. }
  1464. unsigned
  1465. AllocateDxilConstantBuffer(HLCBuffer &CB,
  1466. std::unordered_map<Constant *, DxilFieldAnnotation>
  1467. &constVarAnnotationMap) {
  1468. unsigned offset = 0;
  1469. // Scan user allocated constants first.
  1470. // Update offset.
  1471. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  1472. if (C->GetLowerBound() == UINT_MAX)
  1473. continue;
  1474. unsigned size = C->GetRangeSize();
  1475. unsigned nextOffset = size + C->GetLowerBound();
  1476. if (offset < nextOffset)
  1477. offset = nextOffset;
  1478. }
  1479. // Alloc after user allocated constants.
  1480. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  1481. if (C->GetLowerBound() != UINT_MAX)
  1482. continue;
  1483. unsigned size = C->GetRangeSize();
  1484. llvm::Type *Ty = C->GetGlobalSymbol()->getType()->getPointerElementType();
  1485. auto fieldAnnotation = constVarAnnotationMap.at(C->GetGlobalSymbol());
  1486. bool bRowMajor = HLMatrixType::isa(Ty)
  1487. ? fieldAnnotation.GetMatrixAnnotation().Orientation ==
  1488. MatrixOrientation::RowMajor
  1489. : false;
  1490. // Align offset.
  1491. offset = AlignCBufferOffset(offset, size, Ty, bRowMajor);
  1492. if (C->GetLowerBound() == UINT_MAX) {
  1493. C->SetLowerBound(offset);
  1494. }
  1495. offset += size;
  1496. }
  1497. return offset;
  1498. }
  1499. void AllocateDxilConstantBuffers(
  1500. HLModule &HLM, std::unordered_map<Constant *, DxilFieldAnnotation>
  1501. &constVarAnnotationMap) {
  1502. for (unsigned i = 0; i < HLM.GetCBuffers().size(); i++) {
  1503. HLCBuffer &CB = *static_cast<HLCBuffer *>(&(HLM.GetCBuffer(i)));
  1504. unsigned size = AllocateDxilConstantBuffer(CB, constVarAnnotationMap);
  1505. CB.SetSize(size);
  1506. }
  1507. }
  1508. } // namespace
  1509. namespace {
  1510. void ReplaceUseInFunction(Value *V, Value *NewV, Function *F,
  1511. IRBuilder<> &Builder) {
  1512. for (auto U = V->user_begin(); U != V->user_end();) {
  1513. User *user = *(U++);
  1514. if (Instruction *I = dyn_cast<Instruction>(user)) {
  1515. if (I->getParent()->getParent() == F) {
  1516. // replace use with GEP if in F
  1517. for (unsigned i = 0; i < I->getNumOperands(); i++) {
  1518. if (I->getOperand(i) == V)
  1519. I->setOperand(i, NewV);
  1520. }
  1521. }
  1522. } else {
  1523. // For constant operator, create local clone which use GEP.
  1524. // Only support GEP and bitcast.
  1525. if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(user)) {
  1526. std::vector<Value *> idxList(GEPOp->idx_begin(), GEPOp->idx_end());
  1527. Value *NewGEP = Builder.CreateInBoundsGEP(NewV, idxList);
  1528. ReplaceUseInFunction(GEPOp, NewGEP, F, Builder);
  1529. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(user)) {
  1530. // Change the init val into NewV with Store.
  1531. GV->setInitializer(nullptr);
  1532. Builder.CreateStore(NewV, GV);
  1533. } else {
  1534. // Must be bitcast here.
  1535. BitCastOperator *BC = cast<BitCastOperator>(user);
  1536. Value *NewBC = Builder.CreateBitCast(NewV, BC->getType());
  1537. ReplaceUseInFunction(BC, NewBC, F, Builder);
  1538. }
  1539. }
  1540. }
  1541. }
  1542. void MarkUsedFunctionForConst(Value *V,
  1543. std::unordered_set<Function *> &usedFunc) {
  1544. for (auto U = V->user_begin(); U != V->user_end();) {
  1545. User *user = *(U++);
  1546. if (Instruction *I = dyn_cast<Instruction>(user)) {
  1547. Function *F = I->getParent()->getParent();
  1548. usedFunc.insert(F);
  1549. } else {
  1550. // For constant operator, create local clone which use GEP.
  1551. // Only support GEP and bitcast.
  1552. if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(user)) {
  1553. MarkUsedFunctionForConst(GEPOp, usedFunc);
  1554. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(user)) {
  1555. MarkUsedFunctionForConst(GV, usedFunc);
  1556. } else {
  1557. // Must be bitcast here.
  1558. BitCastOperator *BC = cast<BitCastOperator>(user);
  1559. MarkUsedFunctionForConst(BC, usedFunc);
  1560. }
  1561. }
  1562. }
  1563. }
  1564. bool CreateCBufferVariable(HLCBuffer &CB, HLModule &HLM, llvm::Type *HandleTy) {
  1565. bool bUsed = false;
  1566. // Build Struct for CBuffer.
  1567. SmallVector<llvm::Type *, 4> Elements;
  1568. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  1569. Value *GV = C->GetGlobalSymbol();
  1570. if (GV->hasNUsesOrMore(1))
  1571. bUsed = true;
  1572. // Global variable must be pointer type.
  1573. llvm::Type *Ty = GV->getType()->getPointerElementType();
  1574. Elements.emplace_back(Ty);
  1575. }
  1576. // Don't create CBuffer variable for unused cbuffer.
  1577. if (!bUsed)
  1578. return false;
  1579. llvm::Module &M = *HLM.GetModule();
  1580. bool isCBArray = CB.GetRangeSize() != 1;
  1581. llvm::GlobalVariable *cbGV = nullptr;
  1582. llvm::Type *cbTy = nullptr;
  1583. unsigned cbIndexDepth = 0;
  1584. if (!isCBArray) {
  1585. llvm::StructType *CBStructTy =
  1586. llvm::StructType::create(Elements, CB.GetGlobalName());
  1587. cbGV = new llvm::GlobalVariable(M, CBStructTy, /*IsConstant*/ true,
  1588. llvm::GlobalValue::ExternalLinkage,
  1589. /*InitVal*/ nullptr, CB.GetGlobalName());
  1590. cbTy = cbGV->getType();
  1591. } else {
  1592. // For array of ConstantBuffer, create array of struct instead of struct of
  1593. // array.
  1594. DXASSERT(CB.GetConstants().size() == 1,
  1595. "ConstantBuffer should have 1 constant");
  1596. Value *GV = CB.GetConstants()[0]->GetGlobalSymbol();
  1597. llvm::Type *CBEltTy =
  1598. GV->getType()->getPointerElementType()->getArrayElementType();
  1599. cbIndexDepth = 1;
  1600. while (CBEltTy->isArrayTy()) {
  1601. CBEltTy = CBEltTy->getArrayElementType();
  1602. cbIndexDepth++;
  1603. }
  1604. // Add one level struct type to match normal case.
  1605. llvm::StructType *CBStructTy =
  1606. llvm::StructType::create({CBEltTy}, CB.GetGlobalName());
  1607. llvm::ArrayType *CBArrayTy =
  1608. llvm::ArrayType::get(CBStructTy, CB.GetRangeSize());
  1609. cbGV = new llvm::GlobalVariable(M, CBArrayTy, /*IsConstant*/ true,
  1610. llvm::GlobalValue::ExternalLinkage,
  1611. /*InitVal*/ nullptr, CB.GetGlobalName());
  1612. cbTy = llvm::PointerType::get(CBStructTy,
  1613. cbGV->getType()->getPointerAddressSpace());
  1614. }
  1615. CB.SetGlobalSymbol(cbGV);
  1616. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  1617. llvm::Type *idxTy = opcodeTy;
  1618. Constant *zeroIdx = ConstantInt::get(opcodeTy, 0);
  1619. Value *HandleArgs[] = {cbGV, zeroIdx};
  1620. llvm::FunctionType *SubscriptFuncTy =
  1621. llvm::FunctionType::get(cbTy, {opcodeTy, HandleTy, idxTy}, false);
  1622. Function *subscriptFunc =
  1623. GetOrCreateHLFunction(M, SubscriptFuncTy, HLOpcodeGroup::HLSubscript,
  1624. (unsigned)HLSubscriptOpcode::CBufferSubscript);
  1625. Constant *opArg =
  1626. ConstantInt::get(opcodeTy, (unsigned)HLSubscriptOpcode::CBufferSubscript);
  1627. Value *args[] = {opArg, nullptr, zeroIdx};
  1628. llvm::LLVMContext &Context = M.getContext();
  1629. llvm::Type *i32Ty = llvm::Type::getInt32Ty(Context);
  1630. Value *zero = ConstantInt::get(i32Ty, (uint64_t)0);
  1631. std::vector<Value *> indexArray(CB.GetConstants().size());
  1632. std::vector<std::unordered_set<Function *>> constUsedFuncList(
  1633. CB.GetConstants().size());
  1634. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  1635. Value *idx = ConstantInt::get(i32Ty, C->GetID());
  1636. indexArray[C->GetID()] = idx;
  1637. Value *GV = C->GetGlobalSymbol();
  1638. MarkUsedFunctionForConst(GV, constUsedFuncList[C->GetID()]);
  1639. }
  1640. for (Function &F : M.functions()) {
  1641. if (F.isDeclaration())
  1642. continue;
  1643. if (GetHLOpcodeGroupByName(&F) != HLOpcodeGroup::NotHL)
  1644. continue;
  1645. IRBuilder<> Builder(F.getEntryBlock().getFirstInsertionPt());
  1646. // create HL subscript to make all the use of cbuffer start from it.
  1647. HandleArgs[HLOperandIndex::kCreateHandleResourceOpIdx-1] = cbGV;
  1648. CallInst *Handle = HLM.EmitHLOperationCall(
  1649. Builder, HLOpcodeGroup::HLCreateHandle, 0, HandleTy, HandleArgs, M);
  1650. args[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  1651. Instruction *cbSubscript =
  1652. cast<Instruction>(Builder.CreateCall(subscriptFunc, {args}));
  1653. // Replace constant var with GEP pGV
  1654. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  1655. Value *GV = C->GetGlobalSymbol();
  1656. if (constUsedFuncList[C->GetID()].count(&F) == 0)
  1657. continue;
  1658. Value *idx = indexArray[C->GetID()];
  1659. if (!isCBArray) {
  1660. Instruction *GEP = cast<Instruction>(
  1661. Builder.CreateInBoundsGEP(cbSubscript, {zero, idx}));
  1662. // TODO: make sure the debug info is synced to GEP.
  1663. // GEP->setDebugLoc(GV);
  1664. ReplaceUseInFunction(GV, GEP, &F, Builder);
  1665. // Delete if no use in F.
  1666. if (GEP->user_empty())
  1667. GEP->eraseFromParent();
  1668. } else {
  1669. for (auto U = GV->user_begin(); U != GV->user_end();) {
  1670. User *user = *(U++);
  1671. if (user->user_empty())
  1672. continue;
  1673. Instruction *I = dyn_cast<Instruction>(user);
  1674. if (I && I->getParent()->getParent() != &F)
  1675. continue;
  1676. IRBuilder<> *instBuilder = &Builder;
  1677. std::unique_ptr<IRBuilder<>> B;
  1678. if (I) {
  1679. B = llvm::make_unique<IRBuilder<>>(I);
  1680. instBuilder = B.get();
  1681. }
  1682. GEPOperator *GEPOp = cast<GEPOperator>(user);
  1683. std::vector<Value *> idxList;
  1684. DXASSERT(GEPOp->getNumIndices() >= 1 + cbIndexDepth,
  1685. "must indexing ConstantBuffer array");
  1686. idxList.reserve(GEPOp->getNumIndices() - (cbIndexDepth - 1));
  1687. gep_type_iterator GI = gep_type_begin(*GEPOp),
  1688. E = gep_type_end(*GEPOp);
  1689. idxList.push_back(GI.getOperand());
  1690. // change array index with 0 for struct index.
  1691. idxList.push_back(zero);
  1692. GI++;
  1693. Value *arrayIdx = GI.getOperand();
  1694. GI++;
  1695. for (unsigned curIndex = 1; GI != E && curIndex < cbIndexDepth;
  1696. ++GI, ++curIndex) {
  1697. arrayIdx = instBuilder->CreateMul(
  1698. arrayIdx, Builder.getInt32(GI->getArrayNumElements()));
  1699. arrayIdx = instBuilder->CreateAdd(arrayIdx, GI.getOperand());
  1700. }
  1701. for (; GI != E; ++GI) {
  1702. idxList.push_back(GI.getOperand());
  1703. }
  1704. HandleArgs[HLOperandIndex::kCreateHandleIndexOpIdx-1] = arrayIdx;
  1705. CallInst *Handle =
  1706. HLM.EmitHLOperationCall(*instBuilder,
  1707. HLOpcodeGroup::HLCreateHandle, 0,
  1708. HandleTy, HandleArgs, M);
  1709. args[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  1710. args[HLOperandIndex::kSubscriptIndexOpIdx] = arrayIdx;
  1711. Instruction *cbSubscript =
  1712. cast<Instruction>(instBuilder->CreateCall(subscriptFunc, {args}));
  1713. Instruction *NewGEP = cast<Instruction>(
  1714. instBuilder->CreateInBoundsGEP(cbSubscript, idxList));
  1715. ReplaceUseInFunction(GEPOp, NewGEP, &F, *instBuilder);
  1716. }
  1717. }
  1718. }
  1719. // Delete if no use in F.
  1720. if (cbSubscript->user_empty()) {
  1721. cbSubscript->eraseFromParent();
  1722. Handle->eraseFromParent();
  1723. } else {
  1724. // merge GEP use for cbSubscript.
  1725. HLModule::MergeGepUse(cbSubscript);
  1726. }
  1727. }
  1728. return true;
  1729. }
  1730. void ConstructCBufferAnnotation(
  1731. HLCBuffer &CB, DxilTypeSystem &dxilTypeSys,
  1732. std::unordered_map<Constant *, DxilFieldAnnotation> &AnnotationMap) {
  1733. Value *GV = CB.GetGlobalSymbol();
  1734. llvm::StructType *CBStructTy =
  1735. dyn_cast<llvm::StructType>(GV->getType()->getPointerElementType());
  1736. if (!CBStructTy) {
  1737. // For Array of ConstantBuffer.
  1738. llvm::ArrayType *CBArrayTy =
  1739. cast<llvm::ArrayType>(GV->getType()->getPointerElementType());
  1740. CBStructTy = cast<llvm::StructType>(CBArrayTy->getArrayElementType());
  1741. }
  1742. DxilStructAnnotation *CBAnnotation =
  1743. dxilTypeSys.AddStructAnnotation(CBStructTy);
  1744. CBAnnotation->SetCBufferSize(CB.GetSize());
  1745. // Set fieldAnnotation for each constant var.
  1746. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  1747. Constant *GV = C->GetGlobalSymbol();
  1748. DxilFieldAnnotation &fieldAnnotation =
  1749. CBAnnotation->GetFieldAnnotation(C->GetID());
  1750. fieldAnnotation = AnnotationMap[GV];
  1751. // This is after CBuffer allocation.
  1752. fieldAnnotation.SetCBufferOffset(C->GetLowerBound());
  1753. fieldAnnotation.SetFieldName(C->GetGlobalName());
  1754. }
  1755. }
  1756. void ConstructCBuffer(
  1757. HLModule &HLM, llvm::Type *CBufferType,
  1758. std::unordered_map<Constant *, DxilFieldAnnotation> &AnnotationMap) {
  1759. DxilTypeSystem &dxilTypeSys = HLM.GetTypeSystem();
  1760. llvm::Type *HandleTy = HLM.GetOP()->GetHandleType();
  1761. for (unsigned i = 0; i < HLM.GetCBuffers().size(); i++) {
  1762. HLCBuffer &CB = *static_cast<HLCBuffer *>(&(HLM.GetCBuffer(i)));
  1763. if (CB.GetConstants().size() == 0) {
  1764. // Create Fake variable for cbuffer which is empty.
  1765. llvm::GlobalVariable *pGV = new llvm::GlobalVariable(
  1766. *HLM.GetModule(), CBufferType, true,
  1767. llvm::GlobalValue::ExternalLinkage, nullptr, CB.GetGlobalName());
  1768. CB.SetGlobalSymbol(pGV);
  1769. } else {
  1770. bool bCreated = CreateCBufferVariable(CB, HLM, HandleTy);
  1771. if (bCreated)
  1772. ConstructCBufferAnnotation(CB, dxilTypeSys, AnnotationMap);
  1773. else {
  1774. // Create Fake variable for cbuffer which is unused.
  1775. llvm::GlobalVariable *pGV = new llvm::GlobalVariable(
  1776. *HLM.GetModule(), CBufferType, true,
  1777. llvm::GlobalValue::ExternalLinkage, nullptr, CB.GetGlobalName());
  1778. CB.SetGlobalSymbol(pGV);
  1779. }
  1780. }
  1781. // Clear the constants which useless now.
  1782. CB.GetConstants().clear();
  1783. }
  1784. }
  1785. }
  1786. namespace CGHLSLMSHelper {
  1787. // Align cbuffer offset in legacy mode (16 bytes per row).
  1788. unsigned AlignBufferOffsetInLegacy(unsigned offset, unsigned size,
  1789. unsigned scalarSizeInBytes,
  1790. bool bNeedNewRow) {
  1791. if (unsigned remainder = (offset & 0xf)) {
  1792. // Start from new row
  1793. if (remainder + size > 16 || bNeedNewRow) {
  1794. return offset + 16 - remainder;
  1795. }
  1796. // If not, naturally align data
  1797. return RoundToAlign(offset, scalarSizeInBytes);
  1798. }
  1799. return offset;
  1800. }
  1801. // Translate RayQuery constructor. From:
  1802. // %call = call %"RayQuery<flags>" @<constructor>(%"RayQuery<flags>" %ptr)
  1803. // To:
  1804. // i32 %handle = AllocateRayQuery(i32 <IntrinsicOp::IOP_AllocateRayQuery>, i32
  1805. // %flags) %gep = GEP %"RayQuery<flags>" %ptr, 0, 0 store i32* %gep, i32
  1806. // %handle ; and replace uses of %call with %ptr
  1807. void TranslateRayQueryConstructor(HLModule &HLM) {
  1808. llvm::Module &M = *HLM.GetModule();
  1809. SmallVector<Function *, 4> Constructors;
  1810. for (auto &F : M.functions()) {
  1811. // Match templated RayQuery constructor instantiation by prefix and
  1812. // signature. It should be impossible to achieve the same signature from
  1813. // HLSL.
  1814. if (!F.getName().startswith("\01??0?$RayQuery@$"))
  1815. continue;
  1816. llvm::Type *Ty = F.getReturnType();
  1817. if (!Ty->isPointerTy() ||
  1818. !dxilutil::IsHLSLRayQueryType(Ty->getPointerElementType()))
  1819. continue;
  1820. if (F.arg_size() != 1 || Ty != F.arg_begin()->getType())
  1821. continue;
  1822. Constructors.emplace_back(&F);
  1823. }
  1824. for (auto pConstructorFunc : Constructors) {
  1825. llvm::IntegerType *i32Ty = llvm::Type::getInt32Ty(M.getContext());
  1826. llvm::ConstantInt *i32Zero =
  1827. llvm::ConstantInt::get(i32Ty, (uint64_t)0, false);
  1828. llvm::FunctionType *funcTy =
  1829. llvm::FunctionType::get(i32Ty, {i32Ty, i32Ty}, false);
  1830. unsigned opcode = (unsigned)IntrinsicOp::IOP_AllocateRayQuery;
  1831. llvm::ConstantInt *opVal = llvm::ConstantInt::get(i32Ty, opcode, false);
  1832. Function *opFunc =
  1833. GetOrCreateHLFunction(M, funcTy, HLOpcodeGroup::HLIntrinsic, opcode);
  1834. while (!pConstructorFunc->user_empty()) {
  1835. Value *V = *pConstructorFunc->user_begin();
  1836. llvm::CallInst *CI = cast<CallInst>(V); // Must be call
  1837. llvm::Value *pThis = CI->getArgOperand(0);
  1838. llvm::StructType *pRQType =
  1839. cast<llvm::StructType>(pThis->getType()->getPointerElementType());
  1840. DxilStructAnnotation *SA =
  1841. HLM.GetTypeSystem().GetStructAnnotation(pRQType);
  1842. DXASSERT(SA, "otherwise, could not find type annoation for RayQuery "
  1843. "specialization");
  1844. DXASSERT(SA->GetNumTemplateArgs() == 1 &&
  1845. SA->GetTemplateArgAnnotation(0).IsIntegral(),
  1846. "otherwise, RayQuery has changed, or lacks template args");
  1847. llvm::IRBuilder<> Builder(CI);
  1848. llvm::Value *rayFlags =
  1849. Builder.getInt32(SA->GetTemplateArgAnnotation(0).GetIntegral());
  1850. llvm::Value *Call =
  1851. Builder.CreateCall(opFunc, {opVal, rayFlags}, pThis->getName());
  1852. llvm::Value *GEP = Builder.CreateInBoundsGEP(pThis, {i32Zero, i32Zero});
  1853. Builder.CreateStore(Call, GEP);
  1854. CI->replaceAllUsesWith(pThis);
  1855. CI->eraseFromParent();
  1856. }
  1857. pConstructorFunc->eraseFromParent();
  1858. }
  1859. }
  1860. }
  1861. namespace {
  1862. bool BuildImmInit(Function *Ctor) {
  1863. GlobalVariable *GV = nullptr;
  1864. SmallVector<Constant *, 4> ImmList;
  1865. bool allConst = true;
  1866. for (inst_iterator I = inst_begin(Ctor), E = inst_end(Ctor); I != E; ++I) {
  1867. if (StoreInst *SI = dyn_cast<StoreInst>(&(*I))) {
  1868. Value *V = SI->getValueOperand();
  1869. if (!isa<Constant>(V) || V->getType()->isPointerTy()) {
  1870. allConst = false;
  1871. break;
  1872. }
  1873. ImmList.emplace_back(cast<Constant>(V));
  1874. Value *Ptr = SI->getPointerOperand();
  1875. if (GEPOperator *GepOp = dyn_cast<GEPOperator>(Ptr)) {
  1876. Ptr = GepOp->getPointerOperand();
  1877. if (GlobalVariable *pGV = dyn_cast<GlobalVariable>(Ptr)) {
  1878. if (GV == nullptr)
  1879. GV = pGV;
  1880. else {
  1881. DXASSERT(GV == pGV, "else pointer mismatch");
  1882. }
  1883. }
  1884. }
  1885. } else {
  1886. if (!isa<ReturnInst>(*I)) {
  1887. allConst = false;
  1888. break;
  1889. }
  1890. }
  1891. }
  1892. if (!allConst)
  1893. return false;
  1894. if (!GV)
  1895. return false;
  1896. llvm::Type *Ty = GV->getType()->getElementType();
  1897. llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty);
  1898. // TODO: support other types.
  1899. if (!AT)
  1900. return false;
  1901. if (ImmList.size() != AT->getNumElements())
  1902. return false;
  1903. Constant *Init = llvm::ConstantArray::get(AT, ImmList);
  1904. GV->setInitializer(Init);
  1905. return true;
  1906. }
  1907. } // namespace
  1908. namespace CGHLSLMSHelper {
  1909. void ProcessCtorFunctions(llvm::Module &M, StringRef globalName,
  1910. Instruction *InsertPt) {
  1911. // add global call to entry func
  1912. GlobalVariable *GV = M.getGlobalVariable(globalName);
  1913. if (!GV)
  1914. return;
  1915. ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
  1916. if (!CA)
  1917. return;
  1918. IRBuilder<> Builder(InsertPt);
  1919. for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
  1920. if (isa<ConstantAggregateZero>(*i))
  1921. continue;
  1922. ConstantStruct *CS = cast<ConstantStruct>(*i);
  1923. if (isa<ConstantPointerNull>(CS->getOperand(1)))
  1924. continue;
  1925. // Must have a function or null ptr.
  1926. if (!isa<Function>(CS->getOperand(1)))
  1927. continue;
  1928. Function *Ctor = cast<Function>(CS->getOperand(1));
  1929. DXASSERT(Ctor->getReturnType()->isVoidTy() && Ctor->arg_size() == 0,
  1930. "function type must be void (void)");
  1931. for (inst_iterator I = inst_begin(Ctor), E = inst_end(Ctor); I != E; ++I) {
  1932. if (CallInst *CI = dyn_cast<CallInst>(&(*I))) {
  1933. Function *F = CI->getCalledFunction();
  1934. // Try to build imm initilizer.
  1935. // If not work, add global call to entry func.
  1936. if (BuildImmInit(F) == false) {
  1937. Builder.CreateCall(F);
  1938. }
  1939. } else {
  1940. DXASSERT(isa<ReturnInst>(&(*I)),
  1941. "else invalid Global constructor function");
  1942. }
  1943. }
  1944. }
  1945. // remove the GV
  1946. GV->eraseFromParent();
  1947. }
  1948. void FinishCBuffer(HLModule &HLM, llvm::Type *CBufferType,
  1949. std::unordered_map<Constant *, DxilFieldAnnotation>
  1950. &constVarAnnotationMap) {
  1951. // Allocate constant buffers.
  1952. AllocateDxilConstantBuffers(HLM, constVarAnnotationMap);
  1953. // TODO: create temp variable for constant which has store use.
  1954. // Create Global variable and type annotation for each CBuffer.
  1955. ConstructCBuffer(HLM, CBufferType, constVarAnnotationMap);
  1956. }
  1957. void AddRegBindingsForResourceInConstantBuffer(
  1958. HLModule &HLM,
  1959. llvm::DenseMap<llvm::Constant *,
  1960. llvm::SmallVector<std::pair<DXIL::ResourceClass, unsigned>,
  1961. 1>> &constantRegBindingMap) {
  1962. for (unsigned i = 0; i < HLM.GetCBuffers().size(); i++) {
  1963. HLCBuffer &CB = *static_cast<HLCBuffer *>(&(HLM.GetCBuffer(i)));
  1964. auto &Constants = CB.GetConstants();
  1965. for (unsigned j = 0; j < Constants.size(); j++) {
  1966. const std::unique_ptr<DxilResourceBase> &C = Constants[j];
  1967. Constant *CGV = C->GetGlobalSymbol();
  1968. auto &regBindings = constantRegBindingMap[CGV];
  1969. if (regBindings.empty())
  1970. continue;
  1971. unsigned Srv = UINT_MAX;
  1972. unsigned Uav = UINT_MAX;
  1973. unsigned Sampler = UINT_MAX;
  1974. for (auto it : regBindings) {
  1975. unsigned RegNum = it.second;
  1976. switch (it.first) {
  1977. case DXIL::ResourceClass::SRV:
  1978. Srv = RegNum;
  1979. break;
  1980. case DXIL::ResourceClass::UAV:
  1981. Uav = RegNum;
  1982. break;
  1983. case DXIL::ResourceClass::Sampler:
  1984. Sampler = RegNum;
  1985. break;
  1986. default:
  1987. DXASSERT(0, "invalid resource class");
  1988. break;
  1989. }
  1990. }
  1991. HLM.AddRegBinding(CB.GetID(), j, Srv, Uav, Sampler);
  1992. }
  1993. }
  1994. }
  1995. // extension codegen.
  1996. void ExtensionCodeGen(HLModule &HLM, clang::CodeGen::CodeGenModule &CGM) {
  1997. // Add semantic defines for extensions if any are available.
  1998. HLSLExtensionsCodegenHelper::SemanticDefineErrorList errors =
  1999. CGM.getCodeGenOpts().HLSLExtensionsCodegen->WriteSemanticDefines(
  2000. HLM.GetModule());
  2001. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  2002. for (const HLSLExtensionsCodegenHelper::SemanticDefineError &error : errors) {
  2003. clang::DiagnosticsEngine::Level level = clang::DiagnosticsEngine::Error;
  2004. if (error.IsWarning())
  2005. level = clang::DiagnosticsEngine::Warning;
  2006. unsigned DiagID = Diags.getCustomDiagID(level, "%0");
  2007. Diags.Report(clang::SourceLocation::getFromRawEncoding(error.Location()),
  2008. DiagID)
  2009. << error.Message();
  2010. }
  2011. // Add root signature from a #define. Overrides root signature in function
  2012. // attribute.
  2013. {
  2014. using Status = HLSLExtensionsCodegenHelper::CustomRootSignature::Status;
  2015. HLSLExtensionsCodegenHelper::CustomRootSignature customRootSig;
  2016. HLSLExtensionsCodegenHelper::CustomRootSignature::Status status =
  2017. CGM.getCodeGenOpts().HLSLExtensionsCodegen->GetCustomRootSignature(
  2018. &customRootSig);
  2019. if (status == Status::FOUND) {
  2020. DxilRootSignatureVersion rootSigVer;
  2021. // set root signature version.
  2022. if (CGM.getLangOpts().RootSigMinor == 0) {
  2023. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_0;
  2024. } else {
  2025. DXASSERT(CGM.getLangOpts().RootSigMinor == 1,
  2026. "else CGMSHLSLRuntime Constructor needs to be updated");
  2027. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_1;
  2028. }
  2029. RootSignatureHandle RootSigHandle;
  2030. CompileRootSignature(
  2031. customRootSig.RootSignature, Diags,
  2032. clang::SourceLocation::getFromRawEncoding(
  2033. customRootSig.EncodedSourceLocation),
  2034. rootSigVer, DxilRootSignatureCompilationFlags::GlobalRootSignature,
  2035. &RootSigHandle);
  2036. if (!RootSigHandle.IsEmpty()) {
  2037. RootSigHandle.EnsureSerializedAvailable();
  2038. HLM.SetSerializedRootSignature(RootSigHandle.GetSerializedBytes(),
  2039. RootSigHandle.GetSerializedSize());
  2040. }
  2041. }
  2042. }
  2043. }
  2044. } // namespace CGHLSLMSHelper
  2045. namespace {
  2046. void ReportDisallowedTypeInExportParam(clang::CodeGen ::CodeGenModule &CGM,
  2047. StringRef name) {
  2048. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  2049. unsigned DiagID =
  2050. Diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
  2051. "Exported function %0 must not contain a "
  2052. "resource in parameter or return type.");
  2053. std::string escaped;
  2054. llvm::raw_string_ostream os(escaped);
  2055. dxilutil::PrintEscapedString(name, os);
  2056. Diags.Report(DiagID) << os.str();
  2057. }
  2058. } // namespace
  2059. namespace CGHLSLMSHelper {
  2060. void FinishClipPlane(HLModule &HLM, std::vector<Function *> &clipPlaneFuncList,
  2061. std::unordered_map<Value *, DebugLoc> &debugInfoMap,
  2062. clang::CodeGen::CodeGenModule &CGM) {
  2063. bool bDebugInfo = CGM.getCodeGenOpts().getDebugInfo() ==
  2064. clang::CodeGenOptions::FullDebugInfo;
  2065. Module &M = *HLM.GetModule();
  2066. for (Function *F : clipPlaneFuncList) {
  2067. DxilFunctionProps &props = HLM.GetDxilFunctionProps(F);
  2068. IRBuilder<> Builder(F->getEntryBlock().getFirstInsertionPt());
  2069. for (unsigned i = 0; i < DXIL::kNumClipPlanes; i++) {
  2070. Value *clipPlane = props.ShaderProps.VS.clipPlanes[i];
  2071. if (!clipPlane)
  2072. continue;
  2073. if (bDebugInfo) {
  2074. Builder.SetCurrentDebugLocation(debugInfoMap[clipPlane]);
  2075. }
  2076. llvm::Type *Ty = clipPlane->getType()->getPointerElementType();
  2077. // Constant *zeroInit = ConstantFP::get(Ty, 0);
  2078. GlobalVariable *GV = new llvm::GlobalVariable(
  2079. M, Ty, /*IsConstant*/ false, // constant false to store.
  2080. llvm::GlobalValue::ExternalLinkage,
  2081. /*InitVal*/ nullptr, Twine("SV_ClipPlane") + Twine(i));
  2082. Value *initVal = Builder.CreateLoad(clipPlane);
  2083. Builder.CreateStore(initVal, GV);
  2084. props.ShaderProps.VS.clipPlanes[i] = GV;
  2085. }
  2086. }
  2087. }
  2088. } // namespace
  2089. namespace {
  2090. void LowerExportFunctions(HLModule &HLM, clang::CodeGen::CodeGenModule &CGM,
  2091. dxilutil::ExportMap &exportMap,
  2092. StringMap<EntryFunctionInfo> &entryFunctionMap) {
  2093. bool bIsLib = HLM.GetShaderModel()->IsLib();
  2094. Module &M = *HLM.GetModule();
  2095. if (bIsLib && !exportMap.empty()) {
  2096. for (auto &it : entryFunctionMap) {
  2097. if (HLM.HasDxilFunctionProps(it.second.Func)) {
  2098. const DxilFunctionProps &props =
  2099. HLM.GetDxilFunctionProps(it.second.Func);
  2100. if (props.IsHS())
  2101. exportMap.RegisterExportedFunction(
  2102. props.ShaderProps.HS.patchConstantFunc);
  2103. }
  2104. }
  2105. }
  2106. if (bIsLib && !exportMap.empty()) {
  2107. exportMap.BeginProcessing();
  2108. for (Function &f : M.functions()) {
  2109. if (f.isDeclaration() || f.isIntrinsic() ||
  2110. GetHLOpcodeGroup(&f) != HLOpcodeGroup::NotHL)
  2111. continue;
  2112. exportMap.ProcessFunction(&f, true);
  2113. }
  2114. // TODO: add subobject export names here.
  2115. if (!exportMap.EndProcessing()) {
  2116. for (auto &name : exportMap.GetNameCollisions()) {
  2117. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  2118. unsigned DiagID = Diags.getCustomDiagID(
  2119. clang::DiagnosticsEngine::Error,
  2120. "Export name collides with another export: %0");
  2121. std::string escaped;
  2122. llvm::raw_string_ostream os(escaped);
  2123. dxilutil::PrintEscapedString(name, os);
  2124. Diags.Report(DiagID) << os.str();
  2125. }
  2126. for (auto &name : exportMap.GetUnusedExports()) {
  2127. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  2128. unsigned DiagID =
  2129. Diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
  2130. "Could not find target for export: %0");
  2131. std::string escaped;
  2132. llvm::raw_string_ostream os(escaped);
  2133. dxilutil::PrintEscapedString(name, os);
  2134. Diags.Report(DiagID) << os.str();
  2135. }
  2136. }
  2137. }
  2138. for (auto &it : exportMap.GetFunctionRenames()) {
  2139. Function *F = it.first;
  2140. auto &renames = it.second;
  2141. if (renames.empty())
  2142. continue;
  2143. // Rename the original, if necessary, then clone the rest
  2144. if (renames.find(F->getName()) == renames.end())
  2145. F->setName(*renames.begin());
  2146. for (auto &itName : renames) {
  2147. if (F->getName() != itName) {
  2148. Function *pClone = CloneFunction(F, itName, &M, HLM.GetTypeSystem(),
  2149. HLM.GetTypeSystem());
  2150. // add DxilFunctionProps if entry
  2151. if (HLM.HasDxilFunctionProps(F)) {
  2152. DxilFunctionProps &props = HLM.GetDxilFunctionProps(F);
  2153. auto newProps = llvm::make_unique<DxilFunctionProps>(props);
  2154. HLM.AddDxilFunctionProps(pClone, newProps);
  2155. }
  2156. }
  2157. }
  2158. }
  2159. }
  2160. void CheckResourceParameters(HLModule &HLM,
  2161. clang::CodeGen::CodeGenModule &CGM) {
  2162. Module &M = *HLM.GetModule();
  2163. for (Function &f : M.functions()) {
  2164. // Skip llvm intrinsics, non-external linkage, entry/patch constant func,
  2165. // and HL intrinsics
  2166. if (!f.isIntrinsic() &&
  2167. f.getLinkage() == GlobalValue::LinkageTypes::ExternalLinkage &&
  2168. !HLM.HasDxilFunctionProps(&f) && !HLM.IsPatchConstantShader(&f) &&
  2169. GetHLOpcodeGroup(&f) == HLOpcodeGroup::NotHL) {
  2170. // Verify no resources in param/return types
  2171. if (dxilutil::ContainsHLSLObjectType(f.getReturnType())) {
  2172. ReportDisallowedTypeInExportParam(CGM, f.getName());
  2173. continue;
  2174. }
  2175. for (auto &Arg : f.args()) {
  2176. if (dxilutil::ContainsHLSLObjectType(Arg.getType())) {
  2177. ReportDisallowedTypeInExportParam(CGM, f.getName());
  2178. break;
  2179. }
  2180. }
  2181. }
  2182. }
  2183. }
  2184. } // namespace
  2185. namespace CGHLSLMSHelper {
  2186. void UpdateLinkage(HLModule &HLM, clang::CodeGen::CodeGenModule &CGM,
  2187. dxilutil::ExportMap &exportMap,
  2188. StringMap<EntryFunctionInfo> &entryFunctionMap,
  2189. StringMap<PatchConstantInfo> &patchConstantFunctionMap) {
  2190. bool bIsLib = HLM.GetShaderModel()->IsLib();
  2191. Module &M = *HLM.GetModule();
  2192. // Pin entry point and constant buffers, mark everything else internal.
  2193. for (Function &f : M.functions()) {
  2194. if (!bIsLib) {
  2195. if (&f == HLM.GetEntryFunction() ||
  2196. IsPatchConstantFunction(&f, patchConstantFunctionMap) ||
  2197. f.isDeclaration()) {
  2198. if (f.isDeclaration() && !f.isIntrinsic() &&
  2199. GetHLOpcodeGroup(&f) == HLOpcodeGroup::NotHL) {
  2200. clang::DiagnosticsEngine &Diags = CGM.getDiags();
  2201. unsigned DiagID = Diags.getCustomDiagID(
  2202. clang::DiagnosticsEngine::Error,
  2203. "External function used in non-library profile: %0");
  2204. std::string escaped;
  2205. llvm::raw_string_ostream os(escaped);
  2206. dxilutil::PrintEscapedString(f.getName(), os);
  2207. Diags.Report(DiagID) << os.str();
  2208. return;
  2209. }
  2210. f.setLinkage(GlobalValue::LinkageTypes::ExternalLinkage);
  2211. } else {
  2212. f.setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  2213. }
  2214. }
  2215. // Skip no inline functions.
  2216. if (f.hasFnAttribute(llvm::Attribute::NoInline))
  2217. continue;
  2218. // Always inline for used functions.
  2219. if (!f.user_empty() && !f.isDeclaration())
  2220. f.addFnAttr(llvm::Attribute::AlwaysInline);
  2221. }
  2222. LowerExportFunctions(HLM, CGM, exportMap, entryFunctionMap);
  2223. if (CGM.getCodeGenOpts().ExportShadersOnly) {
  2224. for (Function &f : M.functions()) {
  2225. // Skip declarations, intrinsics, shaders, and non-external linkage
  2226. if (f.isDeclaration() || f.isIntrinsic() ||
  2227. GetHLOpcodeGroup(&f) != HLOpcodeGroup::NotHL ||
  2228. HLM.HasDxilFunctionProps(&f) || HLM.IsPatchConstantShader(&f) ||
  2229. f.getLinkage() != GlobalValue::LinkageTypes::ExternalLinkage)
  2230. continue;
  2231. // Mark non-shader user functions as InternalLinkage
  2232. f.setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  2233. }
  2234. }
  2235. // Now iterate hull shaders and make sure their corresponding patch constant
  2236. // functions are marked ExternalLinkage:
  2237. for (Function &f : M.functions()) {
  2238. if (f.isDeclaration() || f.isIntrinsic() ||
  2239. GetHLOpcodeGroup(&f) != HLOpcodeGroup::NotHL ||
  2240. f.getLinkage() != GlobalValue::LinkageTypes::ExternalLinkage ||
  2241. !HLM.HasDxilFunctionProps(&f))
  2242. continue;
  2243. DxilFunctionProps &props = HLM.GetDxilFunctionProps(&f);
  2244. if (!props.IsHS())
  2245. continue;
  2246. Function *PCFunc = props.ShaderProps.HS.patchConstantFunc;
  2247. if (PCFunc->getLinkage() != GlobalValue::LinkageTypes::ExternalLinkage)
  2248. PCFunc->setLinkage(GlobalValue::LinkageTypes::ExternalLinkage);
  2249. }
  2250. // Disallow resource arguments in (non-entry) function exports
  2251. // unless offline linking target.
  2252. if (bIsLib &&
  2253. HLM.GetShaderModel()->GetMinor() != ShaderModel::kOfflineMinor) {
  2254. CheckResourceParameters(HLM, CGM);
  2255. }
  2256. }
  2257. void FinishEntries(
  2258. HLModule &HLM, const EntryFunctionInfo &Entry,
  2259. clang::CodeGen::CodeGenModule &CGM,
  2260. StringMap<EntryFunctionInfo> &entryFunctionMap,
  2261. std::unordered_map<Function *, const clang::HLSLPatchConstantFuncAttr *>
  2262. &HSEntryPatchConstantFuncAttr,
  2263. StringMap<PatchConstantInfo> &patchConstantFunctionMap,
  2264. std::unordered_map<Function *, std::unique_ptr<DxilFunctionProps>>
  2265. &patchConstantFunctionPropsMap) {
  2266. bool bIsLib = HLM.GetShaderModel()->IsLib();
  2267. // Library don't have entry.
  2268. if (!bIsLib) {
  2269. SetEntryFunction(HLM, Entry.Func, CGM);
  2270. // If at this point we haven't determined the entry function it's an error.
  2271. if (HLM.GetEntryFunction() == nullptr) {
  2272. assert(CGM.getDiags().hasErrorOccurred() &&
  2273. "else SetEntryFunction should have reported this condition");
  2274. return;
  2275. }
  2276. // In back-compat mode (with /Gec flag) create a static global for each
  2277. // const global to allow writing to it.
  2278. // TODO: Verfiy the behavior of static globals in hull shader
  2279. if (CGM.getLangOpts().EnableDX9CompatMode &&
  2280. CGM.getLangOpts().HLSLVersion <= 2016)
  2281. CreateWriteEnabledStaticGlobals(HLM.GetModule(), HLM.GetEntryFunction());
  2282. if (HLM.GetShaderModel()->IsHS()) {
  2283. SetPatchConstantFunction(Entry, HSEntryPatchConstantFuncAttr,
  2284. patchConstantFunctionMap,
  2285. patchConstantFunctionPropsMap, HLM, CGM);
  2286. }
  2287. } else {
  2288. for (auto &it : entryFunctionMap) {
  2289. // skip clone if RT entry
  2290. if (HLM.GetDxilFunctionProps(it.second.Func).IsRay())
  2291. continue;
  2292. // TODO: change flattened function names to dx.entry.<name>:
  2293. // std::string entryName = (Twine(dxilutil::EntryPrefix) +
  2294. // it.getKey()).str();
  2295. CloneShaderEntry(it.second.Func, it.getKey(), HLM);
  2296. auto AttrIter = HSEntryPatchConstantFuncAttr.find(it.second.Func);
  2297. if (AttrIter != HSEntryPatchConstantFuncAttr.end()) {
  2298. SetPatchConstantFunctionWithAttr(
  2299. it.second, AttrIter->second, patchConstantFunctionMap,
  2300. patchConstantFunctionPropsMap, HLM, CGM);
  2301. }
  2302. }
  2303. }
  2304. }
  2305. } // namespace
  2306. namespace CGHLSLMSHelper {
  2307. void FinishIntrinsics(
  2308. HLModule &HLM, std::vector<std::pair<Function *, unsigned>> &intrinsicMap,
  2309. DenseMap<Value *, DxilResourceProperties> &valToResPropertiesMap) {
  2310. // Lower getResourceHeap before AddOpcodeParamForIntrinsics to skip automatic
  2311. // lower for getResourceFromHeap.
  2312. LowerGetResourceFromHeap(HLM, intrinsicMap);
  2313. // translate opcode into parameter for intrinsic functions
  2314. // Do this before CloneShaderEntry and TranslateRayQueryConstructor to avoid
  2315. // update valToResPropertiesMap for cloned inst.
  2316. AddOpcodeParamForIntrinsics(HLM, intrinsicMap, valToResPropertiesMap);
  2317. }
  2318. // Add the dx.break temporary intrinsic and create Call Instructions
  2319. // to it for each branch that requires the artificial conditional.
  2320. void AddDxBreak(Module &M, const SmallVector<llvm::BranchInst*, 16> &DxBreaks) {
  2321. if (DxBreaks.empty())
  2322. return;
  2323. // Collect functions that make use of any wave operations
  2324. // Only they will need the dx.break condition added
  2325. SmallPtrSet<Function *, 16> WaveUsers;
  2326. for (Function &F : M.functions()) {
  2327. HLOpcodeGroup opgroup = hlsl::GetHLOpcodeGroup(&F);
  2328. if (F.isDeclaration() && IsHLWaveSensitive(&F) &&
  2329. (opgroup == HLOpcodeGroup::HLIntrinsic || opgroup == HLOpcodeGroup::HLExtIntrinsic)) {
  2330. for (User *U : F.users()) {
  2331. CallInst *CI = cast<CallInst>(U);
  2332. WaveUsers.insert(CI->getParent()->getParent());
  2333. }
  2334. }
  2335. }
  2336. // If there are no wave users, not even the function declaration is needed
  2337. if (WaveUsers.empty())
  2338. return;
  2339. // Create the dx.break function
  2340. FunctionType *FT = llvm::FunctionType::get(llvm::Type::getInt1Ty(M.getContext()), false);
  2341. Function *func = cast<llvm::Function>(M.getOrInsertFunction(DXIL::kDxBreakFuncName, FT));
  2342. func->addFnAttr(Attribute::AttrKind::NoUnwind);
  2343. // For all break branches recorded previously, if the function they are in makes
  2344. // any use of a wave op, it may need to be artificially conditional. Make it so now.
  2345. // The CleanupDxBreak pass will remove those that aren't needed when more is known.
  2346. for(llvm::BranchInst *BI : DxBreaks) {
  2347. if (WaveUsers.count(BI->getParent()->getParent())) {
  2348. CallInst *Call = CallInst::Create(FT, func, ArrayRef<Value *>(), "", BI);
  2349. BI->setCondition(Call);
  2350. }
  2351. }
  2352. }
  2353. }