InlineFunction.cpp 56 KB

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