InlineFunction.cpp 68 KB

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