CGHLSLMSFinishCodeGen.cpp 93 KB

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