InlineFunction.cpp 60 KB

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