InlineFunction.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  1. //===- InlineFunction.cpp - Code to perform function inlining -------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements inlining of a function into a call site, resolving
  11. // parameters and the return value as appropriate.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/Cloning.h"
  15. #include "llvm/ADT/SmallSet.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/SetVector.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/Analysis/AliasAnalysis.h"
  20. #include "llvm/Analysis/CallGraph.h"
  21. #include "llvm/Analysis/CaptureTracking.h"
  22. #include "llvm/Analysis/InstructionSimplify.h"
  23. #include "llvm/Analysis/ValueTracking.h"
  24. #include "llvm/IR/Attributes.h"
  25. #include "llvm/IR/CallSite.h"
  26. #include "llvm/IR/CFG.h"
  27. #include "llvm/IR/Constants.h"
  28. #include "llvm/IR/DataLayout.h"
  29. #include "llvm/IR/DebugInfo.h"
  30. #include "llvm/IR/DerivedTypes.h"
  31. #include "llvm/IR/Dominators.h"
  32. #include "llvm/IR/IRBuilder.h"
  33. #include "llvm/IR/Instructions.h"
  34. #include "llvm/IR/IntrinsicInst.h"
  35. #include "llvm/IR/Intrinsics.h"
  36. #include "llvm/IR/MDBuilder.h"
  37. #include "llvm/IR/Module.h"
  38. #include "llvm/Transforms/Utils/Local.h"
  39. #include "llvm/Support/CommandLine.h"
  40. #include <algorithm>
  41. using namespace llvm;
  42. static cl::opt<bool>
  43. EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(false),
  44. cl::Hidden,
  45. cl::desc("Convert noalias attributes to metadata during inlining."));
  46. bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
  47. bool InsertLifetime) {
  48. return InlineFunction(CallSite(CI), IFI, InsertLifetime);
  49. }
  50. bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
  51. bool InsertLifetime) {
  52. return InlineFunction(CallSite(II), IFI, InsertLifetime);
  53. }
  54. namespace {
  55. /// A class for recording information about inlining through an invoke.
  56. class InvokeInliningInfo {
  57. BasicBlock *OuterResumeDest; ///< Destination of the invoke's unwind.
  58. BasicBlock *InnerResumeDest; ///< Destination for the callee's resume.
  59. LandingPadInst *CallerLPad; ///< LandingPadInst associated with the invoke.
  60. PHINode *InnerEHValuesPHI; ///< PHI for EH values from landingpad insts.
  61. SmallVector<Value*, 8> UnwindDestPHIValues;
  62. public:
  63. InvokeInliningInfo(InvokeInst *II)
  64. : OuterResumeDest(II->getUnwindDest()), InnerResumeDest(nullptr),
  65. CallerLPad(nullptr), InnerEHValuesPHI(nullptr) {
  66. // If there are PHI nodes in the unwind destination block, we need to keep
  67. // track of which values came into them from the invoke before removing
  68. // the edge from this block.
  69. llvm::BasicBlock *InvokeBB = II->getParent();
  70. BasicBlock::iterator I = OuterResumeDest->begin();
  71. for (; isa<PHINode>(I); ++I) {
  72. // Save the value to use for this edge.
  73. PHINode *PHI = cast<PHINode>(I);
  74. UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
  75. }
  76. CallerLPad = cast<LandingPadInst>(I);
  77. }
  78. /// getOuterResumeDest - The outer unwind destination is the target of
  79. /// unwind edges introduced for calls within the inlined function.
  80. BasicBlock *getOuterResumeDest() const {
  81. return OuterResumeDest;
  82. }
  83. BasicBlock *getInnerResumeDest();
  84. LandingPadInst *getLandingPadInst() const { return CallerLPad; }
  85. /// forwardResume - Forward the 'resume' instruction to the caller's landing
  86. /// pad block. When the landing pad block has only one predecessor, this is
  87. /// a simple branch. When there is more than one predecessor, we need to
  88. /// split the landing pad block after the landingpad instruction and jump
  89. /// to there.
  90. void forwardResume(ResumeInst *RI,
  91. SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
  92. /// addIncomingPHIValuesFor - Add incoming-PHI values to the unwind
  93. /// destination block for the given basic block, using the values for the
  94. /// original invoke's source block.
  95. void addIncomingPHIValuesFor(BasicBlock *BB) const {
  96. addIncomingPHIValuesForInto(BB, OuterResumeDest);
  97. }
  98. void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
  99. BasicBlock::iterator I = dest->begin();
  100. for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
  101. PHINode *phi = cast<PHINode>(I);
  102. phi->addIncoming(UnwindDestPHIValues[i], src);
  103. }
  104. }
  105. };
  106. }
  107. /// getInnerResumeDest - Get or create a target for the branch from ResumeInsts.
  108. BasicBlock *InvokeInliningInfo::getInnerResumeDest() {
  109. if (InnerResumeDest) return InnerResumeDest;
  110. // Split the landing pad.
  111. BasicBlock::iterator SplitPoint = CallerLPad; ++SplitPoint;
  112. InnerResumeDest =
  113. OuterResumeDest->splitBasicBlock(SplitPoint,
  114. OuterResumeDest->getName() + ".body");
  115. // The number of incoming edges we expect to the inner landing pad.
  116. const unsigned PHICapacity = 2;
  117. // Create corresponding new PHIs for all the PHIs in the outer landing pad.
  118. BasicBlock::iterator InsertPoint = InnerResumeDest->begin();
  119. BasicBlock::iterator I = OuterResumeDest->begin();
  120. for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
  121. PHINode *OuterPHI = cast<PHINode>(I);
  122. PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
  123. OuterPHI->getName() + ".lpad-body",
  124. InsertPoint);
  125. OuterPHI->replaceAllUsesWith(InnerPHI);
  126. InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
  127. }
  128. // Create a PHI for the exception values.
  129. InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
  130. "eh.lpad-body", InsertPoint);
  131. CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
  132. InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
  133. // All done.
  134. return InnerResumeDest;
  135. }
  136. /// forwardResume - Forward the 'resume' instruction to the caller's landing pad
  137. /// block. When the landing pad block has only one predecessor, this is a simple
  138. /// branch. When there is more than one predecessor, we need to split the
  139. /// landing pad block after the landingpad instruction and jump to there.
  140. void InvokeInliningInfo::forwardResume(ResumeInst *RI,
  141. SmallPtrSetImpl<LandingPadInst*> &InlinedLPads) {
  142. BasicBlock *Dest = getInnerResumeDest();
  143. BasicBlock *Src = RI->getParent();
  144. BranchInst::Create(Dest, Src);
  145. // Update the PHIs in the destination. They were inserted in an order which
  146. // makes this work.
  147. addIncomingPHIValuesForInto(Src, Dest);
  148. InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
  149. RI->eraseFromParent();
  150. }
  151. /// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
  152. /// an invoke, we have to turn all of the calls that can throw into
  153. /// invokes. This function analyze BB to see if there are any calls, and if so,
  154. /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
  155. /// nodes in that block with the values specified in InvokeDestPHIValues.
  156. static void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
  157. InvokeInliningInfo &Invoke) {
  158. for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
  159. Instruction *I = BBI++;
  160. // We only need to check for function calls: inlined invoke
  161. // instructions require no special handling.
  162. CallInst *CI = dyn_cast<CallInst>(I);
  163. // If this call cannot unwind, don't convert it to an invoke.
  164. // Inline asm calls cannot throw.
  165. if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
  166. continue;
  167. // Convert this function call into an invoke instruction. First, split the
  168. // basic block.
  169. BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
  170. // Delete the unconditional branch inserted by splitBasicBlock
  171. BB->getInstList().pop_back();
  172. // Create the new invoke instruction.
  173. ImmutableCallSite CS(CI);
  174. SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
  175. InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split,
  176. Invoke.getOuterResumeDest(),
  177. InvokeArgs, CI->getName(), BB);
  178. II->setDebugLoc(CI->getDebugLoc());
  179. II->setCallingConv(CI->getCallingConv());
  180. II->setAttributes(CI->getAttributes());
  181. // Make sure that anything using the call now uses the invoke! This also
  182. // updates the CallGraph if present, because it uses a WeakVH.
  183. CI->replaceAllUsesWith(II);
  184. // Delete the original call
  185. Split->getInstList().pop_front();
  186. // Update any PHI nodes in the exceptional block to indicate that there is
  187. // now a new entry in them.
  188. Invoke.addIncomingPHIValuesFor(BB);
  189. return;
  190. }
  191. }
  192. /// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
  193. /// in the body of the inlined function into invokes.
  194. ///
  195. /// II is the invoke instruction being inlined. FirstNewBlock is the first
  196. /// block of the inlined code (the last block is the end of the function),
  197. /// and InlineCodeInfo is information about the code that got inlined.
  198. static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
  199. ClonedCodeInfo &InlinedCodeInfo) {
  200. BasicBlock *InvokeDest = II->getUnwindDest();
  201. Function *Caller = FirstNewBlock->getParent();
  202. // The inlined code is currently at the end of the function, scan from the
  203. // start of the inlined code to its end, checking for stuff we need to
  204. // rewrite.
  205. InvokeInliningInfo Invoke(II);
  206. // Get all of the inlined landing pad instructions.
  207. SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
  208. for (Function::iterator I = FirstNewBlock, E = Caller->end(); I != E; ++I)
  209. if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
  210. InlinedLPads.insert(II->getLandingPadInst());
  211. // Append the clauses from the outer landing pad instruction into the inlined
  212. // landing pad instructions.
  213. LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
  214. for (SmallPtrSet<LandingPadInst*, 16>::iterator I = InlinedLPads.begin(),
  215. E = InlinedLPads.end(); I != E; ++I) {
  216. LandingPadInst *InlinedLPad = *I;
  217. unsigned OuterNum = OuterLPad->getNumClauses();
  218. InlinedLPad->reserveClauses(OuterNum);
  219. for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
  220. InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
  221. if (OuterLPad->isCleanup())
  222. InlinedLPad->setCleanup(true);
  223. }
  224. for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
  225. if (InlinedCodeInfo.ContainsCalls)
  226. HandleCallsInBlockInlinedThroughInvoke(BB, Invoke);
  227. // Forward any resumes that are remaining here.
  228. if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
  229. Invoke.forwardResume(RI, InlinedLPads);
  230. }
  231. // Now that everything is happy, we have one final detail. The PHI nodes in
  232. // the exception destination block still have entries due to the original
  233. // invoke instruction. Eliminate these entries (which might even delete the
  234. // PHI node) now.
  235. InvokeDest->removePredecessor(II->getParent());
  236. }
  237. /// CloneAliasScopeMetadata - When inlining a function that contains noalias
  238. /// scope metadata, this metadata needs to be cloned so that the inlined blocks
  239. /// have different "unqiue scopes" at every call site. Were this not done, then
  240. /// aliasing scopes from a function inlined into a caller multiple times could
  241. /// not be differentiated (and this would lead to miscompiles because the
  242. /// non-aliasing property communicated by the metadata could have
  243. /// call-site-specific control dependencies).
  244. static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
  245. const Function *CalledFunc = CS.getCalledFunction();
  246. SetVector<const MDNode *> MD;
  247. // Note: We could only clone the metadata if it is already used in the
  248. // caller. I'm omitting that check here because it might confuse
  249. // inter-procedural alias analysis passes. We can revisit this if it becomes
  250. // an efficiency or overhead problem.
  251. for (Function::const_iterator I = CalledFunc->begin(), IE = CalledFunc->end();
  252. I != IE; ++I)
  253. for (BasicBlock::const_iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
  254. if (const MDNode *M = J->getMetadata(LLVMContext::MD_alias_scope))
  255. MD.insert(M);
  256. if (const MDNode *M = J->getMetadata(LLVMContext::MD_noalias))
  257. MD.insert(M);
  258. }
  259. if (MD.empty())
  260. return;
  261. // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
  262. // the set.
  263. SmallVector<const Value *, 16> Queue(MD.begin(), MD.end());
  264. while (!Queue.empty()) {
  265. const MDNode *M = cast<MDNode>(Queue.pop_back_val());
  266. for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
  267. if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
  268. if (MD.insert(M1))
  269. Queue.push_back(M1);
  270. }
  271. // Now we have a complete set of all metadata in the chains used to specify
  272. // the noalias scopes and the lists of those scopes.
  273. SmallVector<MDNode *, 16> DummyNodes;
  274. DenseMap<const MDNode *, TrackingVH<MDNode> > MDMap;
  275. for (SetVector<const MDNode *>::iterator I = MD.begin(), IE = MD.end();
  276. I != IE; ++I) {
  277. MDNode *Dummy = MDNode::getTemporary(CalledFunc->getContext(),
  278. ArrayRef<Value*>());
  279. DummyNodes.push_back(Dummy);
  280. MDMap[*I] = Dummy;
  281. }
  282. // Create new metadata nodes to replace the dummy nodes, replacing old
  283. // metadata references with either a dummy node or an already-created new
  284. // node.
  285. for (SetVector<const MDNode *>::iterator I = MD.begin(), IE = MD.end();
  286. I != IE; ++I) {
  287. SmallVector<Value *, 4> NewOps;
  288. for (unsigned i = 0, ie = (*I)->getNumOperands(); i != ie; ++i) {
  289. const Value *V = (*I)->getOperand(i);
  290. if (const MDNode *M = dyn_cast<MDNode>(V))
  291. NewOps.push_back(MDMap[M]);
  292. else
  293. NewOps.push_back(const_cast<Value *>(V));
  294. }
  295. MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps),
  296. *TempM = MDMap[*I];
  297. TempM->replaceAllUsesWith(NewM);
  298. }
  299. // Now replace the metadata in the new inlined instructions with the
  300. // repacements from the map.
  301. for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
  302. VMI != VMIE; ++VMI) {
  303. if (!VMI->second)
  304. continue;
  305. Instruction *NI = dyn_cast<Instruction>(VMI->second);
  306. if (!NI)
  307. continue;
  308. if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope)) {
  309. MDNode *NewMD = MDMap[M];
  310. // If the call site also had alias scope metadata (a list of scopes to
  311. // which instructions inside it might belong), propagate those scopes to
  312. // the inlined instructions.
  313. if (MDNode *CSM =
  314. CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
  315. NewMD = MDNode::concatenate(NewMD, CSM);
  316. NI->setMetadata(LLVMContext::MD_alias_scope, NewMD);
  317. } else if (NI->mayReadOrWriteMemory()) {
  318. if (MDNode *M =
  319. CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
  320. NI->setMetadata(LLVMContext::MD_alias_scope, M);
  321. }
  322. if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias)) {
  323. MDNode *NewMD = MDMap[M];
  324. // If the call site also had noalias metadata (a list of scopes with
  325. // which instructions inside it don't alias), propagate those scopes to
  326. // the inlined instructions.
  327. if (MDNode *CSM =
  328. CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
  329. NewMD = MDNode::concatenate(NewMD, CSM);
  330. NI->setMetadata(LLVMContext::MD_noalias, NewMD);
  331. } else if (NI->mayReadOrWriteMemory()) {
  332. if (MDNode *M =
  333. CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
  334. NI->setMetadata(LLVMContext::MD_noalias, M);
  335. }
  336. }
  337. // Now that everything has been replaced, delete the dummy nodes.
  338. for (unsigned i = 0, ie = DummyNodes.size(); i != ie; ++i)
  339. MDNode::deleteTemporary(DummyNodes[i]);
  340. }
  341. /// AddAliasScopeMetadata - If the inlined function has noalias arguments, then
  342. /// add new alias scopes for each noalias argument, tag the mapped noalias
  343. /// parameters with noalias metadata specifying the new scope, and tag all
  344. /// non-derived loads, stores and memory intrinsics with the new alias scopes.
  345. static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
  346. const DataLayout *DL) {
  347. if (!EnableNoAliasConversion)
  348. return;
  349. const Function *CalledFunc = CS.getCalledFunction();
  350. SmallVector<const Argument *, 4> NoAliasArgs;
  351. for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
  352. E = CalledFunc->arg_end(); I != E; ++I) {
  353. if (I->hasNoAliasAttr() && !I->hasNUses(0))
  354. NoAliasArgs.push_back(I);
  355. }
  356. if (NoAliasArgs.empty())
  357. return;
  358. // To do a good job, if a noalias variable is captured, we need to know if
  359. // the capture point dominates the particular use we're considering.
  360. DominatorTree DT;
  361. DT.recalculate(const_cast<Function&>(*CalledFunc));
  362. // noalias indicates that pointer values based on the argument do not alias
  363. // pointer values which are not based on it. So we add a new "scope" for each
  364. // noalias function argument. Accesses using pointers based on that argument
  365. // become part of that alias scope, accesses using pointers not based on that
  366. // argument are tagged as noalias with that scope.
  367. DenseMap<const Argument *, MDNode *> NewScopes;
  368. MDBuilder MDB(CalledFunc->getContext());
  369. // Create a new scope domain for this function.
  370. MDNode *NewDomain =
  371. MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
  372. for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
  373. const Argument *A = NoAliasArgs[i];
  374. std::string Name = CalledFunc->getName();
  375. if (A->hasName()) {
  376. Name += ": %";
  377. Name += A->getName();
  378. } else {
  379. Name += ": argument ";
  380. Name += utostr(i);
  381. }
  382. // Note: We always create a new anonymous root here. This is true regardless
  383. // of the linkage of the callee because the aliasing "scope" is not just a
  384. // property of the callee, but also all control dependencies in the caller.
  385. MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
  386. NewScopes.insert(std::make_pair(A, NewScope));
  387. }
  388. // Iterate over all new instructions in the map; for all memory-access
  389. // instructions, add the alias scope metadata.
  390. for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
  391. VMI != VMIE; ++VMI) {
  392. if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
  393. if (!VMI->second)
  394. continue;
  395. Instruction *NI = dyn_cast<Instruction>(VMI->second);
  396. if (!NI)
  397. continue;
  398. SmallVector<const Value *, 2> PtrArgs;
  399. if (const LoadInst *LI = dyn_cast<LoadInst>(I))
  400. PtrArgs.push_back(LI->getPointerOperand());
  401. else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
  402. PtrArgs.push_back(SI->getPointerOperand());
  403. else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
  404. PtrArgs.push_back(VAAI->getPointerOperand());
  405. else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
  406. PtrArgs.push_back(CXI->getPointerOperand());
  407. else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
  408. PtrArgs.push_back(RMWI->getPointerOperand());
  409. else if (ImmutableCallSite ICS = ImmutableCallSite(I)) {
  410. // If we know that the call does not access memory, then we'll still
  411. // know that about the inlined clone of this call site, and we don't
  412. // need to add metadata.
  413. if (ICS.doesNotAccessMemory())
  414. continue;
  415. for (ImmutableCallSite::arg_iterator AI = ICS.arg_begin(),
  416. AE = ICS.arg_end(); AI != AE; ++AI)
  417. // We need to check the underlying objects of all arguments, not just
  418. // the pointer arguments, because we might be passing pointers as
  419. // integers, etc.
  420. // FIXME: If we know that the call only accesses pointer arguments,
  421. // then we only need to check the pointer arguments.
  422. PtrArgs.push_back(*AI);
  423. }
  424. // If we found no pointers, then this instruction is not suitable for
  425. // pairing with an instruction to receive aliasing metadata.
  426. // However, if this is a call, this we might just alias with none of the
  427. // noalias arguments.
  428. if (PtrArgs.empty() && !isa<CallInst>(I) && !isa<InvokeInst>(I))
  429. continue;
  430. // It is possible that there is only one underlying object, but you
  431. // need to go through several PHIs to see it, and thus could be
  432. // repeated in the Objects list.
  433. SmallPtrSet<const Value *, 4> ObjSet;
  434. SmallVector<Value *, 4> Scopes, NoAliases;
  435. SmallSetVector<const Argument *, 4> NAPtrArgs;
  436. for (unsigned i = 0, ie = PtrArgs.size(); i != ie; ++i) {
  437. SmallVector<Value *, 4> Objects;
  438. GetUnderlyingObjects(const_cast<Value*>(PtrArgs[i]),
  439. Objects, DL, /* MaxLookup = */ 0);
  440. for (Value *O : Objects)
  441. ObjSet.insert(O);
  442. }
  443. // Figure out if we're derived from anyhing that is not a noalias
  444. // argument.
  445. bool CanDeriveViaCapture = false;
  446. for (const Value *V : ObjSet)
  447. if (!isIdentifiedFunctionLocal(const_cast<Value*>(V))) {
  448. CanDeriveViaCapture = true;
  449. break;
  450. }
  451. // First, we want to figure out all of the sets with which we definitely
  452. // don't alias. Iterate over all noalias set, and add those for which:
  453. // 1. The noalias argument is not in the set of objects from which we
  454. // definitely derive.
  455. // 2. The noalias argument has not yet been captured.
  456. for (const Argument *A : NoAliasArgs) {
  457. if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
  458. A->hasNoCaptureAttr() ||
  459. !PointerMayBeCapturedBefore(A,
  460. /* ReturnCaptures */ false,
  461. /* StoreCaptures */ false, I, &DT)))
  462. NoAliases.push_back(NewScopes[A]);
  463. }
  464. if (!NoAliases.empty())
  465. NI->setMetadata(LLVMContext::MD_noalias, MDNode::concatenate(
  466. NI->getMetadata(LLVMContext::MD_noalias),
  467. MDNode::get(CalledFunc->getContext(), NoAliases)));
  468. // Next, we want to figure out all of the sets to which we might belong.
  469. // We might below to a set if:
  470. // 1. The noalias argument is in the set of underlying objects
  471. // or
  472. // 2. There is some non-noalias argument in our list and the no-alias
  473. // argument has been captured.
  474. for (const Argument *A : NoAliasArgs) {
  475. if (ObjSet.count(A) || (CanDeriveViaCapture &&
  476. PointerMayBeCapturedBefore(A,
  477. /* ReturnCaptures */ false,
  478. /* StoreCaptures */ false,
  479. I, &DT)))
  480. Scopes.push_back(NewScopes[A]);
  481. }
  482. if (!Scopes.empty())
  483. NI->setMetadata(LLVMContext::MD_alias_scope, MDNode::concatenate(
  484. NI->getMetadata(LLVMContext::MD_alias_scope),
  485. MDNode::get(CalledFunc->getContext(), Scopes)));
  486. }
  487. }
  488. }
  489. /// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
  490. /// into the caller, update the specified callgraph to reflect the changes we
  491. /// made. Note that it's possible that not all code was copied over, so only
  492. /// some edges of the callgraph may remain.
  493. static void UpdateCallGraphAfterInlining(CallSite CS,
  494. Function::iterator FirstNewBlock,
  495. ValueToValueMapTy &VMap,
  496. InlineFunctionInfo &IFI) {
  497. CallGraph &CG = *IFI.CG;
  498. const Function *Caller = CS.getInstruction()->getParent()->getParent();
  499. const Function *Callee = CS.getCalledFunction();
  500. CallGraphNode *CalleeNode = CG[Callee];
  501. CallGraphNode *CallerNode = CG[Caller];
  502. // Since we inlined some uninlined call sites in the callee into the caller,
  503. // add edges from the caller to all of the callees of the callee.
  504. CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
  505. // Consider the case where CalleeNode == CallerNode.
  506. CallGraphNode::CalledFunctionsVector CallCache;
  507. if (CalleeNode == CallerNode) {
  508. CallCache.assign(I, E);
  509. I = CallCache.begin();
  510. E = CallCache.end();
  511. }
  512. for (; I != E; ++I) {
  513. const Value *OrigCall = I->first;
  514. ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
  515. // Only copy the edge if the call was inlined!
  516. if (VMI == VMap.end() || VMI->second == nullptr)
  517. continue;
  518. // If the call was inlined, but then constant folded, there is no edge to
  519. // add. Check for this case.
  520. Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
  521. if (!NewCall) continue;
  522. // Remember that this call site got inlined for the client of
  523. // InlineFunction.
  524. IFI.InlinedCalls.push_back(NewCall);
  525. // It's possible that inlining the callsite will cause it to go from an
  526. // indirect to a direct call by resolving a function pointer. If this
  527. // happens, set the callee of the new call site to a more precise
  528. // destination. This can also happen if the call graph node of the caller
  529. // was just unnecessarily imprecise.
  530. if (!I->second->getFunction())
  531. if (Function *F = CallSite(NewCall).getCalledFunction()) {
  532. // Indirect call site resolved to direct call.
  533. CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
  534. continue;
  535. }
  536. CallerNode->addCalledFunction(CallSite(NewCall), I->second);
  537. }
  538. // Update the call graph by deleting the edge from Callee to Caller. We must
  539. // do this after the loop above in case Caller and Callee are the same.
  540. CallerNode->removeCallEdgeFor(CS);
  541. }
  542. static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
  543. BasicBlock *InsertBlock,
  544. InlineFunctionInfo &IFI) {
  545. LLVMContext &Context = Src->getContext();
  546. Type *VoidPtrTy = Type::getInt8PtrTy(Context);
  547. Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
  548. Type *Tys[3] = { VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context) };
  549. Function *MemCpyFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy, Tys);
  550. IRBuilder<> builder(InsertBlock->begin());
  551. Value *DstCast = builder.CreateBitCast(Dst, VoidPtrTy, "tmp");
  552. Value *SrcCast = builder.CreateBitCast(Src, VoidPtrTy, "tmp");
  553. Value *Size;
  554. if (IFI.DL == nullptr)
  555. Size = ConstantExpr::getSizeOf(AggTy);
  556. else
  557. Size = ConstantInt::get(Type::getInt64Ty(Context),
  558. IFI.DL->getTypeStoreSize(AggTy));
  559. // Always generate a memcpy of alignment 1 here because we don't know
  560. // the alignment of the src pointer. Other optimizations can infer
  561. // better alignment.
  562. Value *CallArgs[] = {
  563. DstCast, SrcCast, Size,
  564. ConstantInt::get(Type::getInt32Ty(Context), 1),
  565. ConstantInt::getFalse(Context) // isVolatile
  566. };
  567. builder.CreateCall(MemCpyFn, CallArgs);
  568. }
  569. /// HandleByValArgument - When inlining a call site that has a byval argument,
  570. /// we have to make the implicit memcpy explicit by adding it.
  571. static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
  572. const Function *CalledFunc,
  573. InlineFunctionInfo &IFI,
  574. unsigned ByValAlignment) {
  575. PointerType *ArgTy = cast<PointerType>(Arg->getType());
  576. Type *AggTy = ArgTy->getElementType();
  577. // If the called function is readonly, then it could not mutate the caller's
  578. // copy of the byval'd memory. In this case, it is safe to elide the copy and
  579. // temporary.
  580. if (CalledFunc->onlyReadsMemory()) {
  581. // If the byval argument has a specified alignment that is greater than the
  582. // passed in pointer, then we either have to round up the input pointer or
  583. // give up on this transformation.
  584. if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment.
  585. return Arg;
  586. // If the pointer is already known to be sufficiently aligned, or if we can
  587. // round it up to a larger alignment, then we don't need a temporary.
  588. if (getOrEnforceKnownAlignment(Arg, ByValAlignment,
  589. IFI.DL) >= ByValAlignment)
  590. return Arg;
  591. // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
  592. // for code quality, but rarely happens and is required for correctness.
  593. }
  594. // Create the alloca. If we have DataLayout, use nice alignment.
  595. unsigned Align = 1;
  596. if (IFI.DL)
  597. Align = IFI.DL->getPrefTypeAlignment(AggTy);
  598. // If the byval had an alignment specified, we *must* use at least that
  599. // alignment, as it is required by the byval argument (and uses of the
  600. // pointer inside the callee).
  601. Align = std::max(Align, ByValAlignment);
  602. Function *Caller = TheCall->getParent()->getParent();
  603. Value *NewAlloca = new AllocaInst(AggTy, nullptr, Align, Arg->getName(),
  604. &*Caller->begin()->begin());
  605. IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
  606. // Uses of the argument in the function should use our new alloca
  607. // instead.
  608. return NewAlloca;
  609. }
  610. // isUsedByLifetimeMarker - Check whether this Value is used by a lifetime
  611. // intrinsic.
  612. static bool isUsedByLifetimeMarker(Value *V) {
  613. for (User *U : V->users()) {
  614. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
  615. switch (II->getIntrinsicID()) {
  616. default: break;
  617. case Intrinsic::lifetime_start:
  618. case Intrinsic::lifetime_end:
  619. return true;
  620. }
  621. }
  622. }
  623. return false;
  624. }
  625. // hasLifetimeMarkers - Check whether the given alloca already has
  626. // lifetime.start or lifetime.end intrinsics.
  627. static bool hasLifetimeMarkers(AllocaInst *AI) {
  628. Type *Ty = AI->getType();
  629. Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
  630. Ty->getPointerAddressSpace());
  631. if (Ty == Int8PtrTy)
  632. return isUsedByLifetimeMarker(AI);
  633. // Do a scan to find all the casts to i8*.
  634. for (User *U : AI->users()) {
  635. if (U->getType() != Int8PtrTy) continue;
  636. if (U->stripPointerCasts() != AI) continue;
  637. if (isUsedByLifetimeMarker(U))
  638. return true;
  639. }
  640. return false;
  641. }
  642. /// updateInlinedAtInfo - Helper function used by fixupLineNumbers to
  643. /// recursively update InlinedAtEntry of a DebugLoc.
  644. static DebugLoc updateInlinedAtInfo(const DebugLoc &DL,
  645. const DebugLoc &InlinedAtDL,
  646. LLVMContext &Ctx) {
  647. if (MDNode *IA = DL.getInlinedAt(Ctx)) {
  648. DebugLoc NewInlinedAtDL
  649. = updateInlinedAtInfo(DebugLoc::getFromDILocation(IA), InlinedAtDL, Ctx);
  650. return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
  651. NewInlinedAtDL.getAsMDNode(Ctx));
  652. }
  653. return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
  654. InlinedAtDL.getAsMDNode(Ctx));
  655. }
  656. /// fixupLineNumbers - Update inlined instructions' line numbers to
  657. /// to encode location where these instructions are inlined.
  658. static void fixupLineNumbers(Function *Fn, Function::iterator FI,
  659. Instruction *TheCall) {
  660. DebugLoc TheCallDL = TheCall->getDebugLoc();
  661. if (TheCallDL.isUnknown())
  662. return;
  663. for (; FI != Fn->end(); ++FI) {
  664. for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
  665. BI != BE; ++BI) {
  666. DebugLoc DL = BI->getDebugLoc();
  667. if (DL.isUnknown()) {
  668. // If the inlined instruction has no line number, make it look as if it
  669. // originates from the call location. This is important for
  670. // ((__always_inline__, __nodebug__)) functions which must use caller
  671. // location for all instructions in their function body.
  672. BI->setDebugLoc(TheCallDL);
  673. } else {
  674. BI->setDebugLoc(updateInlinedAtInfo(DL, TheCallDL, BI->getContext()));
  675. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(BI)) {
  676. LLVMContext &Ctx = BI->getContext();
  677. MDNode *InlinedAt = BI->getDebugLoc().getInlinedAt(Ctx);
  678. DVI->setOperand(2, createInlinedVariable(DVI->getVariable(),
  679. InlinedAt, Ctx));
  680. }
  681. }
  682. }
  683. }
  684. }
  685. /// InlineFunction - This function inlines the called function into the basic
  686. /// block of the caller. This returns false if it is not possible to inline
  687. /// this call. The program is still in a well defined state if this occurs
  688. /// though.
  689. ///
  690. /// Note that this only does one level of inlining. For example, if the
  691. /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
  692. /// exists in the instruction stream. Similarly this will inline a recursive
  693. /// function by one level.
  694. bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
  695. bool InsertLifetime) {
  696. Instruction *TheCall = CS.getInstruction();
  697. assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
  698. "Instruction not in function!");
  699. // If IFI has any state in it, zap it before we fill it in.
  700. IFI.reset();
  701. const Function *CalledFunc = CS.getCalledFunction();
  702. if (!CalledFunc || // Can't inline external function or indirect
  703. CalledFunc->isDeclaration() || // call, or call to a vararg function!
  704. CalledFunc->getFunctionType()->isVarArg()) return false;
  705. // If the call to the callee cannot throw, set the 'nounwind' flag on any
  706. // calls that we inline.
  707. bool MarkNoUnwind = CS.doesNotThrow();
  708. BasicBlock *OrigBB = TheCall->getParent();
  709. Function *Caller = OrigBB->getParent();
  710. // GC poses two hazards to inlining, which only occur when the callee has GC:
  711. // 1. If the caller has no GC, then the callee's GC must be propagated to the
  712. // caller.
  713. // 2. If the caller has a differing GC, it is invalid to inline.
  714. if (CalledFunc->hasGC()) {
  715. if (!Caller->hasGC())
  716. Caller->setGC(CalledFunc->getGC());
  717. else if (CalledFunc->getGC() != Caller->getGC())
  718. return false;
  719. }
  720. // Get the personality function from the callee if it contains a landing pad.
  721. Value *CalleePersonality = nullptr;
  722. for (Function::const_iterator I = CalledFunc->begin(), E = CalledFunc->end();
  723. I != E; ++I)
  724. if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
  725. const BasicBlock *BB = II->getUnwindDest();
  726. const LandingPadInst *LP = BB->getLandingPadInst();
  727. CalleePersonality = LP->getPersonalityFn();
  728. break;
  729. }
  730. // Find the personality function used by the landing pads of the caller. If it
  731. // exists, then check to see that it matches the personality function used in
  732. // the callee.
  733. if (CalleePersonality) {
  734. for (Function::const_iterator I = Caller->begin(), E = Caller->end();
  735. I != E; ++I)
  736. if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
  737. const BasicBlock *BB = II->getUnwindDest();
  738. const LandingPadInst *LP = BB->getLandingPadInst();
  739. // If the personality functions match, then we can perform the
  740. // inlining. Otherwise, we can't inline.
  741. // TODO: This isn't 100% true. Some personality functions are proper
  742. // supersets of others and can be used in place of the other.
  743. if (LP->getPersonalityFn() != CalleePersonality)
  744. return false;
  745. break;
  746. }
  747. }
  748. // Get an iterator to the last basic block in the function, which will have
  749. // the new function inlined after it.
  750. Function::iterator LastBlock = &Caller->back();
  751. // Make sure to capture all of the return instructions from the cloned
  752. // function.
  753. SmallVector<ReturnInst*, 8> Returns;
  754. ClonedCodeInfo InlinedFunctionInfo;
  755. Function::iterator FirstNewBlock;
  756. { // Scope to destroy VMap after cloning.
  757. ValueToValueMapTy VMap;
  758. // Keep a list of pair (dst, src) to emit byval initializations.
  759. SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
  760. assert(CalledFunc->arg_size() == CS.arg_size() &&
  761. "No varargs calls can be inlined!");
  762. // Calculate the vector of arguments to pass into the function cloner, which
  763. // matches up the formal to the actual argument values.
  764. CallSite::arg_iterator AI = CS.arg_begin();
  765. unsigned ArgNo = 0;
  766. for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
  767. E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
  768. Value *ActualArg = *AI;
  769. // When byval arguments actually inlined, we need to make the copy implied
  770. // by them explicit. However, we don't do this if the callee is readonly
  771. // or readnone, because the copy would be unneeded: the callee doesn't
  772. // modify the struct.
  773. if (CS.isByValArgument(ArgNo)) {
  774. ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
  775. CalledFunc->getParamAlignment(ArgNo+1));
  776. if (ActualArg != *AI)
  777. ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
  778. }
  779. VMap[I] = ActualArg;
  780. }
  781. // We want the inliner to prune the code as it copies. We would LOVE to
  782. // have no dead or constant instructions leftover after inlining occurs
  783. // (which can happen, e.g., because an argument was constant), but we'll be
  784. // happy with whatever the cloner can do.
  785. CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
  786. /*ModuleLevelChanges=*/false, Returns, ".i",
  787. &InlinedFunctionInfo, IFI.DL, TheCall);
  788. // Remember the first block that is newly cloned over.
  789. FirstNewBlock = LastBlock; ++FirstNewBlock;
  790. // Inject byval arguments initialization.
  791. for (std::pair<Value*, Value*> &Init : ByValInit)
  792. HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
  793. FirstNewBlock, IFI);
  794. // Update the callgraph if requested.
  795. if (IFI.CG)
  796. UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
  797. // Update inlined instructions' line number information.
  798. fixupLineNumbers(Caller, FirstNewBlock, TheCall);
  799. // Clone existing noalias metadata if necessary.
  800. CloneAliasScopeMetadata(CS, VMap);
  801. // Add noalias metadata if necessary.
  802. AddAliasScopeMetadata(CS, VMap, IFI.DL);
  803. }
  804. // If there are any alloca instructions in the block that used to be the entry
  805. // block for the callee, move them to the entry block of the caller. First
  806. // calculate which instruction they should be inserted before. We insert the
  807. // instructions at the end of the current alloca list.
  808. {
  809. BasicBlock::iterator InsertPoint = Caller->begin()->begin();
  810. for (BasicBlock::iterator I = FirstNewBlock->begin(),
  811. E = FirstNewBlock->end(); I != E; ) {
  812. AllocaInst *AI = dyn_cast<AllocaInst>(I++);
  813. if (!AI) continue;
  814. // If the alloca is now dead, remove it. This often occurs due to code
  815. // specialization.
  816. if (AI->use_empty()) {
  817. AI->eraseFromParent();
  818. continue;
  819. }
  820. if (!isa<Constant>(AI->getArraySize()))
  821. continue;
  822. // Keep track of the static allocas that we inline into the caller.
  823. IFI.StaticAllocas.push_back(AI);
  824. // Scan for the block of allocas that we can move over, and move them
  825. // all at once.
  826. while (isa<AllocaInst>(I) &&
  827. isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
  828. IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
  829. ++I;
  830. }
  831. // Transfer all of the allocas over in a block. Using splice means
  832. // that the instructions aren't removed from the symbol table, then
  833. // reinserted.
  834. Caller->getEntryBlock().getInstList().splice(InsertPoint,
  835. FirstNewBlock->getInstList(),
  836. AI, I);
  837. }
  838. }
  839. bool InlinedMustTailCalls = false;
  840. if (InlinedFunctionInfo.ContainsCalls) {
  841. CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
  842. if (CallInst *CI = dyn_cast<CallInst>(TheCall))
  843. CallSiteTailKind = CI->getTailCallKind();
  844. for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
  845. ++BB) {
  846. for (Instruction &I : *BB) {
  847. CallInst *CI = dyn_cast<CallInst>(&I);
  848. if (!CI)
  849. continue;
  850. // We need to reduce the strength of any inlined tail calls. For
  851. // musttail, we have to avoid introducing potential unbounded stack
  852. // growth. For example, if functions 'f' and 'g' are mutually recursive
  853. // with musttail, we can inline 'g' into 'f' so long as we preserve
  854. // musttail on the cloned call to 'f'. If either the inlined call site
  855. // or the cloned call site is *not* musttail, the program already has
  856. // one frame of stack growth, so it's safe to remove musttail. Here is
  857. // a table of example transformations:
  858. //
  859. // f -> musttail g -> musttail f ==> f -> musttail f
  860. // f -> musttail g -> tail f ==> f -> tail f
  861. // f -> g -> musttail f ==> f -> f
  862. // f -> g -> tail f ==> f -> f
  863. CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
  864. ChildTCK = std::min(CallSiteTailKind, ChildTCK);
  865. CI->setTailCallKind(ChildTCK);
  866. InlinedMustTailCalls |= CI->isMustTailCall();
  867. // Calls inlined through a 'nounwind' call site should be marked
  868. // 'nounwind'.
  869. if (MarkNoUnwind)
  870. CI->setDoesNotThrow();
  871. }
  872. }
  873. }
  874. // Leave lifetime markers for the static alloca's, scoping them to the
  875. // function we just inlined.
  876. if (InsertLifetime && !IFI.StaticAllocas.empty()) {
  877. IRBuilder<> builder(FirstNewBlock->begin());
  878. for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
  879. AllocaInst *AI = IFI.StaticAllocas[ai];
  880. // If the alloca is already scoped to something smaller than the whole
  881. // function then there's no need to add redundant, less accurate markers.
  882. if (hasLifetimeMarkers(AI))
  883. continue;
  884. // Try to determine the size of the allocation.
  885. ConstantInt *AllocaSize = nullptr;
  886. if (ConstantInt *AIArraySize =
  887. dyn_cast<ConstantInt>(AI->getArraySize())) {
  888. if (IFI.DL) {
  889. Type *AllocaType = AI->getAllocatedType();
  890. uint64_t AllocaTypeSize = IFI.DL->getTypeAllocSize(AllocaType);
  891. uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
  892. assert(AllocaArraySize > 0 && "array size of AllocaInst is zero");
  893. // Check that array size doesn't saturate uint64_t and doesn't
  894. // overflow when it's multiplied by type size.
  895. if (AllocaArraySize != ~0ULL &&
  896. UINT64_MAX / AllocaArraySize >= AllocaTypeSize) {
  897. AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
  898. AllocaArraySize * AllocaTypeSize);
  899. }
  900. }
  901. }
  902. builder.CreateLifetimeStart(AI, AllocaSize);
  903. for (ReturnInst *RI : Returns) {
  904. // Don't insert llvm.lifetime.end calls between a musttail call and a
  905. // return. The return kills all local allocas.
  906. if (InlinedMustTailCalls &&
  907. RI->getParent()->getTerminatingMustTailCall())
  908. continue;
  909. IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
  910. }
  911. }
  912. }
  913. // If the inlined code contained dynamic alloca instructions, wrap the inlined
  914. // code with llvm.stacksave/llvm.stackrestore intrinsics.
  915. if (InlinedFunctionInfo.ContainsDynamicAllocas) {
  916. Module *M = Caller->getParent();
  917. // Get the two intrinsics we care about.
  918. Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
  919. Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
  920. // Insert the llvm.stacksave.
  921. CallInst *SavedPtr = IRBuilder<>(FirstNewBlock, FirstNewBlock->begin())
  922. .CreateCall(StackSave, "savedstack");
  923. // Insert a call to llvm.stackrestore before any return instructions in the
  924. // inlined function.
  925. for (ReturnInst *RI : Returns) {
  926. // Don't insert llvm.stackrestore calls between a musttail call and a
  927. // return. The return will restore the stack pointer.
  928. if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
  929. continue;
  930. IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
  931. }
  932. }
  933. // If we are inlining for an invoke instruction, we must make sure to rewrite
  934. // any call instructions into invoke instructions.
  935. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
  936. HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
  937. // Handle any inlined musttail call sites. In order for a new call site to be
  938. // musttail, the source of the clone and the inlined call site must have been
  939. // musttail. Therefore it's safe to return without merging control into the
  940. // phi below.
  941. if (InlinedMustTailCalls) {
  942. // Check if we need to bitcast the result of any musttail calls.
  943. Type *NewRetTy = Caller->getReturnType();
  944. bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
  945. // Handle the returns preceded by musttail calls separately.
  946. SmallVector<ReturnInst *, 8> NormalReturns;
  947. for (ReturnInst *RI : Returns) {
  948. CallInst *ReturnedMustTail =
  949. RI->getParent()->getTerminatingMustTailCall();
  950. if (!ReturnedMustTail) {
  951. NormalReturns.push_back(RI);
  952. continue;
  953. }
  954. if (!NeedBitCast)
  955. continue;
  956. // Delete the old return and any preceding bitcast.
  957. BasicBlock *CurBB = RI->getParent();
  958. auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
  959. RI->eraseFromParent();
  960. if (OldCast)
  961. OldCast->eraseFromParent();
  962. // Insert a new bitcast and return with the right type.
  963. IRBuilder<> Builder(CurBB);
  964. Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
  965. }
  966. // Leave behind the normal returns so we can merge control flow.
  967. std::swap(Returns, NormalReturns);
  968. }
  969. // If we cloned in _exactly one_ basic block, and if that block ends in a
  970. // return instruction, we splice the body of the inlined callee directly into
  971. // the calling basic block.
  972. if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
  973. // Move all of the instructions right before the call.
  974. OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
  975. FirstNewBlock->begin(), FirstNewBlock->end());
  976. // Remove the cloned basic block.
  977. Caller->getBasicBlockList().pop_back();
  978. // If the call site was an invoke instruction, add a branch to the normal
  979. // destination.
  980. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
  981. BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
  982. NewBr->setDebugLoc(Returns[0]->getDebugLoc());
  983. }
  984. // If the return instruction returned a value, replace uses of the call with
  985. // uses of the returned value.
  986. if (!TheCall->use_empty()) {
  987. ReturnInst *R = Returns[0];
  988. if (TheCall == R->getReturnValue())
  989. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  990. else
  991. TheCall->replaceAllUsesWith(R->getReturnValue());
  992. }
  993. // Since we are now done with the Call/Invoke, we can delete it.
  994. TheCall->eraseFromParent();
  995. // Since we are now done with the return instruction, delete it also.
  996. Returns[0]->eraseFromParent();
  997. // We are now done with the inlining.
  998. return true;
  999. }
  1000. // Otherwise, we have the normal case, of more than one block to inline or
  1001. // multiple return sites.
  1002. // We want to clone the entire callee function into the hole between the
  1003. // "starter" and "ender" blocks. How we accomplish this depends on whether
  1004. // this is an invoke instruction or a call instruction.
  1005. BasicBlock *AfterCallBB;
  1006. BranchInst *CreatedBranchToNormalDest = nullptr;
  1007. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
  1008. // Add an unconditional branch to make this look like the CallInst case...
  1009. CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
  1010. // Split the basic block. This guarantees that no PHI nodes will have to be
  1011. // updated due to new incoming edges, and make the invoke case more
  1012. // symmetric to the call case.
  1013. AfterCallBB = OrigBB->splitBasicBlock(CreatedBranchToNormalDest,
  1014. CalledFunc->getName()+".exit");
  1015. } else { // It's a call
  1016. // If this is a call instruction, we need to split the basic block that
  1017. // the call lives in.
  1018. //
  1019. AfterCallBB = OrigBB->splitBasicBlock(TheCall,
  1020. CalledFunc->getName()+".exit");
  1021. }
  1022. // Change the branch that used to go to AfterCallBB to branch to the first
  1023. // basic block of the inlined function.
  1024. //
  1025. TerminatorInst *Br = OrigBB->getTerminator();
  1026. assert(Br && Br->getOpcode() == Instruction::Br &&
  1027. "splitBasicBlock broken!");
  1028. Br->setOperand(0, FirstNewBlock);
  1029. // Now that the function is correct, make it a little bit nicer. In
  1030. // particular, move the basic blocks inserted from the end of the function
  1031. // into the space made by splitting the source basic block.
  1032. Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
  1033. FirstNewBlock, Caller->end());
  1034. // Handle all of the return instructions that we just cloned in, and eliminate
  1035. // any users of the original call/invoke instruction.
  1036. Type *RTy = CalledFunc->getReturnType();
  1037. PHINode *PHI = nullptr;
  1038. if (Returns.size() > 1) {
  1039. // The PHI node should go at the front of the new basic block to merge all
  1040. // possible incoming values.
  1041. if (!TheCall->use_empty()) {
  1042. PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
  1043. AfterCallBB->begin());
  1044. // Anything that used the result of the function call should now use the
  1045. // PHI node as their operand.
  1046. TheCall->replaceAllUsesWith(PHI);
  1047. }
  1048. // Loop over all of the return instructions adding entries to the PHI node
  1049. // as appropriate.
  1050. if (PHI) {
  1051. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  1052. ReturnInst *RI = Returns[i];
  1053. assert(RI->getReturnValue()->getType() == PHI->getType() &&
  1054. "Ret value not consistent in function!");
  1055. PHI->addIncoming(RI->getReturnValue(), RI->getParent());
  1056. }
  1057. }
  1058. // Add a branch to the merge points and remove return instructions.
  1059. DebugLoc Loc;
  1060. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  1061. ReturnInst *RI = Returns[i];
  1062. BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
  1063. Loc = RI->getDebugLoc();
  1064. BI->setDebugLoc(Loc);
  1065. RI->eraseFromParent();
  1066. }
  1067. // We need to set the debug location to *somewhere* inside the
  1068. // inlined function. The line number may be nonsensical, but the
  1069. // instruction will at least be associated with the right
  1070. // function.
  1071. if (CreatedBranchToNormalDest)
  1072. CreatedBranchToNormalDest->setDebugLoc(Loc);
  1073. } else if (!Returns.empty()) {
  1074. // Otherwise, if there is exactly one return value, just replace anything
  1075. // using the return value of the call with the computed value.
  1076. if (!TheCall->use_empty()) {
  1077. if (TheCall == Returns[0]->getReturnValue())
  1078. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  1079. else
  1080. TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
  1081. }
  1082. // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
  1083. BasicBlock *ReturnBB = Returns[0]->getParent();
  1084. ReturnBB->replaceAllUsesWith(AfterCallBB);
  1085. // Splice the code from the return block into the block that it will return
  1086. // to, which contains the code that was after the call.
  1087. AfterCallBB->getInstList().splice(AfterCallBB->begin(),
  1088. ReturnBB->getInstList());
  1089. if (CreatedBranchToNormalDest)
  1090. CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
  1091. // Delete the return instruction now and empty ReturnBB now.
  1092. Returns[0]->eraseFromParent();
  1093. ReturnBB->eraseFromParent();
  1094. } else if (!TheCall->use_empty()) {
  1095. // No returns, but something is using the return value of the call. Just
  1096. // nuke the result.
  1097. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  1098. }
  1099. // Since we are now done with the Call/Invoke, we can delete it.
  1100. TheCall->eraseFromParent();
  1101. // If we inlined any musttail calls and the original return is now
  1102. // unreachable, delete it. It can only contain a bitcast and ret.
  1103. if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
  1104. AfterCallBB->eraseFromParent();
  1105. // We should always be able to fold the entry block of the function into the
  1106. // single predecessor of the block...
  1107. assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
  1108. BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
  1109. // Splice the code entry block into calling block, right before the
  1110. // unconditional branch.
  1111. CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
  1112. OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
  1113. // Remove the unconditional branch.
  1114. OrigBB->getInstList().erase(Br);
  1115. // Now we can remove the CalleeEntry block, which is now empty.
  1116. Caller->getBasicBlockList().erase(CalleeEntry);
  1117. // If we inserted a phi node, check to see if it has a single value (e.g. all
  1118. // the entries are the same or undef). If so, remove the PHI so it doesn't
  1119. // block other optimizations.
  1120. if (PHI) {
  1121. if (Value *V = SimplifyInstruction(PHI, IFI.DL)) {
  1122. PHI->replaceAllUsesWith(V);
  1123. PHI->eraseFromParent();
  1124. }
  1125. }
  1126. return true;
  1127. }