2
0

StateFunctionTransform.cpp 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778
  1. #include "StateFunctionTransform.h"
  2. #include "llvm/IR/CFG.h"
  3. #include "llvm/IR/Constants.h"
  4. #include "llvm/IR/InstIterator.h"
  5. #include "llvm/IR/Instructions.h"
  6. #include "llvm/IR/LegacyPassManager.h"
  7. #include "llvm/IR/PassManager.h"
  8. #include "llvm/IR/ValueMap.h"
  9. #include "llvm/IR/Verifier.h"
  10. #include "llvm/Support/FileSystem.h"
  11. #include "llvm/Transforms/Scalar.h"
  12. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  13. #include "llvm/Transforms/Utils/Cloning.h"
  14. #include "llvm/Transforms/Utils/Local.h"
  15. #include "FunctionBuilder.h"
  16. #include "LiveValues.h"
  17. #include "LLVMUtils.h"
  18. #include "Reducibility.h"
  19. #define DBGS dbgs
  20. //#define DBGS errs
  21. using namespace llvm;
  22. static const char* CALL_INDIRECT_NAME = "\x1?Fallback_CallIndirect@@YAXH@Z";
  23. static const char* SET_PENDING_ATTR_PREFIX = "\x1?Fallback_SetPendingAttr@@";
  24. // Create a string with printf-like arguments
  25. inline std::string stringf(const char* fmt, ...)
  26. {
  27. va_list args;
  28. va_start(args, fmt);
  29. #ifdef WIN32
  30. int size = _vscprintf(fmt, args);
  31. #else
  32. int size = vsnprintf(0, 0, fmt, args);
  33. #endif
  34. va_end(args);
  35. std::string ret;
  36. if (size > 0)
  37. {
  38. ret.resize(size);
  39. va_start(args, fmt);
  40. vsnprintf(const_cast<char*>(ret.data()), size + 1, fmt, args);
  41. va_end(args);
  42. }
  43. return ret;
  44. }
  45. // Remove ELF mangling
  46. static std::string cleanName(StringRef name)
  47. {
  48. if (!name.startswith("\x1?"))
  49. return name;
  50. size_t pos = name.find("@@");
  51. if (pos == name.npos)
  52. return name;
  53. std::string newName = name.substr(2, pos - 2);
  54. return newName;
  55. }
  56. // Utility to append the suffix to the name of the value, but returns
  57. // an empty string if name is empty. This is to avoid names like ".ptr".
  58. static std::string addSuffix(StringRef valueName, StringRef suffix)
  59. {
  60. if (!valueName.empty())
  61. {
  62. if (valueName.back() == '.' && suffix.front() == '.') // avoid double dots
  63. return (valueName + suffix.substr(1)).str();
  64. else
  65. return (valueName + suffix).str();
  66. }
  67. else
  68. return valueName.str();
  69. }
  70. // Remove suffix from name.
  71. static std::string stripSuffix(StringRef name, StringRef suffix)
  72. {
  73. size_t pos = name.rfind(suffix);
  74. if (pos != name.npos)
  75. return name.substr(0, pos).str();
  76. else
  77. return name.str();
  78. }
  79. // Insert str before the final "." in filename.
  80. static std::string insertBeforeExtension(const std::string& filename, const std::string& str)
  81. {
  82. std::string ret = filename;
  83. size_t pos = filename.rfind('.');
  84. if (pos != std::string::npos)
  85. ret.insert(pos, str);
  86. else
  87. ret += str;
  88. return ret;
  89. }
  90. // Inserts <functionName>-<id>-<suffix> before the extension in baseName
  91. static std::string createDumpPath(
  92. const std::string& baseName,
  93. unsigned id,
  94. const std::string& suffix,
  95. const std::string& functionName)
  96. {
  97. std::string s;
  98. if (!functionName.empty())
  99. s = "-" + functionName;
  100. s += stringf("-%02d-", id) + suffix;
  101. return insertBeforeExtension(baseName, s);
  102. }
  103. // Return byte offset aligned to the alignment required by inst.
  104. static uint64_t align(uint64_t offset, Instruction* inst, DataLayout& DL)
  105. {
  106. unsigned alignment = 0;
  107. if (AllocaInst* ai = dyn_cast<AllocaInst>(inst))
  108. alignment = ai->getAlignment();
  109. if (alignment == 0)
  110. alignment = DL.getPrefTypeAlignment(inst->getType());
  111. return RoundUpToAlignment(offset, alignment);
  112. }
  113. template <class T> // T can be Value* or Instruction*
  114. T createCastForStack(T ptr, llvm::Type* targetPtrElemType, llvm::Instruction* insertBefore)
  115. {
  116. llvm::PointerType* requiredType = llvm::PointerType::get(targetPtrElemType, ptr->getType()->getPointerAddressSpace());
  117. if (ptr->getType() == requiredType)
  118. return ptr;
  119. return new llvm::BitCastInst(ptr, requiredType, ptr->getName(), insertBefore);
  120. }
  121. static Value* createCastToInt(Value* val, Instruction* insertBefore)
  122. {
  123. Type* i32Ty = Type::getInt32Ty(val->getContext());
  124. if (val->getType() == i32Ty)
  125. return val;
  126. if (val->getType() == Type::getInt1Ty(val->getContext()))
  127. return new ZExtInst(val, i32Ty, addSuffix(val->getName(), ".int"), insertBefore);
  128. Value* intVal = new BitCastInst(val, i32Ty, addSuffix(val->getName(), ".int"), insertBefore);
  129. return intVal;
  130. }
  131. static Value* createCastFromInt(Value* intVal, Type* ty, Instruction* insertBefore)
  132. {
  133. Type* i32Ty = Type::getInt32Ty(intVal->getContext());
  134. if (ty == i32Ty)
  135. return intVal;
  136. std::string name = intVal->getName();
  137. intVal->setName(addSuffix(name, ".int"));
  138. // Create boolean with compare
  139. if (ty == Type::getInt1Ty(intVal->getContext()))
  140. return new ICmpInst(insertBefore, CmpInst::ICMP_SGT, intVal, makeInt32(0, intVal->getContext()), name);
  141. return new BitCastInst(intVal, ty, name, insertBefore);
  142. }
  143. // Gives every value in the given function a name. This can aid in debugging.
  144. static void dbgNameUnnamedVals(Function* func)
  145. {
  146. Type* voidTy = Type::getVoidTy(func->getContext());
  147. for (auto& I : inst_range(func))
  148. {
  149. if (!I.hasName() && I.getType() != voidTy)
  150. I.setName("v"); // LLVM will uniquify the name by adding a numeric suffix
  151. }
  152. }
  153. // Returns an iterator for the instruction after the last alloca in the entry block
  154. // (assuming that allocas are at the top of the entry block).
  155. static BasicBlock::iterator afterEntryBlockAllocas(Function* function)
  156. {
  157. BasicBlock::iterator insertBefore = function->getEntryBlock().begin();
  158. while (isa<AllocaInst>(insertBefore))
  159. ++insertBefore;
  160. return insertBefore;
  161. }
  162. // Return all the blocks reachable from entryBlock.
  163. static BasicBlockVector getReachableBlocks(BasicBlock* entryBlock)
  164. {
  165. BasicBlockVector blocks;
  166. std::deque<BasicBlock*> stack = { entryBlock };
  167. ::BasicBlockSet visited = { entryBlock };
  168. while (!stack.empty())
  169. {
  170. BasicBlock* block = stack.front();
  171. stack.pop_front();
  172. blocks.push_back(block);
  173. TerminatorInst* termInst = block->getTerminator();
  174. for (unsigned int succ = 0, succEnd = termInst->getNumSuccessors(); succ != succEnd; ++succ)
  175. {
  176. BasicBlock* succBlock = termInst->getSuccessor(succ);
  177. if (visited.insert(succBlock).second)
  178. stack.push_front(succBlock);
  179. }
  180. }
  181. return blocks;
  182. }
  183. // Creates a new function with the same arguments and attributes as oldFunction
  184. static Function* cloneFunctionPrototype(const Function* oldFunction, ValueToValueMapTy& VMap)
  185. {
  186. std::vector<Type*> argTypes;
  187. for (auto I = oldFunction->arg_begin(), E = oldFunction->arg_end(); I != E; ++I)
  188. argTypes.push_back(I->getType());
  189. FunctionType* FTy = FunctionType::get(oldFunction->getFunctionType()->getReturnType(), argTypes,
  190. oldFunction->getFunctionType()->isVarArg());
  191. Function* newFunction = Function::Create(FTy, oldFunction->getLinkage(), oldFunction->getName());
  192. Function::arg_iterator destI = newFunction->arg_begin();
  193. for (auto I = oldFunction->arg_begin(), E = oldFunction->arg_end(); I != E; ++I, ++destI)
  194. {
  195. destI->setName(I->getName());
  196. VMap[I] = destI;
  197. }
  198. AttributeSet oldAttrs = oldFunction->getAttributes();
  199. for (auto I = oldFunction->arg_begin(), E = oldFunction->arg_end(); I != E; ++I)
  200. {
  201. if (Argument* Anew = dyn_cast<Argument>(VMap[I]))
  202. {
  203. AttributeSet attrs = oldAttrs.getParamAttributes(I->getArgNo() + 1);
  204. if (attrs.getNumSlots() > 0)
  205. Anew->addAttr(attrs);
  206. }
  207. }
  208. newFunction->setAttributes(newFunction->getAttributes().addAttributes(newFunction->getContext(), AttributeSet::ReturnIndex,
  209. oldAttrs.getRetAttributes()));
  210. newFunction->setAttributes(newFunction->getAttributes().addAttributes(newFunction->getContext(), AttributeSet::FunctionIndex,
  211. oldAttrs.getFnAttributes()));
  212. return newFunction;
  213. }
  214. // Creates a new function by cloning blocks reachable from entryBlock
  215. static Function* cloneBlocksReachableFrom(BasicBlock* entryBlock, ValueToValueMapTy& VMap)
  216. {
  217. Function* oldFunction = entryBlock->getParent();
  218. Function* newFunction = cloneFunctionPrototype(oldFunction, VMap);
  219. // Insert a clone of the entry block into the function.
  220. BasicBlock* newEntry = CloneBasicBlock(entryBlock, VMap, "", newFunction);
  221. VMap[entryBlock] = newEntry;
  222. // Clone all other blocks.
  223. BasicBlockVector blocks = getReachableBlocks(entryBlock);
  224. for (auto block : blocks)
  225. {
  226. if (block == entryBlock)
  227. continue;
  228. BasicBlock* clonedBlock = CloneBasicBlock(block, VMap, "", newFunction);
  229. VMap[block] = clonedBlock;
  230. }
  231. // Remap new instructions to reference blocks and instructions of the new function.
  232. for (auto block : blocks)
  233. {
  234. auto clonedBlock = cast<BasicBlock>(VMap[block]);
  235. for (BasicBlock::iterator I = clonedBlock->begin(); I != clonedBlock->end(); ++I)
  236. {
  237. RemapInstruction(I, VMap, RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
  238. }
  239. }
  240. // Remove phi operands incoming from blocks that are not present in the new function anymore.
  241. for (auto& block : *newFunction)
  242. {
  243. PHINode* firstPHI = dyn_cast<PHINode>(block.begin());
  244. if (firstPHI == nullptr)
  245. continue; // phi instructions only at beginning
  246. // Create set of actual predecessors
  247. BasicBlockSet preds(pred_begin(&block), pred_end(&block));
  248. if (preds.size() == firstPHI->getNumIncomingValues())
  249. continue;
  250. // Remove phi incoming blocks not in preds
  251. for (auto iter = block.begin(); isa<PHINode>(iter); ++iter)
  252. {
  253. std::vector<unsigned int> toRemove;
  254. PHINode* phi = cast<PHINode>(iter);
  255. for (unsigned int op = 0, opEnd = phi->getNumIncomingValues(); op != opEnd; ++op)
  256. {
  257. BasicBlock* pred = phi->getIncomingBlock(op);
  258. if (preds.count(pred) == 0)
  259. {
  260. toRemove.push_back(op);
  261. }
  262. }
  263. for (auto I = toRemove.rbegin(), E = toRemove.rend(); I != E; ++I)
  264. phi->removeIncomingValue(*I, false);
  265. }
  266. }
  267. return newFunction;
  268. }
  269. // Replace and remove calls to func with val
  270. static void replaceValAndRemoveUnusedDummyFunc(Value* oldVal, Value* newVal, Function* caller)
  271. {
  272. CallInst* call = dyn_cast<CallInst>(oldVal);
  273. assert(call != nullptr && "Must be a call");
  274. Function* func = call->getCalledFunction();
  275. for (CallInst* CI : getCallsToFunction(func, caller))
  276. {
  277. CI->replaceAllUsesWith(newVal);
  278. CI->eraseFromParent();
  279. }
  280. if (func->getNumUses() == 0)
  281. func->eraseFromParent();
  282. }
  283. // Get the integer value of val. If val is not a ConstantInt return false.
  284. static bool getConstantValue(int& constant, const Value* val)
  285. {
  286. const ConstantInt* CI = dyn_cast<ConstantInt>(val);
  287. if (!CI)
  288. return false;
  289. if (CI->getBitWidth() > 32)
  290. return false;
  291. constant = static_cast<int>(CI->getSExtValue());
  292. return true;
  293. }
  294. static int getConstantValue(const Value* val)
  295. {
  296. const ConstantInt* CI = dyn_cast<ConstantInt>(val);
  297. assert(CI && CI->getBitWidth() <= 32);
  298. return static_cast<int>(CI->getSExtValue());
  299. }
  300. struct StoreInfo
  301. {
  302. Function* stackIntPtrFunc;
  303. Value* runtimeDataArg;
  304. Value* baseOffset;
  305. Instruction* insertBefore;
  306. Value* val;
  307. std::vector<Value*> idxList;
  308. };
  309. // Takes the offset at which to store the next value.
  310. // Returns the next available offset.
  311. static int store(int offset, StoreInfo& SI, Type* ty)
  312. {
  313. if (StructType* STy = dyn_cast<StructType>(ty))
  314. {
  315. SI.idxList.push_back(nullptr);
  316. int elIdx = 0;
  317. for (auto& elTy : STy->elements())
  318. {
  319. SI.idxList.back() = makeInt32(elIdx++, ty->getContext());
  320. offset = store(offset, SI, elTy);
  321. }
  322. SI.idxList.pop_back();
  323. }
  324. else if (ArrayType* ATy = dyn_cast<ArrayType>(ty))
  325. {
  326. Type* elTy = ATy->getArrayElementType();
  327. SI.idxList.push_back(nullptr);
  328. for (int elIdx = 0; elIdx < (int)ATy->getArrayNumElements(); ++elIdx)
  329. {
  330. SI.idxList.back() = makeInt32(elIdx, ty->getContext());
  331. offset = store(offset, SI, elTy);
  332. }
  333. SI.idxList.pop_back();
  334. }
  335. else if (PointerType* PTy = dyn_cast<PointerType>(ty))
  336. {
  337. SI.idxList.push_back(makeInt32(0, ty->getContext()));
  338. offset = store(offset, SI, PTy->getPointerElementType());
  339. SI.idxList.pop_back();
  340. }
  341. else
  342. {
  343. Value* val = SI.val;
  344. if (!SI.idxList.empty())
  345. {
  346. Value* gep = GetElementPtrInst::CreateInBounds(SI.val, SI.idxList, "", SI.insertBefore);
  347. val = new LoadInst(gep, "", SI.insertBefore);
  348. }
  349. if (VectorType* VTy = dyn_cast<VectorType>(ty))
  350. {
  351. std::vector<Value*>idxList = std::move(SI.idxList);
  352. Type* elTy = VTy->getVectorElementType();
  353. for (int elIdx = 0; elIdx < (int)VTy->getVectorNumElements(); ++elIdx)
  354. {
  355. Value* idxVal = makeInt32(elIdx, ty->getContext());
  356. Value* el = ExtractElementInst::Create(val, idxVal, "", SI.insertBefore);
  357. SI.val = el;
  358. offset = store(offset, SI, elTy);
  359. }
  360. SI.idxList = std::move(idxList);
  361. }
  362. else
  363. {
  364. Value* idxVal = makeInt32(offset, val->getContext());
  365. Value* intVal = createCastToInt(val, SI.insertBefore);
  366. Value* intPtr = CallInst::Create(SI.stackIntPtrFunc, { SI.runtimeDataArg, SI.baseOffset, idxVal }, addSuffix(val->getName(), ".ptr"), SI.insertBefore);
  367. new StoreInst(intVal, intPtr, SI.insertBefore);
  368. offset += 1;
  369. }
  370. }
  371. return offset;
  372. }
  373. // Store value to the stack at given baseOffset + offset. Will flatten aggregates and vectors.
  374. // Returns the offset where writing left off. For pointer vals stores what is pointed to.
  375. static int store(Value* val, Function* stackIntPtrFunc, Value* runtimeDataArg, Value* baseOffset, int offset, Instruction* insertBefore)
  376. {
  377. StoreInfo SI;
  378. SI.stackIntPtrFunc = stackIntPtrFunc;
  379. SI.runtimeDataArg = runtimeDataArg;
  380. SI.baseOffset = baseOffset;
  381. SI.insertBefore = insertBefore;
  382. SI.val = val;
  383. return store(offset, SI, val->getType());
  384. }
  385. static Value* load(llvm::Function* m_stackIntPtrFunc, Value* runtimeDataArg, Value* offset, Value* idx, const std::string& name, Type* ty, Instruction* insertBefore)
  386. {
  387. if (VectorType* VTy = dyn_cast<VectorType>(ty))
  388. {
  389. LLVMContext& C = ty->getContext();
  390. int baseIdx = getConstantValue(idx);
  391. Type* elTy = VTy->getVectorElementType();
  392. Value* vec = UndefValue::get(VTy);
  393. for (int i = 0; i < (int)VTy->getVectorNumElements(); ++i)
  394. {
  395. std::string elName = stringf("el%d.", i);
  396. Value* intPtr = CallInst::Create(m_stackIntPtrFunc, { runtimeDataArg, offset, makeInt32(baseIdx + i, C) }, elName + "ptr", insertBefore);
  397. Value* intEl = new LoadInst(intPtr, elName, insertBefore);
  398. Value* el = createCastFromInt(intEl, elTy, insertBefore);
  399. vec = InsertElementInst::Create(vec, el, makeInt32(i, C), "tmpvec", insertBefore);
  400. }
  401. vec->setName(name);
  402. return vec;
  403. }
  404. else
  405. {
  406. Value* intPtr = CallInst::Create(m_stackIntPtrFunc, { runtimeDataArg, offset, idx }, addSuffix(name, ".ptr"), insertBefore);
  407. Value* intVal = new LoadInst(intPtr, name, insertBefore);
  408. Value* val = createCastFromInt(intVal, ty, insertBefore);
  409. return val;
  410. }
  411. }
  412. static void reg2Mem(DenseMap<Instruction*, AllocaInst*>& valToAlloca, DenseMap<AllocaInst*, Instruction*>& allocaToVal, Instruction* inst)
  413. {
  414. if (valToAlloca.count(inst))
  415. return;
  416. // Convert the value to an alloca
  417. AllocaInst* allocaPtr = DemoteRegToStack(*inst, false);
  418. if (allocaPtr)
  419. {
  420. valToAlloca[inst] = allocaPtr;
  421. allocaToVal[allocaPtr] = inst;
  422. }
  423. }
  424. // Utility class for rematerializing values at a callsite
  425. class Rematerializer
  426. {
  427. public:
  428. Rematerializer(
  429. DenseMap<AllocaInst*, Instruction*>& allocaToVal,
  430. const InstructionSetVector& liveHere,
  431. const std::set<Value*>& resources
  432. )
  433. : m_allocaToVal(allocaToVal)
  434. , m_liveHere(liveHere)
  435. , m_resources(resources)
  436. {}
  437. // Returns true if inst can be rematerialized.
  438. bool canRematerialize(Instruction* inst)
  439. {
  440. if (CallInst* call = dyn_cast<CallInst>(inst))
  441. {
  442. StringRef funcName = call->getCalledFunction()->getName();
  443. if (funcName.startswith("dummyStackFrameSize"))
  444. return true;
  445. if (funcName.startswith("stack.ptr"))
  446. return true;
  447. if (funcName.startswith("stack.load"))
  448. return true;
  449. if (funcName.startswith("dx.op.createHandle"))
  450. return true;
  451. }
  452. else if (LoadInst* load = dyn_cast<LoadInst>(inst))
  453. {
  454. Value* op = load->getOperand(0);
  455. if (GetElementPtrInst* gep = dyn_cast<GetElementPtrInst>(op)) // for descriptor tables
  456. op = gep->getOperand(0);
  457. if (m_resources.count(op))
  458. return true;
  459. }
  460. else if (GetElementPtrInst* gep = dyn_cast<GetElementPtrInst>(inst))
  461. {
  462. assert(gep->hasAllConstantIndices() && "Unhandled non-constant index"); // Should have been changed to stack.ptr
  463. return true;
  464. }
  465. return false;
  466. }
  467. // Rematerialize the given instruction and its dependency graph, adding
  468. // any nonrematerializable values that are live in the function, but not
  469. // at this callsite to the work list to insure that their values are restored.
  470. Instruction* rematerialize(Instruction* inst, std::vector<Instruction *> workList, Instruction* insertBefore, int depth = 0)
  471. {
  472. // Signal if we hit a complex case. Deep rematerialization needs more analysis.
  473. // To make this robust we would need to make it possible to run the current
  474. // value through the live value handling pipeline: figure out where it is live,
  475. // reg2mem, save/restore at appropriate callsites, etc.
  476. assert(depth < 8);
  477. // Reuse an already rematerialized value?
  478. auto it = m_rematMap.find(inst);
  479. if (it != m_rematMap.end())
  480. return it->second;
  481. // Handle allocas
  482. if (AllocaInst* alloc = dyn_cast<AllocaInst>(inst))
  483. {
  484. assert(depth > 0); // Should only be an operand to another rematerialized value
  485. auto it = m_allocaToVal.find(alloc);
  486. if (it != m_allocaToVal.end()) // Is it a value that is live at some callsite (and reg2mem'd)?
  487. {
  488. Instruction* val = it->second;
  489. if (canRematerialize(val))
  490. {
  491. // Rematerialize here and store to the alloca. We may have already rematerialized a load
  492. // from the alloca. Any future uses will use the rematerialized value directly.
  493. Instruction* remat = rematerialize(val, workList, insertBefore, depth + 1);
  494. new StoreInst(remat, alloc, insertBefore);
  495. }
  496. else
  497. {
  498. // Value has to be restored, but it rematerialization may have extended
  499. // the liveness of this value to this callsite. Make sure it gets restored.
  500. if (!m_liveHere.count(val))
  501. workList.push_back(val);
  502. }
  503. }
  504. // Allocas are not cloned.
  505. return inst;
  506. }
  507. Instruction* clone = inst->clone();
  508. clone->setName(addSuffix(inst->getName(), ".remat"));
  509. for (unsigned i = 0; i < inst->getNumOperands(); ++i)
  510. {
  511. Value* op = inst->getOperand(i);
  512. if (Instruction* opInst = dyn_cast<Instruction>(op))
  513. clone->setOperand(i, rematerialize(opInst, workList, insertBefore, depth + 1));
  514. else
  515. clone->setOperand(i, op);
  516. }
  517. clone->insertBefore(insertBefore); // insert after any instructions cloned for operands
  518. m_rematMap[inst] = clone;
  519. return clone;
  520. }
  521. Instruction* getRematerializedValueFor(Instruction* val)
  522. {
  523. auto it = m_rematMap.find(val);
  524. if (it != m_rematMap.end())
  525. return it->second;
  526. else
  527. return nullptr;
  528. }
  529. private:
  530. DenseMap<Instruction*, Instruction*> m_rematMap; // Map instructions to their rematerialized counterparts
  531. DenseMap<AllocaInst*, Instruction*>& m_allocaToVal; // Map allocas for reg2mem'd live values back to the value
  532. const InstructionSetVector& m_liveHere; // Values live at this callsite
  533. const std::set<Value*>& m_resources; // Values for resources like SRVs, UAVs, etc.
  534. };
  535. StateFunctionTransform::StateFunctionTransform(Function* func, const std::vector<std::string>& candidateFuncNames, Type* runtimeDataArgTy)
  536. : m_function(func)
  537. , m_candidateFuncNames(candidateFuncNames)
  538. , m_runtimeDataArgTy(runtimeDataArgTy)
  539. {
  540. m_functionName = cleanName(m_function->getName());
  541. auto it = std::find(m_candidateFuncNames.begin(), m_candidateFuncNames.end(), m_functionName);
  542. assert(it != m_candidateFuncNames.end());
  543. m_functionIdx = it - m_candidateFuncNames.begin();
  544. }
  545. void StateFunctionTransform::setAttributeSize(int size)
  546. {
  547. m_attributeSizeInBytes = size;
  548. }
  549. void StateFunctionTransform::setParameterInfo(const std::vector<ParameterSemanticType>& paramTypes, bool useCommittedAttr)
  550. {
  551. m_paramTypes = paramTypes;
  552. m_useCommittedAttr = useCommittedAttr;
  553. }
  554. void StateFunctionTransform::setResourceGlobals(const std::set<llvm::Value*>& resources)
  555. {
  556. m_resources = &resources;
  557. }
  558. Function* StateFunctionTransform::createDummyRuntimeDataArgFunc(Module* mod, Type* runtimeDataArgTy)
  559. {
  560. return FunctionBuilder(mod, "dummyRuntimeDataArg").type(runtimeDataArgTy).build();
  561. }
  562. void StateFunctionTransform::setVerbose(bool val)
  563. {
  564. m_verbose = val;
  565. }
  566. void StateFunctionTransform::setDumpFilename(const std::string& dumpFilename)
  567. {
  568. m_dumpFilename = dumpFilename;
  569. }
  570. void StateFunctionTransform::run(std::vector<Function*>& stateFunctions, _Out_ unsigned int &shaderStackSize)
  571. {
  572. printFunction("Initial");
  573. init();
  574. printFunction("AfterInit");
  575. changeCallingConvention();
  576. printFunction("AfterCallingConvention");
  577. preserveLiveValuesAcrossCallsites(shaderStackSize);
  578. printFunction("AfterPreserveLiveValues");
  579. createSubstateFunctions(stateFunctions);
  580. printFunctions(stateFunctions, "AfterSubstateFunctions");
  581. lowerStackFuncs();
  582. printFunctions(stateFunctions, "AfterLowerStackFuncs");
  583. }
  584. void StateFunctionTransform::finalizeStateIds(llvm::Module* mod, const std::vector<int>& candidateFuncEntryStateIds)
  585. {
  586. LLVMContext& context = mod->getContext();
  587. Function* func = mod->getFunction("dummyStateId");
  588. if (!func)
  589. return;
  590. std::vector<Instruction*> toRemove;
  591. for (User* U : func->users())
  592. {
  593. CallInst* call = dyn_cast<CallInst>(U);
  594. if (!call)
  595. continue;
  596. int functionIdx = 0;
  597. int substate = 0;
  598. getConstantValue(functionIdx, call->getArgOperand(0));
  599. getConstantValue(substate, call->getArgOperand(1));
  600. int stateId = candidateFuncEntryStateIds[functionIdx] + substate;
  601. call->replaceAllUsesWith(makeInt32(stateId, context));
  602. toRemove.push_back(call);
  603. }
  604. for (Instruction* v : toRemove)
  605. v->eraseFromParent();
  606. func->eraseFromParent();
  607. }
  608. void StateFunctionTransform::init()
  609. {
  610. Module* mod = m_function->getParent();
  611. m_function->setName(cleanName(m_function->getName()));
  612. // Run preparatory passes
  613. runPasses(m_function, {
  614. //createBreakCriticalEdgesPass(),
  615. //createLoopSimplifyPass(),
  616. //createLCSSAPass(),
  617. createPromoteMemoryToRegisterPass()
  618. });
  619. // Make debugging a little easier by giving things names
  620. dbgNameUnnamedVals(m_function);
  621. findCallSitesIntrinsicsAndReturns();
  622. // Create a bunch of functions that we are going to need
  623. m_stackIntPtrFunc = FunctionBuilder(mod, "stackIntPtr").i32Ptr().type(m_runtimeDataArgTy, "runtimeData").i32("baseOffset").i32("offset").build();
  624. Instruction* insertBefore = afterEntryBlockAllocas(m_function);
  625. Function* runtimeDataArgFunc = createDummyRuntimeDataArgFunc(mod, m_runtimeDataArgTy);
  626. m_runtimeDataArg = CallInst::Create(runtimeDataArgFunc, "runtimeData", insertBefore);
  627. Function* stackFrameSizeFunc = FunctionBuilder(mod, "dummyStackFrameSize").i32().build();
  628. m_stackFrameSizeVal = CallInst::Create(stackFrameSizeFunc, "stackFrame.size", insertBefore);
  629. // TODO only create the values that are actually needed
  630. Function* payloadOffsetFunc = FunctionBuilder(mod, "payloadOffset").i32().type(m_runtimeDataArgTy, "runtimeData").build();
  631. m_payloadOffset = CallInst::Create(payloadOffsetFunc, { m_runtimeDataArg }, "payload.offset", insertBefore);
  632. Function* committedAttrOffsetFunc = FunctionBuilder(mod, "committedAttrOffset").i32().type(m_runtimeDataArgTy, "runtimeData").build();
  633. m_committedAttrOffset = CallInst::Create(committedAttrOffsetFunc, { m_runtimeDataArg }, "committedAttr.offset", insertBefore);
  634. Function* pendingAttrOffsetFunc = FunctionBuilder(mod, "pendingAttrOffset").i32().type(m_runtimeDataArgTy, "runtimeData").build();
  635. m_pendingAttrOffset = CallInst::Create(pendingAttrOffsetFunc, { m_runtimeDataArg }, "pendingAttr.offset", insertBefore);
  636. Function* stackFrameOffsetFunc = FunctionBuilder(mod, "stackFrameOffset").i32().type(m_runtimeDataArgTy, "runtimeData").build();
  637. m_stackFrameOffset = CallInst::Create(stackFrameOffsetFunc, { m_runtimeDataArg }, "stackFrame.offset", insertBefore);
  638. // lower SetPendingAttr() now
  639. for (CallInst* call : m_setPendingAttrCalls)
  640. {
  641. // Get the current pending attribute offset. It can change when a hit is committed
  642. Instruction* insertBefore = call;
  643. Value* currentPendingAttrOffset = CallInst::Create(pendingAttrOffsetFunc, { m_runtimeDataArg }, "cur.pendingAttr.offset", insertBefore);
  644. Value* attr = call->getArgOperand(0);
  645. createStackStore(currentPendingAttrOffset, attr, 0, insertBefore);
  646. call->eraseFromParent();
  647. }
  648. }
  649. void StateFunctionTransform::findCallSitesIntrinsicsAndReturns()
  650. {
  651. // Create a map for log N lookup
  652. std::map<std::string, int> candidateFuncMap;
  653. for (int i = 0; i < (int)m_candidateFuncNames.size(); ++i)
  654. candidateFuncMap[m_candidateFuncNames[i]] = i;
  655. for (auto& I : inst_range(m_function))
  656. {
  657. if (CallInst* call = dyn_cast<CallInst>(&I))
  658. {
  659. StringRef calledFuncName = call->getCalledFunction()->getName();
  660. if (calledFuncName.startswith(SET_PENDING_ATTR_PREFIX))
  661. m_setPendingAttrCalls.push_back(call);
  662. else if (calledFuncName.startswith("movePayloadToStack"))
  663. m_movePayloadToStackCalls.push_back(call);
  664. else if (calledFuncName == CALL_INDIRECT_NAME)
  665. m_callSites.push_back(call);
  666. else
  667. {
  668. auto it = candidateFuncMap.find(cleanName(calledFuncName));
  669. if (it == candidateFuncMap.end())
  670. continue;
  671. assert(call->getCalledFunction()->getReturnType() == Type::getVoidTy(call->getContext()) && "Continuations with returns not supported");
  672. m_callSites.push_back(call);
  673. m_callSiteFunctionIdx.push_back(it->second);
  674. }
  675. }
  676. else if (ReturnInst* ret = dyn_cast<ReturnInst>(&I))
  677. {
  678. m_returns.push_back(ret);
  679. }
  680. }
  681. }
  682. void StateFunctionTransform::changeCallingConvention()
  683. {
  684. if (!m_callSites.empty() || m_attributeSizeInBytes >= 0)
  685. allocateStackFrame();
  686. if (m_attributeSizeInBytes >= 0)
  687. allocateTraceFrame();
  688. createArgFrames();
  689. changeFunctionSignature();
  690. }
  691. static bool isCallToStackPtr(Value* inst)
  692. {
  693. CallInst* call = dyn_cast<CallInst>(inst);
  694. if (call && call->getCalledFunction()->getName().startswith("stack.ptr"))
  695. return true;
  696. return false;
  697. }
  698. static void extendAllocaLifetimes(LiveValues& lv)
  699. {
  700. for (Instruction* inst : lv.getAllLiveValues())
  701. {
  702. if (!inst->getType()->isPointerTy())
  703. continue;
  704. if (isa<AllocaInst>(inst) || isCallToStackPtr(inst))
  705. continue;
  706. GetElementPtrInst* gep = dyn_cast<GetElementPtrInst>(inst);
  707. assert(gep && "Unhandled live pointer");
  708. Value* ptr = gep->getPointerOperand();
  709. if (isCallToStackPtr(ptr))
  710. continue;
  711. AllocaInst* alloc = dyn_cast<AllocaInst>(gep->getPointerOperand());
  712. assert(alloc && "GEP of non-alloca pointer");
  713. // TODO: We need to set indices of the uses of the gep, not the gep itself
  714. const LiveValues::Indices* gepIndices = lv.getIndicesWhereLive(gep);
  715. const LiveValues::Indices* allocIndices = lv.getIndicesWhereLive(alloc);
  716. if (!allocIndices || *allocIndices != *gepIndices)
  717. lv.setIndicesWhereLive(alloc, gepIndices);
  718. }
  719. }
  720. void StateFunctionTransform::preserveLiveValuesAcrossCallsites(_Out_ unsigned int &shaderStackSize)
  721. {
  722. if (m_callSites.empty())
  723. {
  724. // No stack frame. Nothing to do.
  725. rewriteDummyStackSize(0);
  726. return;
  727. }
  728. SetVector<Instruction*> stackOffsets;
  729. stackOffsets.insert(m_stackFrameOffset);
  730. if (m_payloadOffset && !m_payloadOffset->user_empty())
  731. stackOffsets.insert(m_payloadOffset);
  732. if (m_committedAttrOffset && !m_committedAttrOffset->user_empty())
  733. stackOffsets.insert(m_committedAttrOffset);
  734. if (m_pendingAttrOffset && !m_pendingAttrOffset->user_empty())
  735. stackOffsets.insert(m_pendingAttrOffset);
  736. // Do liveness analysis
  737. ArrayRef<Instruction*> instructions((Instruction**)m_callSites.data(), m_callSites.size());
  738. LiveValues lv(instructions);
  739. lv.run();
  740. // Make sure alloca lifetimes match their uses
  741. extendAllocaLifetimes(lv);
  742. // Make sure stack offsets get included
  743. for (auto o : stackOffsets)
  744. lv.setLiveAtAllIndices(o, true);
  745. // Add payload allocas, if any
  746. for (CallInst* call : m_movePayloadToStackCalls)
  747. {
  748. if (AllocaInst* payloadAlloca = dyn_cast<AllocaInst>(call->getArgOperand(0)))
  749. lv.setLiveAtAllIndices(payloadAlloca, true);
  750. }
  751. printSet(lv.getAllLiveValues(), "live values");
  752. //
  753. // Carve up the stack frame.
  754. //
  755. uint64_t offsetInBytes = 0;
  756. // ... argument frame
  757. offsetInBytes += m_maxCallerArgFrameSizeInBytes;
  758. // ... live allocas.
  759. Module* mod = m_function->getParent();
  760. DataLayout DL(mod);
  761. DenseMap<Instruction*, Instruction*> allocaToStack;
  762. Instruction* insertBefore = getInstructionAfter(m_stackFrameOffset);
  763. for (Instruction* inst : lv.getAllLiveValues())
  764. {
  765. AllocaInst* alloc = dyn_cast<AllocaInst>(inst);
  766. if (!alloc)
  767. continue;
  768. // Allocate a slot in the stack frame for the alloca
  769. offsetInBytes = align(offsetInBytes, inst, DL);
  770. Instruction* stackAlloca = createStackPtr(m_stackFrameOffset, alloc, offsetInBytes, insertBefore);
  771. alloc->replaceAllUsesWith(stackAlloca);
  772. allocaToStack[inst] = stackAlloca;
  773. offsetInBytes += DL.getTypeAllocSize(alloc->getAllocatedType());
  774. }
  775. lv.remapLiveValues(allocaToStack); // replace old allocas with stackAllocas
  776. for (auto& kv : allocaToStack)
  777. kv.first->eraseFromParent(); // delete old allocas
  778. // Set payload offsets now that they are all on the stack
  779. for (CallInst* call : m_movePayloadToStackCalls)
  780. {
  781. CallInst* payloadStackPtr = dyn_cast<CallInst>(call->getArgOperand(0));
  782. assert(payloadStackPtr->getCalledFunction()->getName().startswith("stack.ptr"));
  783. Value* baseOffset = payloadStackPtr->getArgOperand(0);
  784. Value* idx = payloadStackPtr->getArgOperand(1);
  785. Value* payloadOffset = BinaryOperator::Create(Instruction::Add, baseOffset, idx, "", call);
  786. call->replaceAllUsesWith(payloadOffset);
  787. payloadOffset->takeName(call);
  788. call->eraseFromParent();
  789. }
  790. //printFunction("AfterStackAllocas");
  791. // ... saves/restores for each call site
  792. // Create allocas for live values. This makes it easier to generate code because
  793. // we don't have to maintain the use-def chains of SSA form. We can just
  794. // load/store from/to the alloca for a particular value. A subsequent mem2reg
  795. // pass will rebuild the SSA form.
  796. DenseMap<Instruction*, AllocaInst*> valToAlloca;
  797. DenseMap<AllocaInst*, Instruction*> allocaToVal;
  798. for (Instruction* inst : lv.getAllLiveValues())
  799. reg2Mem(valToAlloca, allocaToVal, inst);
  800. //printFunction("AfterReg2Mem");
  801. uint64_t baseOffsetInBytes = offsetInBytes;
  802. uint64_t maxOffsetInBytes = offsetInBytes;
  803. for (size_t i = 0; i < m_callSites.size(); ++i)
  804. {
  805. offsetInBytes = baseOffsetInBytes;
  806. const InstructionSetVector& liveHere = lv.getLiveValues(i);
  807. std::vector<Instruction*> workList(liveHere.begin(), liveHere.end());
  808. std::set<Instruction*> visited;
  809. Rematerializer R(allocaToVal, liveHere, *m_resources);
  810. Instruction* saveInsertBefore = m_callSites[i];
  811. Instruction* restoreInsertBefore = getInstructionAfter(m_callSites[i]);
  812. Instruction* rematInsertBefore = nullptr; // create only if needed
  813. // Rematerialize stack offsets after the continuation before other restores
  814. for (Instruction* inst : stackOffsets)
  815. {
  816. visited.insert(inst);
  817. Instruction* remat = R.rematerialize(inst, workList, restoreInsertBefore);
  818. new StoreInst(remat, valToAlloca[inst], restoreInsertBefore);
  819. }
  820. Instruction* saveStackFrameOffset = new LoadInst(valToAlloca[m_stackFrameOffset], "stackFrame.offset", saveInsertBefore);
  821. Instruction* restoreStackFrameOffset = R.getRematerializedValueFor(m_stackFrameOffset);
  822. while (!workList.empty())
  823. {
  824. Instruction* inst = workList.back();
  825. workList.pop_back();
  826. if (!visited.insert(inst).second)
  827. continue;
  828. if (!R.canRematerialize(inst))
  829. {
  830. assert(!inst->getType()->isPointerTy() && "Can not save pointers");
  831. offsetInBytes = align(offsetInBytes, inst, DL);
  832. AllocaInst* alloca = valToAlloca[inst];
  833. Value* saveVal = new LoadInst(alloca, addSuffix(inst->getName(), ".save"), saveInsertBefore);
  834. createStackStore(saveStackFrameOffset, saveVal, offsetInBytes, saveInsertBefore);
  835. Value* restoreVal = createStackLoad(restoreStackFrameOffset, inst, offsetInBytes, restoreInsertBefore);
  836. new StoreInst(restoreVal, alloca, restoreInsertBefore);
  837. offsetInBytes += DL.getTypeAllocSize(inst->getType());
  838. }
  839. else if (R.getRematerializedValueFor(inst) == nullptr)
  840. {
  841. if (!rematInsertBefore)
  842. {
  843. // Create a new block after restores for rematerialized values. This
  844. // ensures that we can use restored values (through their allocas) even
  845. // if we haven't generated the actual restore yet.
  846. rematInsertBefore = restoreInsertBefore->getParent()->splitBasicBlock(restoreInsertBefore, "remat_begin")->begin();
  847. restoreInsertBefore = m_callSites[i]->getParent()->getTerminator();
  848. }
  849. Instruction* remat = R.rematerialize(inst, workList, rematInsertBefore);
  850. new StoreInst(remat, valToAlloca[inst], rematInsertBefore);
  851. }
  852. }
  853. // Take the max offset over all call sites
  854. maxOffsetInBytes = std::max(maxOffsetInBytes, offsetInBytes);
  855. }
  856. // ... traceFrame (if any)
  857. maxOffsetInBytes += m_traceFrameSizeInBytes;
  858. // Set the stack size
  859. rewriteDummyStackSize(maxOffsetInBytes);
  860. shaderStackSize = maxOffsetInBytes;
  861. }
  862. void StateFunctionTransform::createSubstateFunctions(std::vector<Function*>& stateFunctions)
  863. {
  864. // The runtime perf of split() depends on the number of blocks in the function.
  865. // Simplifying the CFG before the split helps reduce the cost of that operation.
  866. runPasses(m_function, {
  867. createCFGSimplificationPass()
  868. });
  869. stateFunctions.resize(m_callSites.size() + 1);
  870. BasicBlockVector substateEntryBlocks = replaceCallSites();
  871. for (size_t i = 0, e = stateFunctions.size(); i < e; ++i)
  872. {
  873. stateFunctions[i] = split(m_function, substateEntryBlocks[i], i);
  874. // Add an attribute so we can detect when an intrinsic is not being called
  875. // from a state function, and thus doesn't have access to the runtimeData pointer.
  876. stateFunctions[i]->addFnAttr("state_function", "true");
  877. }
  878. // Erase base function
  879. m_function->eraseFromParent();
  880. m_function = nullptr;
  881. }
  882. void StateFunctionTransform::allocateStackFrame()
  883. {
  884. Module* mod = m_function->getParent();
  885. // Push stack frame in entry block.
  886. Instruction* insertBefore = m_stackFrameOffset;
  887. Function* stackFramePushFunc = FunctionBuilder(mod, "stackFramePush").voidTy().type(m_runtimeDataArgTy, "runtimeData").i32("size").build();
  888. m_stackFramePush = CallInst::Create(stackFramePushFunc, { m_runtimeDataArg, m_stackFrameSizeVal }, "", insertBefore);
  889. // Pop the stack frame just before returns.
  890. Function* stackFramePop = FunctionBuilder(mod, "stackFramePop").voidTy().type(m_runtimeDataArgTy, "runtimeData").i32("size").build();
  891. for (Instruction* insertBefore : m_returns)
  892. CallInst::Create(stackFramePop, { m_runtimeDataArg, m_stackFrameSizeVal }, "", insertBefore);
  893. }
  894. void StateFunctionTransform::allocateTraceFrame()
  895. {
  896. assert(m_attributeSizeInBytes >= 0 && "Attribute size has not been specified");
  897. m_traceFrameSizeInBytes =
  898. 2 * m_attributeSizeInBytes // committed and pending attributes
  899. + 2 * sizeof(int); // old committed/pending attribute offsets
  900. int attrSizeInInts = m_attributeSizeInBytes / sizeof(int);
  901. // Push the trace frame first thing so that the runtime
  902. // can do setup relative to the entry stack offset.
  903. Module* mod = m_function->getParent();
  904. Instruction* insertBefore = afterEntryBlockAllocas(m_function);
  905. Value* attrSize = makeInt32(attrSizeInInts, mod->getContext());
  906. Function* traceFramePushFunc = FunctionBuilder(mod, "traceFramePush").voidTy().type(m_runtimeDataArgTy, "runtimeData").i32("attrSize").build();
  907. CallInst::Create(traceFramePushFunc, { m_runtimeDataArg, attrSize }, "", insertBefore);
  908. // Pop the trace frame just before returns.
  909. Function* traceFramePopFunc = FunctionBuilder(mod, "traceFramePop").voidTy().type(m_runtimeDataArgTy, "runtimeData").build();
  910. for (Instruction* insertBefore : m_returns)
  911. CallInst::Create(traceFramePopFunc, { m_runtimeDataArg }, "", insertBefore);
  912. }
  913. bool isTemporaryAlloca(Value* op)
  914. {
  915. // TODO: Need to some analysis to figure this out. We can put the alloca on
  916. // the caller stack if:
  917. // there is only a single callsite OR
  918. // if no callsite between stores/loads and this callsite
  919. return true;
  920. }
  921. void StateFunctionTransform::createArgFrames()
  922. {
  923. Module* mod = m_function->getParent();
  924. DataLayout DL(mod);
  925. Instruction* stackAllocaInsertBefore = getInstructionAfter(m_stackFrameOffset);
  926. // Retrieve this function's arguments from the stack
  927. if (m_function->getFunctionType()->getNumParams() > 0)
  928. {
  929. if (m_paramTypes.empty())
  930. m_paramTypes.assign(m_function->getFunctionType()->getNumParams(), PST_NONE); // assume standard argument types
  931. static_assert(PST_COUNT == 3, "Expected 3 parameter semantic types");
  932. int offsetInBytes[PST_COUNT] = { 0, 0, 0 };
  933. Value* baseOffset[PST_COUNT] = { nullptr, nullptr, nullptr };
  934. Instruction* insertBefore = stackAllocaInsertBefore;
  935. for (auto pst : m_paramTypes)
  936. {
  937. if (baseOffset[pst])
  938. continue;
  939. if (pst == PST_NONE)
  940. {
  941. baseOffset[pst] = BinaryOperator::Create(Instruction::Add, m_stackFrameOffset, m_stackFrameSizeVal, "callerArgFrame.offset", insertBefore);
  942. offsetInBytes[pst] = sizeof(int); // skip the first element in caller arg frame (returnStateID)
  943. }
  944. else if (pst == PST_PAYLOAD)
  945. {
  946. baseOffset[pst] = m_payloadOffset;
  947. }
  948. else if (pst == PST_ATTRIBUTE)
  949. {
  950. baseOffset[pst] = (m_useCommittedAttr) ? m_committedAttrOffset : m_pendingAttrOffset;
  951. }
  952. else
  953. {
  954. assert(0 && "Bad parameter type");
  955. }
  956. }
  957. int argIdx = 0;
  958. for (auto& arg : m_function->args())
  959. {
  960. ParameterSemanticType pst = m_paramTypes[argIdx];
  961. Value* val = nullptr;
  962. if (arg.getType()->isPointerTy())
  963. {
  964. // Assume that pointed to memory is on the stack.
  965. val = createStackPtr(baseOffset[pst], &arg, offsetInBytes[pst], insertBefore);
  966. offsetInBytes[pst] += DL.getTypeAllocSize(arg.getType()->getPointerElementType());
  967. }
  968. else
  969. {
  970. val = createStackLoad(baseOffset[pst], &arg, offsetInBytes[pst], insertBefore);
  971. offsetInBytes[pst] += DL.getTypeAllocSize(arg.getType());
  972. }
  973. // Replace use of the argument with the loaded value
  974. if (arg.hasName())
  975. val->takeName(&arg);
  976. else
  977. val->setName("arg" + std::to_string(argIdx));
  978. arg.replaceAllUsesWith(val);
  979. argIdx++;
  980. }
  981. }
  982. // Process function arguments for each call site
  983. m_maxCallerArgFrameSizeInBytes = 0;
  984. for (size_t i = 0; i < m_callSites.size(); ++i)
  985. {
  986. int offsetInBytes = 0;
  987. CallInst* call = m_callSites[i];
  988. FunctionType* FT = call->getCalledFunction()->getFunctionType();
  989. StringRef calledFuncName = call->getCalledFunction()->getName();
  990. Instruction* insertBefore = call;
  991. // Set the return stateId (next substate of this function)
  992. int nextSubstate = i + 1;
  993. Value* nextStateId = getDummyStateId(m_functionIdx, nextSubstate, insertBefore);
  994. createStackStore(m_stackFrameOffset, nextStateId, offsetInBytes, insertBefore);
  995. offsetInBytes += DL.getTypeAllocSize(nextStateId->getType());
  996. if (FT->getNumParams() && calledFuncName != CALL_INDIRECT_NAME)
  997. {
  998. for (unsigned index = 0; index < FT->getNumParams(); ++index)
  999. {
  1000. // Save the argument from the argFrame
  1001. Value* op = call->getArgOperand(index);
  1002. Type* opTy = op->getType();
  1003. if (opTy->isPointerTy())
  1004. {
  1005. // TODO: Until we have callable shaders we should not get here except
  1006. // in tests.
  1007. if (isTemporaryAlloca(op))
  1008. {
  1009. // We can just replace the alloca with space in the arg frame
  1010. assert(isa<AllocaInst>(op));
  1011. Value* stackAlloca = createStackPtr(m_stackFrameOffset, op, offsetInBytes, stackAllocaInsertBefore);
  1012. op->replaceAllUsesWith(stackAlloca);
  1013. cast<AllocaInst>(op)->eraseFromParent();
  1014. }
  1015. else
  1016. {
  1017. // copy in/out
  1018. assert(0);
  1019. }
  1020. offsetInBytes += DL.getTypeAllocSize(opTy->getPointerElementType());
  1021. }
  1022. else
  1023. {
  1024. createStackStore(m_stackFrameOffset, op, offsetInBytes, insertBefore);
  1025. offsetInBytes += DL.getTypeAllocSize(opTy);
  1026. }
  1027. // Replace use of the argument with undef
  1028. call->setArgOperand(index, UndefValue::get(opTy));
  1029. }
  1030. }
  1031. if (offsetInBytes > m_maxCallerArgFrameSizeInBytes)
  1032. m_maxCallerArgFrameSizeInBytes = offsetInBytes;
  1033. }
  1034. }
  1035. void StateFunctionTransform::changeFunctionSignature()
  1036. {
  1037. // Create a new function that takes a state object pointer and returns next state ID
  1038. // and splice in the body of the old function into the new one.
  1039. Function* newFunc = FunctionBuilder(m_function->getParent(), m_functionName + "_tmp").i32().type(m_runtimeDataArgTy, "runtimeData").build();
  1040. newFunc->getBasicBlockList().splice(newFunc->begin(), m_function->getBasicBlockList());
  1041. m_function = newFunc;
  1042. // Set the runtime data pointer and remove the dummy function .
  1043. Value* runtimeDataArg = m_function->arg_begin();
  1044. replaceValAndRemoveUnusedDummyFunc(m_runtimeDataArg, runtimeDataArg, m_function);
  1045. m_runtimeDataArg = runtimeDataArg;
  1046. // Get return stateID from stack on each return.
  1047. LLVMContext& context = m_function->getContext();
  1048. Value* zero = makeInt32(0, context);
  1049. CallInst* retStackFrameOffset = m_stackFrameOffset;
  1050. for (ReturnInst*& ret : m_returns)
  1051. {
  1052. Instruction* insertBefore = ret;
  1053. if (m_stackFramePush)
  1054. retStackFrameOffset = CallInst::Create(m_stackFrameOffset->getCalledFunction(), { m_runtimeDataArg }, "ret.stackFrame.offset", insertBefore);
  1055. Instruction* returnStateIdPtr = CallInst::Create(m_stackIntPtrFunc, { m_runtimeDataArg, retStackFrameOffset, zero }, "ret.stateId.ptr", insertBefore);
  1056. Value* returnStateId = new LoadInst(returnStateIdPtr, "ret.stateId", insertBefore);
  1057. ReturnInst* newRet = ReturnInst::Create(context, returnStateId);
  1058. ReplaceInstWithInst(ret, newRet);
  1059. ret = newRet; // update reference
  1060. }
  1061. }
  1062. void StateFunctionTransform::rewriteDummyStackSize(uint64_t frameSizeInBytes)
  1063. {
  1064. assert(frameSizeInBytes % sizeof(int) == 0);
  1065. Value* frameSizeVal = makeInt32(frameSizeInBytes / sizeof(int), m_function->getContext());
  1066. replaceValAndRemoveUnusedDummyFunc(m_stackFrameSizeVal, frameSizeVal, m_function);
  1067. m_stackFrameSizeVal = frameSizeVal;
  1068. }
  1069. void StateFunctionTransform::createStackStore(Value* baseOffset, Value* val, int offsetInBytes, Instruction* insertBefore)
  1070. {
  1071. assert(offsetInBytes % sizeof(int) == 0);
  1072. Value* intIndex = makeInt32(offsetInBytes / sizeof(int), insertBefore->getContext());
  1073. Value* args[] = { val, baseOffset, intIndex };
  1074. Type* argTypes[] = { args[0]->getType(), args[1]->getType(), args[2]->getType() };
  1075. FunctionType* FT = FunctionType::get(Type::getVoidTy(val->getContext()), argTypes, false);
  1076. Function* F = getOrCreateFunction("stack.store", insertBefore->getModule(), FT, m_stackStoreFuncs);
  1077. CallInst::Create(F, args, "", insertBefore);
  1078. }
  1079. Instruction* StateFunctionTransform::createStackLoad(Value* baseOffset, Value* val, int offsetInBytes, Instruction* insertBefore)
  1080. {
  1081. assert(offsetInBytes % sizeof(int) == 0);
  1082. Value* intIndex = makeInt32(offsetInBytes / sizeof(int), insertBefore->getContext());
  1083. Value* args[] = { baseOffset, intIndex };
  1084. Type* argTypes[] = { args[0]->getType(), args[1]->getType() };
  1085. FunctionType* FT = FunctionType::get(val->getType(), argTypes, false);
  1086. Function* F = getOrCreateFunction("stack.load", insertBefore->getModule(), FT, m_stackLoadFuncs);
  1087. return CallInst::Create(F, args, addSuffix(val->getName(), ".restore"), insertBefore);
  1088. }
  1089. Instruction* StateFunctionTransform::createStackPtr(Value* baseOffset, Type* valTy, Value* intIndex, Instruction* insertBefore)
  1090. {
  1091. Value* args[] = { baseOffset, intIndex };
  1092. Type* argTypes[] = { args[0]->getType(), args[1]->getType() };
  1093. FunctionType* FT = FunctionType::get(valTy, argTypes, false);
  1094. Function* F = getOrCreateFunction("stack.ptr", insertBefore->getModule(), FT, m_stackPtrFuncs);
  1095. CallInst* call = CallInst::Create(F, args, "", insertBefore);
  1096. return call;
  1097. }
  1098. Instruction* StateFunctionTransform::createStackPtr(Value* baseOffset, Value* val, int offsetInBytes, Instruction* insertBefore)
  1099. {
  1100. assert(offsetInBytes % sizeof(int) == 0);
  1101. Value* intIndex = makeInt32(offsetInBytes / sizeof(int), insertBefore->getContext());
  1102. Instruction* ptr = createStackPtr(baseOffset, val->getType(), intIndex, insertBefore);
  1103. ptr->takeName(val);
  1104. return ptr;
  1105. }
  1106. static bool isStackIntPtr(Value* val)
  1107. {
  1108. CallInst* call = dyn_cast<CallInst>(val);
  1109. return call && call->getCalledFunction()->getName().startswith("stack.ptr");
  1110. }
  1111. // This code adapted from GetElementPtrInst::accumulateConstantOffset().
  1112. // TODO: Use a single function for both constant and dynamic offsets? Could do
  1113. // some constant folding along the way for dynamic offsets.
  1114. Value* accumulateDynamicOffset(GetElementPtrInst* gep, const DataLayout &DL)
  1115. {
  1116. LLVMContext& C = gep->getContext();
  1117. Instruction* insertBefore = gep;
  1118. Value* offset = makeInt32(0, C);
  1119. for (gep_type_iterator GTI = gep_type_begin(gep), GTE = gep_type_end(gep); GTI != GTE; ++GTI)
  1120. {
  1121. ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
  1122. if (OpC && OpC->isZero())
  1123. continue;
  1124. // Handle a struct index, which adds its field offset to the pointer.
  1125. Value* elementOffset = nullptr;
  1126. if (StructType *STy = dyn_cast<StructType>(*GTI))
  1127. {
  1128. assert(OpC && "Structure indices must be constant");
  1129. unsigned ElementIdx = OpC->getZExtValue();
  1130. const StructLayout *SL = DL.getStructLayout(STy);
  1131. elementOffset = makeInt32(SL->getElementOffset(ElementIdx) / sizeof(int), C);
  1132. }
  1133. else
  1134. {
  1135. // For array or vector indices, scale the index by the size of the type.
  1136. Value* stride = makeInt32(DL.getTypeAllocSize(GTI.getIndexedType()) / sizeof(int), C);
  1137. elementOffset = BinaryOperator::Create(Instruction::Mul, GTI.getOperand(), stride, "elOffs", insertBefore);
  1138. }
  1139. offset = BinaryOperator::Create(Instruction::Add, offset, elementOffset, "offs", insertBefore);
  1140. }
  1141. return offset;
  1142. }
  1143. // Adds gep offset to offsetVal and returns the result
  1144. static Value* accumulateGepOffset(GetElementPtrInst* gep, Value* offsetVal)
  1145. {
  1146. Module* M = gep->getModule();
  1147. const DataLayout& DL = M->getDataLayout();
  1148. Value* elementOffsetVal = nullptr;
  1149. APInt constOffset(DL.getPointerSizeInBits(), 0);
  1150. if (gep->accumulateConstantOffset(DL, constOffset))
  1151. elementOffsetVal = makeInt32((int)constOffset.getZExtValue() / sizeof(int), M->getContext());
  1152. else
  1153. elementOffsetVal = accumulateDynamicOffset(gep, DL);
  1154. elementOffsetVal = BinaryOperator::Create(Instruction::Add, offsetVal, elementOffsetVal, "offs", gep);
  1155. return elementOffsetVal;
  1156. }
  1157. // Turn GEPs on a stack.ptr of aggregate type into stack.ptrs of scalar type
  1158. void StateFunctionTransform::flattenGepsOnValue(Value* val, Value* baseOffset, Value* offsetVal)
  1159. {
  1160. for (auto U = val->user_begin(), UE = val->user_end(); U != UE;)
  1161. {
  1162. User* user = *U++;
  1163. if (CallInst* call = dyn_cast<CallInst>(user))
  1164. {
  1165. // inline the call to expose GEPs and restart the loop.
  1166. InlineFunctionInfo IFI;
  1167. bool success = InlineFunction(call, IFI, false);
  1168. assert(success);
  1169. (void)success;
  1170. U = val->user_begin();
  1171. UE = val->user_end();
  1172. continue;
  1173. }
  1174. GetElementPtrInst* gep = dyn_cast<GetElementPtrInst>(user);
  1175. if (!gep)
  1176. continue;
  1177. Value* elementOffsetVal = accumulateGepOffset(gep, offsetVal);
  1178. Type* gepElTy = gep->getType()->getPointerElementType();
  1179. if (gepElTy->isAggregateType())
  1180. {
  1181. // flatten geps on this gep
  1182. flattenGepsOnValue(gep, baseOffset, elementOffsetVal);
  1183. }
  1184. else if (isa<VectorType>(gepElTy))
  1185. scalarizeVectorStackAccess(gep, baseOffset, elementOffsetVal);
  1186. else
  1187. {
  1188. Value* ptr = createStackPtr(baseOffset, gep->getType(), elementOffsetVal, gep);
  1189. ptr->takeName(gep); // could use a name that encodes the gep type and indices
  1190. gep->replaceAllUsesWith(ptr);
  1191. }
  1192. gep->eraseFromParent();
  1193. }
  1194. }
  1195. void StateFunctionTransform::scalarizeVectorStackAccess(Instruction* vecPtr, Value* baseOffset, Value* offsetVal)
  1196. {
  1197. std::vector<Value*> elPtrs;
  1198. Type* VTy = vecPtr->getType()->getPointerElementType();
  1199. Type* elTy = VTy->getVectorElementType();
  1200. LLVMContext& C = vecPtr->getContext();
  1201. Value* curOffsetVal = offsetVal;
  1202. Value* one = makeInt32(1, C);
  1203. offsetVal->setName("offs0.");
  1204. for (unsigned i = 0; i < VTy->getVectorNumElements(); ++i)
  1205. {
  1206. // TODO: If offsetVal is a constant we could just create constants instead of add instructions
  1207. if (i > 0)
  1208. curOffsetVal = BinaryOperator::Create(Instruction::Add, curOffsetVal, one, stringf("offs%d.", i), vecPtr);
  1209. elPtrs.push_back(createStackPtr(baseOffset, elTy->getPointerTo(), curOffsetVal, vecPtr));
  1210. elPtrs.back()->setName(addSuffix(vecPtr->getName(), stringf(".el%d.", i)));
  1211. }
  1212. // Scalarize load/stores
  1213. for (auto U = vecPtr->user_begin(), UE = vecPtr->user_end(); U != UE;)
  1214. {
  1215. User* user = *U++;
  1216. if (LoadInst* load = dyn_cast<LoadInst>(user))
  1217. {
  1218. Value* vec = UndefValue::get(VTy);
  1219. for (size_t i = 0; i < elPtrs.size(); ++i)
  1220. {
  1221. Value* el = new LoadInst(elPtrs[i], stringf("el%d.", i), load);
  1222. vec = InsertElementInst::Create(vec, el, makeInt32(i, C), "vec", load);
  1223. }
  1224. load->replaceAllUsesWith(vec);
  1225. load->eraseFromParent();
  1226. }
  1227. else if (StoreInst* store = dyn_cast<StoreInst>(user))
  1228. {
  1229. Value* vec = store->getOperand(0);
  1230. for (size_t i = 0; i < elPtrs.size(); ++i)
  1231. {
  1232. Value* el = ExtractElementInst::Create(vec, makeInt32(i, C), stringf("el%d.", i), store);
  1233. new StoreInst(el, elPtrs[i], store);
  1234. }
  1235. store->eraseFromParent();
  1236. }
  1237. else
  1238. {
  1239. assert(0 && "Unhandled user");
  1240. }
  1241. }
  1242. }
  1243. void StateFunctionTransform::lowerStackFuncs()
  1244. {
  1245. LLVMContext& C = m_stackIntPtrFunc->getContext();
  1246. const DataLayout& DL = m_stackIntPtrFunc->getParent()->getDataLayout();
  1247. // stack.store functions
  1248. for (auto& kv : m_stackStoreFuncs)
  1249. {
  1250. Function* F = kv.second;
  1251. for (auto U = F->user_begin(); U != F->user_end(); )
  1252. {
  1253. CallInst* call = dyn_cast<CallInst>(*(U++));
  1254. assert(call);
  1255. Value* runtimeDataArg = call->getParent()->getParent()->arg_begin();
  1256. Value* val = call->getArgOperand(0);
  1257. Value* offset = call->getArgOperand(1);
  1258. int idx = getConstantValue(call->getArgOperand(2));
  1259. Instruction* insertBefore = call;
  1260. if (isStackIntPtr(val))
  1261. {
  1262. // Copy from one part of the stack to another
  1263. CallInst* valCall = dyn_cast<CallInst>(val);
  1264. Value* srcOffset = valCall->getArgOperand(0);
  1265. int srcIdx = getConstantValue(valCall->getArgOperand(1));
  1266. Value* dstOffset = offset;
  1267. int dstIdx = idx;
  1268. int intCount = (int)DL.getTypeAllocSize(val->getType()->getPointerElementType()) / sizeof(int);
  1269. for (int i = 0; i < intCount; ++i)
  1270. {
  1271. std::string idxStr = stringf("%d.", i);
  1272. Value* srcPtr = CallInst::Create(m_stackIntPtrFunc, { runtimeDataArg, srcOffset, makeInt32(srcIdx + i, C) }, addSuffix(val->getName(), ".ptr" + idxStr), insertBefore);
  1273. Value* dstPtr = CallInst::Create(m_stackIntPtrFunc, { runtimeDataArg, dstOffset, makeInt32(dstIdx + i, C) }, "dst.ptr" + idxStr, insertBefore);
  1274. Value* intVal = new LoadInst(srcPtr, "copy.val" + idxStr, insertBefore);
  1275. new StoreInst(intVal, dstPtr, insertBefore);
  1276. }
  1277. }
  1278. else
  1279. {
  1280. store(val, m_stackIntPtrFunc, runtimeDataArg, offset, idx, insertBefore);
  1281. }
  1282. call->eraseFromParent();
  1283. }
  1284. F->eraseFromParent();
  1285. }
  1286. // stack.load functions
  1287. for (auto& kv : m_stackLoadFuncs)
  1288. {
  1289. Function* F = kv.second;
  1290. for (auto U = F->user_begin(); U != F->user_end(); )
  1291. {
  1292. CallInst* call = dyn_cast<CallInst>(*(U++));
  1293. assert(call);
  1294. std::string name = stripSuffix(call->getName(), ".restore");
  1295. call->setName("");
  1296. Value* runtimeDataArg = call->getParent()->getParent()->arg_begin();
  1297. Value* offset = call->getArgOperand(0);
  1298. Value* idx = call->getArgOperand(1);
  1299. Instruction* insertBefore = call;
  1300. Value* val = load(m_stackIntPtrFunc, runtimeDataArg, offset, idx, name, call->getType(), insertBefore);
  1301. call->replaceAllUsesWith(val);
  1302. call->eraseFromParent();
  1303. }
  1304. F->eraseFromParent();
  1305. }
  1306. // Scalarize accesses based on a stack.ptr func
  1307. for (auto& kv : m_stackPtrFuncs)
  1308. {
  1309. Function* F = kv.second;
  1310. if (!F->getReturnType()->getPointerElementType()->isAggregateType())
  1311. continue;
  1312. for (auto U = F->user_begin(), UE = F->user_end(); U != UE; )
  1313. {
  1314. CallInst* call = dyn_cast<CallInst>(*(U++));
  1315. assert(call);
  1316. Value* offset = call->getArgOperand(0);
  1317. Value* idx = call->getArgOperand(1);
  1318. flattenGepsOnValue(call, offset, idx);
  1319. call->eraseFromParent();
  1320. }
  1321. }
  1322. // stack.ptr functions
  1323. for (auto& kv : m_stackPtrFuncs)
  1324. {
  1325. Function* F = kv.second;
  1326. for (auto U = F->user_begin(); U != F->user_end(); )
  1327. {
  1328. CallInst* call = dyn_cast<CallInst>(*(U++));
  1329. assert(call);
  1330. std::string name = call->getName();
  1331. Value* runtimeDataArg = call->getParent()->getParent()->arg_begin();
  1332. Value* offset = call->getArgOperand(0);
  1333. Value* idx = call->getArgOperand(1);
  1334. Instruction* insertBefore = call;
  1335. Value* ptr = CallInst::Create(m_stackIntPtrFunc, { runtimeDataArg, offset, idx }, addSuffix(name, ".ptr"), insertBefore);
  1336. if (ptr->getType() != call->getType())
  1337. ptr = new BitCastInst(ptr, call->getType(), "", insertBefore);
  1338. ptr->takeName(call);
  1339. call->replaceAllUsesWith(ptr);
  1340. call->eraseFromParent();
  1341. }
  1342. F->eraseFromParent();
  1343. }
  1344. }
  1345. Function* StateFunctionTransform::split(Function* baseFunc, BasicBlock* substateEntryBlock, int substateIndex)
  1346. {
  1347. ValueToValueMapTy VMap;
  1348. Function* substateFunc = cloneBlocksReachableFrom(substateEntryBlock, VMap);
  1349. Module* mod = baseFunc->getParent();
  1350. mod->getFunctionList().push_back(substateFunc);
  1351. substateFunc->setName(m_functionName + ".ss_" + std::to_string(substateIndex));
  1352. if (substateIndex != 0)
  1353. {
  1354. // Collect allocas from entry block
  1355. SmallVector<Instruction*, 16> allocasToClone;
  1356. for (auto& I : baseFunc->getEntryBlock().getInstList())
  1357. {
  1358. if (isa<AllocaInst>(&I))
  1359. allocasToClone.push_back(&I);
  1360. }
  1361. // Clone collected allocas
  1362. BasicBlock* newEntryBlock = &substateFunc->getEntryBlock();
  1363. for (auto I : allocasToClone)
  1364. {
  1365. // Collect users of original instruction in substateFunc
  1366. std::vector<Instruction*> users;
  1367. for (auto U : I->users())
  1368. {
  1369. Instruction* inst = dyn_cast<Instruction>(U);
  1370. if (inst->getParent()->getParent() == substateFunc)
  1371. users.push_back(inst);
  1372. }
  1373. if (users.empty())
  1374. continue;
  1375. // Clone instruction
  1376. Instruction* clone = I->clone();
  1377. if (I->hasName())
  1378. clone->setName(I->getName());
  1379. clone->insertBefore(newEntryBlock->getFirstInsertionPt()); // allocas first in entry block
  1380. RemapInstruction(clone, VMap, RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
  1381. // Replaces uses
  1382. for (auto user : users)
  1383. user->replaceUsesOfWith(I, clone);
  1384. }
  1385. }
  1386. //printFunction( substateFunc, substateFunc->getName().str() + "-BeforeSplittingOpt", m_dumpId++ );
  1387. makeReducible(substateFunc);
  1388. // Undo the reg2mem done in preserveLiveValuesAcrossCallSites()
  1389. runPasses(substateFunc, {
  1390. createVerifierPass(),
  1391. createPromoteMemoryToRegisterPass()
  1392. });
  1393. //printFunction( substateFunc, substateFunc->getName().str() + "-AfterSplitting", m_dumpId++ );
  1394. return substateFunc;
  1395. }
  1396. BasicBlockVector StateFunctionTransform::replaceCallSites()
  1397. {
  1398. LLVMContext& context = m_function->getContext();
  1399. BasicBlockVector substateEntryPoints{ &m_function->getEntryBlock() };
  1400. substateEntryPoints[0]->setName(m_functionName + ".BB0");
  1401. // Add other substates by splitting blocks at call sites.
  1402. for (size_t i = 0; i < m_callSites.size(); ++i)
  1403. {
  1404. CallInst* call = m_callSites[i];
  1405. BasicBlock* block = call->getParent();
  1406. StringRef calledFuncName = call->getCalledFunction()->getName();
  1407. BasicBlock* nextBlock =
  1408. block->splitBasicBlock(call->getNextNode(), m_functionName + ".BB" + std::to_string(i + 1) + ".from."
  1409. + cleanName(calledFuncName));
  1410. substateEntryPoints.push_back(nextBlock);
  1411. // Return state id for entry state of the function being called
  1412. Instruction* insertBefore = call;
  1413. Value* returnStateId = nullptr;
  1414. if (calledFuncName == CALL_INDIRECT_NAME)
  1415. returnStateId = call->getArgOperand(0);
  1416. else
  1417. returnStateId = getDummyStateId(m_callSiteFunctionIdx[i], 0, insertBefore);
  1418. ReplaceInstWithInst(call->getParent()->getTerminator(), ReturnInst::Create(context, returnStateId));
  1419. call->eraseFromParent();
  1420. }
  1421. return substateEntryPoints;
  1422. }
  1423. llvm::Value* StateFunctionTransform::getDummyStateId(int functionIdx, int substate, llvm::Instruction* insertBefore)
  1424. {
  1425. if (!m_dummyStateIdFunc)
  1426. {
  1427. Module* M = m_function->getParent();
  1428. m_dummyStateIdFunc = FunctionBuilder(M, "dummyStateId").i32().i32("functionIdx").i32("substate").build();
  1429. }
  1430. LLVMContext& context = insertBefore->getContext();
  1431. Value* functionIdxVal = makeInt32(functionIdx, context);
  1432. Value* substateVal = makeInt32(substate, context);
  1433. return CallInst::Create(m_dummyStateIdFunc, { functionIdxVal, substateVal }, "stateId", insertBefore);
  1434. }
  1435. raw_ostream& StateFunctionTransform::getOutputStream(const std::string functionName, const std::string& suffix, unsigned int dumpId)
  1436. {
  1437. if (m_dumpFilename.empty())
  1438. return DBGS();
  1439. const std::string filename = createDumpPath(m_dumpFilename, dumpId, suffix, functionName);
  1440. std::error_code errorCode;
  1441. raw_ostream* out = new raw_fd_ostream(filename, errorCode, sys::fs::OpenFlags::F_None);
  1442. if (errorCode)
  1443. {
  1444. DBGS() << "Failed to open " << filename << " for writing sft output. " << errorCode.message() << "\n";
  1445. delete out;
  1446. return DBGS();
  1447. }
  1448. return *out;
  1449. }
  1450. void StateFunctionTransform::printFunction(const Function* function, const std::string& suffix, unsigned int dumpId)
  1451. {
  1452. if (!m_verbose)
  1453. return;
  1454. raw_ostream& out = getOutputStream(m_functionName, suffix, dumpId);
  1455. out << "; ########################### " << suffix << "\n";
  1456. out << *function << "\n";
  1457. if (&out != &DBGS())
  1458. delete &out;
  1459. }
  1460. void StateFunctionTransform::printFunction(const std::string& suffix)
  1461. {
  1462. printFunction(m_function, suffix, m_dumpId++);
  1463. }
  1464. void StateFunctionTransform::printFunctions(const std::vector<Function*>& funcs, const char* suffix)
  1465. {
  1466. if (!m_verbose)
  1467. return;
  1468. raw_ostream& out = getOutputStream(m_functionName, suffix, m_dumpId++);
  1469. out << "; ########################### " << suffix << "\n";
  1470. for (Function* F : funcs)
  1471. out << *F << "\n";
  1472. if (&out != &DBGS())
  1473. delete &out;
  1474. }
  1475. void StateFunctionTransform::printModule(const Module* mod, const std::string& suffix)
  1476. {
  1477. if (!m_verbose)
  1478. return;
  1479. raw_ostream& out = getOutputStream("module", suffix, m_dumpId++);
  1480. out << "; ########################### " << suffix << "\n";
  1481. out << *mod << "\n";
  1482. }
  1483. void StateFunctionTransform::printSet(const InstructionSetVector& vals, const char* msg)
  1484. {
  1485. if (!m_verbose)
  1486. return;
  1487. raw_ostream& out = DBGS();
  1488. if (msg)
  1489. out << msg << " --------------------\n";
  1490. uint64_t totalBytes = 0;
  1491. if (vals.size() > 0)
  1492. {
  1493. Module* mod = m_function->getParent();
  1494. DataLayout DL(mod);
  1495. for (InstructionSetVector::const_iterator I = vals.begin(), IE = vals.end(); I != IE; ++I)
  1496. {
  1497. const Instruction* inst = *I;
  1498. uint64_t size = DL.getTypeAllocSize(inst->getType());
  1499. out << stringf("%3dB: ", size) << *inst << '\n';
  1500. totalBytes += size;
  1501. }
  1502. }
  1503. out << "Count:" << vals.size() << " Bytes:" << totalBytes << "\n\n";
  1504. }