InlineFunction.cpp 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385
  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/ADT/DenseMap.h"
  15. #include "llvm/ADT/None.h"
  16. #include "llvm/ADT/Optional.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SetVector.h"
  19. #include "llvm/ADT/SmallPtrSet.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/StringExtras.h"
  22. #include "llvm/ADT/iterator_range.h"
  23. #include "llvm/Analysis/AliasAnalysis.h"
  24. #include "llvm/Analysis/AssumptionCache.h"
  25. #include "llvm/Analysis/BlockFrequencyInfo.h"
  26. #include "llvm/Analysis/CallGraph.h"
  27. #include "llvm/Analysis/CaptureTracking.h"
  28. #include "llvm/Analysis/EHPersonalities.h"
  29. #include "llvm/Analysis/InstructionSimplify.h"
  30. #include "llvm/Analysis/ProfileSummaryInfo.h"
  31. #include "llvm/Transforms/Utils/Local.h"
  32. #include "llvm/Analysis/ValueTracking.h"
  33. #include "llvm/Analysis/VectorUtils.h"
  34. #include "llvm/IR/Argument.h"
  35. #include "llvm/IR/BasicBlock.h"
  36. #include "llvm/IR/CFG.h"
  37. #include "llvm/IR/CallSite.h"
  38. #include "llvm/IR/Constant.h"
  39. #include "llvm/IR/Constants.h"
  40. #include "llvm/IR/DIBuilder.h"
  41. #include "llvm/IR/DataLayout.h"
  42. #include "llvm/IR/DebugInfoMetadata.h"
  43. #include "llvm/IR/DebugLoc.h"
  44. #include "llvm/IR/DerivedTypes.h"
  45. #include "llvm/IR/Dominators.h"
  46. #include "llvm/IR/Function.h"
  47. #include "llvm/IR/IRBuilder.h"
  48. #include "llvm/IR/InstrTypes.h"
  49. #include "llvm/IR/Instruction.h"
  50. #include "llvm/IR/Instructions.h"
  51. #include "llvm/IR/IntrinsicInst.h"
  52. #include "llvm/IR/Intrinsics.h"
  53. #include "llvm/IR/LLVMContext.h"
  54. #include "llvm/IR/MDBuilder.h"
  55. #include "llvm/IR/Metadata.h"
  56. #include "llvm/IR/Module.h"
  57. #include "llvm/IR/Type.h"
  58. #include "llvm/IR/User.h"
  59. #include "llvm/IR/Value.h"
  60. #include "llvm/Support/Casting.h"
  61. #include "llvm/Support/CommandLine.h"
  62. #include "llvm/Support/ErrorHandling.h"
  63. #include "llvm/Transforms/Utils/Cloning.h"
  64. #include "llvm/Transforms/Utils/ValueMapper.h"
  65. #include <algorithm>
  66. #include <cassert>
  67. #include <cstdint>
  68. #include <iterator>
  69. #include <limits>
  70. #include <string>
  71. #include <utility>
  72. #include <vector>
  73. using namespace llvm;
  74. using ProfileCount = Function::ProfileCount;
  75. static cl::opt<bool>
  76. EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
  77. cl::Hidden,
  78. cl::desc("Convert noalias attributes to metadata during inlining."));
  79. static cl::opt<bool>
  80. PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
  81. cl::init(true), cl::Hidden,
  82. cl::desc("Convert align attributes to assumptions during inlining."));
  83. llvm::InlineResult llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
  84. AAResults *CalleeAAR,
  85. bool InsertLifetime) {
  86. return InlineFunction(CallSite(CI), IFI, CalleeAAR, InsertLifetime);
  87. }
  88. llvm::InlineResult llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
  89. AAResults *CalleeAAR,
  90. bool InsertLifetime) {
  91. return InlineFunction(CallSite(II), IFI, CalleeAAR, InsertLifetime);
  92. }
  93. namespace {
  94. /// A class for recording information about inlining a landing pad.
  95. class LandingPadInliningInfo {
  96. /// Destination of the invoke's unwind.
  97. BasicBlock *OuterResumeDest;
  98. /// Destination for the callee's resume.
  99. BasicBlock *InnerResumeDest = nullptr;
  100. /// LandingPadInst associated with the invoke.
  101. LandingPadInst *CallerLPad = nullptr;
  102. /// PHI for EH values from landingpad insts.
  103. PHINode *InnerEHValuesPHI = nullptr;
  104. SmallVector<Value*, 8> UnwindDestPHIValues;
  105. public:
  106. LandingPadInliningInfo(InvokeInst *II)
  107. : OuterResumeDest(II->getUnwindDest()) {
  108. // If there are PHI nodes in the unwind destination block, we need to keep
  109. // track of which values came into them from the invoke before removing
  110. // the edge from this block.
  111. BasicBlock *InvokeBB = II->getParent();
  112. BasicBlock::iterator I = OuterResumeDest->begin();
  113. for (; isa<PHINode>(I); ++I) {
  114. // Save the value to use for this edge.
  115. PHINode *PHI = cast<PHINode>(I);
  116. UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
  117. }
  118. CallerLPad = cast<LandingPadInst>(I);
  119. }
  120. /// The outer unwind destination is the target of
  121. /// unwind edges introduced for calls within the inlined function.
  122. BasicBlock *getOuterResumeDest() const {
  123. return OuterResumeDest;
  124. }
  125. BasicBlock *getInnerResumeDest();
  126. LandingPadInst *getLandingPadInst() const { return CallerLPad; }
  127. /// Forward the 'resume' instruction to the caller's landing pad block.
  128. /// When the landing pad block has only one predecessor, this is
  129. /// a simple branch. When there is more than one predecessor, we need to
  130. /// split the landing pad block after the landingpad instruction and jump
  131. /// to there.
  132. void forwardResume(ResumeInst *RI,
  133. SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
  134. /// Add incoming-PHI values to the unwind destination block for the given
  135. /// basic block, using the values for the original invoke's source block.
  136. void addIncomingPHIValuesFor(BasicBlock *BB) const {
  137. addIncomingPHIValuesForInto(BB, OuterResumeDest);
  138. }
  139. void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
  140. BasicBlock::iterator I = dest->begin();
  141. for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
  142. PHINode *phi = cast<PHINode>(I);
  143. phi->addIncoming(UnwindDestPHIValues[i], src);
  144. }
  145. }
  146. };
  147. } // end anonymous namespace
  148. /// Get or create a target for the branch from ResumeInsts.
  149. BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
  150. if (InnerResumeDest) return InnerResumeDest;
  151. // Split the landing pad.
  152. BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
  153. InnerResumeDest =
  154. OuterResumeDest->splitBasicBlock(SplitPoint,
  155. OuterResumeDest->getName() + ".body");
  156. // The number of incoming edges we expect to the inner landing pad.
  157. const unsigned PHICapacity = 2;
  158. // Create corresponding new PHIs for all the PHIs in the outer landing pad.
  159. Instruction *InsertPoint = &InnerResumeDest->front();
  160. BasicBlock::iterator I = OuterResumeDest->begin();
  161. for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
  162. PHINode *OuterPHI = cast<PHINode>(I);
  163. PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
  164. OuterPHI->getName() + ".lpad-body",
  165. InsertPoint);
  166. OuterPHI->replaceAllUsesWith(InnerPHI);
  167. InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
  168. }
  169. // Create a PHI for the exception values.
  170. InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
  171. "eh.lpad-body", InsertPoint);
  172. CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
  173. InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
  174. // All done.
  175. return InnerResumeDest;
  176. }
  177. /// Forward the 'resume' instruction to the caller's landing pad block.
  178. /// When the landing pad block has only one predecessor, this is a simple
  179. /// branch. When there is more than one predecessor, we need to split the
  180. /// landing pad block after the landingpad instruction and jump to there.
  181. void LandingPadInliningInfo::forwardResume(
  182. ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
  183. BasicBlock *Dest = getInnerResumeDest();
  184. BasicBlock *Src = RI->getParent();
  185. BranchInst::Create(Dest, Src);
  186. // Update the PHIs in the destination. They were inserted in an order which
  187. // makes this work.
  188. addIncomingPHIValuesForInto(Src, Dest);
  189. InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
  190. RI->eraseFromParent();
  191. }
  192. /// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
  193. static Value *getParentPad(Value *EHPad) {
  194. if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
  195. return FPI->getParentPad();
  196. return cast<CatchSwitchInst>(EHPad)->getParentPad();
  197. }
  198. using UnwindDestMemoTy = DenseMap<Instruction *, Value *>;
  199. /// Helper for getUnwindDestToken that does the descendant-ward part of
  200. /// the search.
  201. static Value *getUnwindDestTokenHelper(Instruction *EHPad,
  202. UnwindDestMemoTy &MemoMap) {
  203. SmallVector<Instruction *, 8> Worklist(1, EHPad);
  204. while (!Worklist.empty()) {
  205. Instruction *CurrentPad = Worklist.pop_back_val();
  206. // We only put pads on the worklist that aren't in the MemoMap. When
  207. // we find an unwind dest for a pad we may update its ancestors, but
  208. // the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
  209. // so they should never get updated while queued on the worklist.
  210. assert(!MemoMap.count(CurrentPad));
  211. Value *UnwindDestToken = nullptr;
  212. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) {
  213. if (CatchSwitch->hasUnwindDest()) {
  214. UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI();
  215. } else {
  216. // Catchswitch doesn't have a 'nounwind' variant, and one might be
  217. // annotated as "unwinds to caller" when really it's nounwind (see
  218. // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
  219. // parent's unwind dest from this. We can check its catchpads'
  220. // descendants, since they might include a cleanuppad with an
  221. // "unwinds to caller" cleanupret, which can be trusted.
  222. for (auto HI = CatchSwitch->handler_begin(),
  223. HE = CatchSwitch->handler_end();
  224. HI != HE && !UnwindDestToken; ++HI) {
  225. BasicBlock *HandlerBlock = *HI;
  226. auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI());
  227. for (User *Child : CatchPad->users()) {
  228. // Intentionally ignore invokes here -- since the catchswitch is
  229. // marked "unwind to caller", it would be a verifier error if it
  230. // contained an invoke which unwinds out of it, so any invoke we'd
  231. // encounter must unwind to some child of the catch.
  232. if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child))
  233. continue;
  234. Instruction *ChildPad = cast<Instruction>(Child);
  235. auto Memo = MemoMap.find(ChildPad);
  236. if (Memo == MemoMap.end()) {
  237. // Haven't figured out this child pad yet; queue it.
  238. Worklist.push_back(ChildPad);
  239. continue;
  240. }
  241. // We've already checked this child, but might have found that
  242. // it offers no proof either way.
  243. Value *ChildUnwindDestToken = Memo->second;
  244. if (!ChildUnwindDestToken)
  245. continue;
  246. // We already know the child's unwind dest, which can either
  247. // be ConstantTokenNone to indicate unwind to caller, or can
  248. // be another child of the catchpad. Only the former indicates
  249. // the unwind dest of the catchswitch.
  250. if (isa<ConstantTokenNone>(ChildUnwindDestToken)) {
  251. UnwindDestToken = ChildUnwindDestToken;
  252. break;
  253. }
  254. assert(getParentPad(ChildUnwindDestToken) == CatchPad);
  255. }
  256. }
  257. }
  258. } else {
  259. auto *CleanupPad = cast<CleanupPadInst>(CurrentPad);
  260. for (User *U : CleanupPad->users()) {
  261. if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
  262. if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
  263. UnwindDestToken = RetUnwindDest->getFirstNonPHI();
  264. else
  265. UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext());
  266. break;
  267. }
  268. Value *ChildUnwindDestToken;
  269. if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
  270. ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI();
  271. } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
  272. Instruction *ChildPad = cast<Instruction>(U);
  273. auto Memo = MemoMap.find(ChildPad);
  274. if (Memo == MemoMap.end()) {
  275. // Haven't resolved this child yet; queue it and keep searching.
  276. Worklist.push_back(ChildPad);
  277. continue;
  278. }
  279. // We've checked this child, but still need to ignore it if it
  280. // had no proof either way.
  281. ChildUnwindDestToken = Memo->second;
  282. if (!ChildUnwindDestToken)
  283. continue;
  284. } else {
  285. // Not a relevant user of the cleanuppad
  286. continue;
  287. }
  288. // In a well-formed program, the child/invoke must either unwind to
  289. // an(other) child of the cleanup, or exit the cleanup. In the
  290. // first case, continue searching.
  291. if (isa<Instruction>(ChildUnwindDestToken) &&
  292. getParentPad(ChildUnwindDestToken) == CleanupPad)
  293. continue;
  294. UnwindDestToken = ChildUnwindDestToken;
  295. break;
  296. }
  297. }
  298. // If we haven't found an unwind dest for CurrentPad, we may have queued its
  299. // children, so move on to the next in the worklist.
  300. if (!UnwindDestToken)
  301. continue;
  302. // Now we know that CurrentPad unwinds to UnwindDestToken. It also exits
  303. // any ancestors of CurrentPad up to but not including UnwindDestToken's
  304. // parent pad. Record this in the memo map, and check to see if the
  305. // original EHPad being queried is one of the ones exited.
  306. Value *UnwindParent;
  307. if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken))
  308. UnwindParent = getParentPad(UnwindPad);
  309. else
  310. UnwindParent = nullptr;
  311. bool ExitedOriginalPad = false;
  312. for (Instruction *ExitedPad = CurrentPad;
  313. ExitedPad && ExitedPad != UnwindParent;
  314. ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) {
  315. // Skip over catchpads since they just follow their catchswitches.
  316. if (isa<CatchPadInst>(ExitedPad))
  317. continue;
  318. MemoMap[ExitedPad] = UnwindDestToken;
  319. ExitedOriginalPad |= (ExitedPad == EHPad);
  320. }
  321. if (ExitedOriginalPad)
  322. return UnwindDestToken;
  323. // Continue the search.
  324. }
  325. // No definitive information is contained within this funclet.
  326. return nullptr;
  327. }
  328. /// Given an EH pad, find where it unwinds. If it unwinds to an EH pad,
  329. /// return that pad instruction. If it unwinds to caller, return
  330. /// ConstantTokenNone. If it does not have a definitive unwind destination,
  331. /// return nullptr.
  332. ///
  333. /// This routine gets invoked for calls in funclets in inlinees when inlining
  334. /// an invoke. Since many funclets don't have calls inside them, it's queried
  335. /// on-demand rather than building a map of pads to unwind dests up front.
  336. /// Determining a funclet's unwind dest may require recursively searching its
  337. /// descendants, and also ancestors and cousins if the descendants don't provide
  338. /// an answer. Since most funclets will have their unwind dest immediately
  339. /// available as the unwind dest of a catchswitch or cleanupret, this routine
  340. /// searches top-down from the given pad and then up. To avoid worst-case
  341. /// quadratic run-time given that approach, it uses a memo map to avoid
  342. /// re-processing funclet trees. The callers that rewrite the IR as they go
  343. /// take advantage of this, for correctness, by checking/forcing rewritten
  344. /// pads' entries to match the original callee view.
  345. static Value *getUnwindDestToken(Instruction *EHPad,
  346. UnwindDestMemoTy &MemoMap) {
  347. // Catchpads unwind to the same place as their catchswitch;
  348. // redirct any queries on catchpads so the code below can
  349. // deal with just catchswitches and cleanuppads.
  350. if (auto *CPI = dyn_cast<CatchPadInst>(EHPad))
  351. EHPad = CPI->getCatchSwitch();
  352. // Check if we've already determined the unwind dest for this pad.
  353. auto Memo = MemoMap.find(EHPad);
  354. if (Memo != MemoMap.end())
  355. return Memo->second;
  356. // Search EHPad and, if necessary, its descendants.
  357. Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
  358. assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
  359. if (UnwindDestToken)
  360. return UnwindDestToken;
  361. // No information is available for this EHPad from itself or any of its
  362. // descendants. An unwind all the way out to a pad in the caller would
  363. // need also to agree with the unwind dest of the parent funclet, so
  364. // search up the chain to try to find a funclet with information. Put
  365. // null entries in the memo map to avoid re-processing as we go up.
  366. MemoMap[EHPad] = nullptr;
  367. #ifndef NDEBUG
  368. SmallPtrSet<Instruction *, 4> TempMemos;
  369. TempMemos.insert(EHPad);
  370. #endif
  371. Instruction *LastUselessPad = EHPad;
  372. Value *AncestorToken;
  373. for (AncestorToken = getParentPad(EHPad);
  374. auto *AncestorPad = dyn_cast<Instruction>(AncestorToken);
  375. AncestorToken = getParentPad(AncestorToken)) {
  376. // Skip over catchpads since they just follow their catchswitches.
  377. if (isa<CatchPadInst>(AncestorPad))
  378. continue;
  379. // If the MemoMap had an entry mapping AncestorPad to nullptr, since we
  380. // haven't yet called getUnwindDestTokenHelper for AncestorPad in this
  381. // call to getUnwindDestToken, that would mean that AncestorPad had no
  382. // information in itself, its descendants, or its ancestors. If that
  383. // were the case, then we should also have recorded the lack of information
  384. // for the descendant that we're coming from. So assert that we don't
  385. // find a null entry in the MemoMap for AncestorPad.
  386. assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
  387. auto AncestorMemo = MemoMap.find(AncestorPad);
  388. if (AncestorMemo == MemoMap.end()) {
  389. UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap);
  390. } else {
  391. UnwindDestToken = AncestorMemo->second;
  392. }
  393. if (UnwindDestToken)
  394. break;
  395. LastUselessPad = AncestorPad;
  396. MemoMap[LastUselessPad] = nullptr;
  397. #ifndef NDEBUG
  398. TempMemos.insert(LastUselessPad);
  399. #endif
  400. }
  401. // We know that getUnwindDestTokenHelper was called on LastUselessPad and
  402. // returned nullptr (and likewise for EHPad and any of its ancestors up to
  403. // LastUselessPad), so LastUselessPad has no information from below. Since
  404. // getUnwindDestTokenHelper must investigate all downward paths through
  405. // no-information nodes to prove that a node has no information like this,
  406. // and since any time it finds information it records it in the MemoMap for
  407. // not just the immediately-containing funclet but also any ancestors also
  408. // exited, it must be the case that, walking downward from LastUselessPad,
  409. // visiting just those nodes which have not been mapped to an unwind dest
  410. // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
  411. // they are just used to keep getUnwindDestTokenHelper from repeating work),
  412. // any node visited must have been exhaustively searched with no information
  413. // for it found.
  414. SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
  415. while (!Worklist.empty()) {
  416. Instruction *UselessPad = Worklist.pop_back_val();
  417. auto Memo = MemoMap.find(UselessPad);
  418. if (Memo != MemoMap.end() && Memo->second) {
  419. // Here the name 'UselessPad' is a bit of a misnomer, because we've found
  420. // that it is a funclet that does have information about unwinding to
  421. // a particular destination; its parent was a useless pad.
  422. // Since its parent has no information, the unwind edge must not escape
  423. // the parent, and must target a sibling of this pad. This local unwind
  424. // gives us no information about EHPad. Leave it and the subtree rooted
  425. // at it alone.
  426. assert(getParentPad(Memo->second) == getParentPad(UselessPad));
  427. continue;
  428. }
  429. // We know we don't have information for UselesPad. If it has an entry in
  430. // the MemoMap (mapping it to nullptr), it must be one of the TempMemos
  431. // added on this invocation of getUnwindDestToken; if a previous invocation
  432. // recorded nullptr, it would have had to prove that the ancestors of
  433. // UselessPad, which include LastUselessPad, had no information, and that
  434. // in turn would have required proving that the descendants of
  435. // LastUselesPad, which include EHPad, have no information about
  436. // LastUselessPad, which would imply that EHPad was mapped to nullptr in
  437. // the MemoMap on that invocation, which isn't the case if we got here.
  438. assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
  439. // Assert as we enumerate users that 'UselessPad' doesn't have any unwind
  440. // information that we'd be contradicting by making a map entry for it
  441. // (which is something that getUnwindDestTokenHelper must have proved for
  442. // us to get here). Just assert on is direct users here; the checks in
  443. // this downward walk at its descendants will verify that they don't have
  444. // any unwind edges that exit 'UselessPad' either (i.e. they either have no
  445. // unwind edges or unwind to a sibling).
  446. MemoMap[UselessPad] = UnwindDestToken;
  447. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) {
  448. assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
  449. for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
  450. auto *CatchPad = HandlerBlock->getFirstNonPHI();
  451. for (User *U : CatchPad->users()) {
  452. assert(
  453. (!isa<InvokeInst>(U) ||
  454. (getParentPad(
  455. cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
  456. CatchPad)) &&
  457. "Expected useless pad");
  458. if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
  459. Worklist.push_back(cast<Instruction>(U));
  460. }
  461. }
  462. } else {
  463. assert(isa<CleanupPadInst>(UselessPad));
  464. for (User *U : UselessPad->users()) {
  465. assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
  466. assert((!isa<InvokeInst>(U) ||
  467. (getParentPad(
  468. cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
  469. UselessPad)) &&
  470. "Expected useless pad");
  471. if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
  472. Worklist.push_back(cast<Instruction>(U));
  473. }
  474. }
  475. }
  476. return UnwindDestToken;
  477. }
  478. /// When we inline a basic block into an invoke,
  479. /// we have to turn all of the calls that can throw into invokes.
  480. /// This function analyze BB to see if there are any calls, and if so,
  481. /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
  482. /// nodes in that block with the values specified in InvokeDestPHIValues.
  483. static BasicBlock *HandleCallsInBlockInlinedThroughInvoke(
  484. BasicBlock *BB, BasicBlock *UnwindEdge,
  485. UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
  486. for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
  487. Instruction *I = &*BBI++;
  488. // We only need to check for function calls: inlined invoke
  489. // instructions require no special handling.
  490. CallInst *CI = dyn_cast<CallInst>(I);
  491. if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
  492. continue;
  493. // We do not need to (and in fact, cannot) convert possibly throwing calls
  494. // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
  495. // invokes. The caller's "segment" of the deoptimization continuation
  496. // attached to the newly inlined @llvm.experimental_deoptimize
  497. // (resp. @llvm.experimental.guard) call should contain the exception
  498. // handling logic, if any.
  499. if (auto *F = CI->getCalledFunction())
  500. if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
  501. F->getIntrinsicID() == Intrinsic::experimental_guard)
  502. continue;
  503. if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
  504. // This call is nested inside a funclet. If that funclet has an unwind
  505. // destination within the inlinee, then unwinding out of this call would
  506. // be UB. Rewriting this call to an invoke which targets the inlined
  507. // invoke's unwind dest would give the call's parent funclet multiple
  508. // unwind destinations, which is something that subsequent EH table
  509. // generation can't handle and that the veirifer rejects. So when we
  510. // see such a call, leave it as a call.
  511. auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]);
  512. Value *UnwindDestToken =
  513. getUnwindDestToken(FuncletPad, *FuncletUnwindMap);
  514. if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
  515. continue;
  516. #ifndef NDEBUG
  517. Instruction *MemoKey;
  518. if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
  519. MemoKey = CatchPad->getCatchSwitch();
  520. else
  521. MemoKey = FuncletPad;
  522. assert(FuncletUnwindMap->count(MemoKey) &&
  523. (*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
  524. "must get memoized to avoid confusing later searches");
  525. #endif // NDEBUG
  526. }
  527. changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
  528. return BB;
  529. }
  530. return nullptr;
  531. }
  532. /// If we inlined an invoke site, we need to convert calls
  533. /// in the body of the inlined function into invokes.
  534. ///
  535. /// II is the invoke instruction being inlined. FirstNewBlock is the first
  536. /// block of the inlined code (the last block is the end of the function),
  537. /// and InlineCodeInfo is information about the code that got inlined.
  538. static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
  539. ClonedCodeInfo &InlinedCodeInfo) {
  540. BasicBlock *InvokeDest = II->getUnwindDest();
  541. Function *Caller = FirstNewBlock->getParent();
  542. // The inlined code is currently at the end of the function, scan from the
  543. // start of the inlined code to its end, checking for stuff we need to
  544. // rewrite.
  545. LandingPadInliningInfo Invoke(II);
  546. // Get all of the inlined landing pad instructions.
  547. SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
  548. for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
  549. I != E; ++I)
  550. if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
  551. InlinedLPads.insert(II->getLandingPadInst());
  552. // Append the clauses from the outer landing pad instruction into the inlined
  553. // landing pad instructions.
  554. LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
  555. for (LandingPadInst *InlinedLPad : InlinedLPads) {
  556. unsigned OuterNum = OuterLPad->getNumClauses();
  557. InlinedLPad->reserveClauses(OuterNum);
  558. for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
  559. InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
  560. if (OuterLPad->isCleanup())
  561. InlinedLPad->setCleanup(true);
  562. }
  563. for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
  564. BB != E; ++BB) {
  565. if (InlinedCodeInfo.ContainsCalls)
  566. if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
  567. &*BB, Invoke.getOuterResumeDest()))
  568. // Update any PHI nodes in the exceptional block to indicate that there
  569. // is now a new entry in them.
  570. Invoke.addIncomingPHIValuesFor(NewBB);
  571. // Forward any resumes that are remaining here.
  572. if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
  573. Invoke.forwardResume(RI, InlinedLPads);
  574. }
  575. // Now that everything is happy, we have one final detail. The PHI nodes in
  576. // the exception destination block still have entries due to the original
  577. // invoke instruction. Eliminate these entries (which might even delete the
  578. // PHI node) now.
  579. InvokeDest->removePredecessor(II->getParent());
  580. }
  581. /// If we inlined an invoke site, we need to convert calls
  582. /// in the body of the inlined function into invokes.
  583. ///
  584. /// II is the invoke instruction being inlined. FirstNewBlock is the first
  585. /// block of the inlined code (the last block is the end of the function),
  586. /// and InlineCodeInfo is information about the code that got inlined.
  587. static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
  588. ClonedCodeInfo &InlinedCodeInfo) {
  589. BasicBlock *UnwindDest = II->getUnwindDest();
  590. Function *Caller = FirstNewBlock->getParent();
  591. assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
  592. // If there are PHI nodes in the unwind destination block, we need to keep
  593. // track of which values came into them from the invoke before removing the
  594. // edge from this block.
  595. SmallVector<Value *, 8> UnwindDestPHIValues;
  596. BasicBlock *InvokeBB = II->getParent();
  597. for (Instruction &I : *UnwindDest) {
  598. // Save the value to use for this edge.
  599. PHINode *PHI = dyn_cast<PHINode>(&I);
  600. if (!PHI)
  601. break;
  602. UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
  603. }
  604. // Add incoming-PHI values to the unwind destination block for the given basic
  605. // block, using the values for the original invoke's source block.
  606. auto UpdatePHINodes = [&](BasicBlock *Src) {
  607. BasicBlock::iterator I = UnwindDest->begin();
  608. for (Value *V : UnwindDestPHIValues) {
  609. PHINode *PHI = cast<PHINode>(I);
  610. PHI->addIncoming(V, Src);
  611. ++I;
  612. }
  613. };
  614. // This connects all the instructions which 'unwind to caller' to the invoke
  615. // destination.
  616. UnwindDestMemoTy FuncletUnwindMap;
  617. for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
  618. BB != E; ++BB) {
  619. if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
  620. if (CRI->unwindsToCaller()) {
  621. auto *CleanupPad = CRI->getCleanupPad();
  622. CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI);
  623. CRI->eraseFromParent();
  624. UpdatePHINodes(&*BB);
  625. // Finding a cleanupret with an unwind destination would confuse
  626. // subsequent calls to getUnwindDestToken, so map the cleanuppad
  627. // to short-circuit any such calls and recognize this as an "unwind
  628. // to caller" cleanup.
  629. assert(!FuncletUnwindMap.count(CleanupPad) ||
  630. isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
  631. FuncletUnwindMap[CleanupPad] =
  632. ConstantTokenNone::get(Caller->getContext());
  633. }
  634. }
  635. Instruction *I = BB->getFirstNonPHI();
  636. if (!I->isEHPad())
  637. continue;
  638. Instruction *Replacement = nullptr;
  639. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
  640. if (CatchSwitch->unwindsToCaller()) {
  641. Value *UnwindDestToken;
  642. if (auto *ParentPad =
  643. dyn_cast<Instruction>(CatchSwitch->getParentPad())) {
  644. // This catchswitch is nested inside another funclet. If that
  645. // funclet has an unwind destination within the inlinee, then
  646. // unwinding out of this catchswitch would be UB. Rewriting this
  647. // catchswitch to unwind to the inlined invoke's unwind dest would
  648. // give the parent funclet multiple unwind destinations, which is
  649. // something that subsequent EH table generation can't handle and
  650. // that the veirifer rejects. So when we see such a call, leave it
  651. // as "unwind to caller".
  652. UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap);
  653. if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
  654. continue;
  655. } else {
  656. // This catchswitch has no parent to inherit constraints from, and
  657. // none of its descendants can have an unwind edge that exits it and
  658. // targets another funclet in the inlinee. It may or may not have a
  659. // descendant that definitively has an unwind to caller. In either
  660. // case, we'll have to assume that any unwinds out of it may need to
  661. // be routed to the caller, so treat it as though it has a definitive
  662. // unwind to caller.
  663. UnwindDestToken = ConstantTokenNone::get(Caller->getContext());
  664. }
  665. auto *NewCatchSwitch = CatchSwitchInst::Create(
  666. CatchSwitch->getParentPad(), UnwindDest,
  667. CatchSwitch->getNumHandlers(), CatchSwitch->getName(),
  668. CatchSwitch);
  669. for (BasicBlock *PadBB : CatchSwitch->handlers())
  670. NewCatchSwitch->addHandler(PadBB);
  671. // Propagate info for the old catchswitch over to the new one in
  672. // the unwind map. This also serves to short-circuit any subsequent
  673. // checks for the unwind dest of this catchswitch, which would get
  674. // confused if they found the outer handler in the callee.
  675. FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
  676. Replacement = NewCatchSwitch;
  677. }
  678. } else if (!isa<FuncletPadInst>(I)) {
  679. llvm_unreachable("unexpected EHPad!");
  680. }
  681. if (Replacement) {
  682. Replacement->takeName(I);
  683. I->replaceAllUsesWith(Replacement);
  684. I->eraseFromParent();
  685. UpdatePHINodes(&*BB);
  686. }
  687. }
  688. if (InlinedCodeInfo.ContainsCalls)
  689. for (Function::iterator BB = FirstNewBlock->getIterator(),
  690. E = Caller->end();
  691. BB != E; ++BB)
  692. if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
  693. &*BB, UnwindDest, &FuncletUnwindMap))
  694. // Update any PHI nodes in the exceptional block to indicate that there
  695. // is now a new entry in them.
  696. UpdatePHINodes(NewBB);
  697. // Now that everything is happy, we have one final detail. The PHI nodes in
  698. // the exception destination block still have entries due to the original
  699. // invoke instruction. Eliminate these entries (which might even delete the
  700. // PHI node) now.
  701. UnwindDest->removePredecessor(InvokeBB);
  702. }
  703. /// When inlining a call site that has !llvm.mem.parallel_loop_access or
  704. /// llvm.access.group metadata, that metadata should be propagated to all
  705. /// memory-accessing cloned instructions.
  706. static void PropagateParallelLoopAccessMetadata(CallSite CS,
  707. ValueToValueMapTy &VMap) {
  708. MDNode *M =
  709. CS.getInstruction()->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
  710. MDNode *CallAccessGroup =
  711. CS.getInstruction()->getMetadata(LLVMContext::MD_access_group);
  712. if (!M && !CallAccessGroup)
  713. return;
  714. for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
  715. VMI != VMIE; ++VMI) {
  716. if (!VMI->second)
  717. continue;
  718. Instruction *NI = dyn_cast<Instruction>(VMI->second);
  719. if (!NI)
  720. continue;
  721. if (M) {
  722. if (MDNode *PM =
  723. NI->getMetadata(LLVMContext::MD_mem_parallel_loop_access)) {
  724. M = MDNode::concatenate(PM, M);
  725. NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
  726. } else if (NI->mayReadOrWriteMemory()) {
  727. NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
  728. }
  729. }
  730. if (NI->mayReadOrWriteMemory()) {
  731. MDNode *UnitedAccGroups = uniteAccessGroups(
  732. NI->getMetadata(LLVMContext::MD_access_group), CallAccessGroup);
  733. NI->setMetadata(LLVMContext::MD_access_group, UnitedAccGroups);
  734. }
  735. }
  736. }
  737. /// When inlining a function that contains noalias scope metadata,
  738. /// this metadata needs to be cloned so that the inlined blocks
  739. /// have different "unique scopes" at every call site. Were this not done, then
  740. /// aliasing scopes from a function inlined into a caller multiple times could
  741. /// not be differentiated (and this would lead to miscompiles because the
  742. /// non-aliasing property communicated by the metadata could have
  743. /// call-site-specific control dependencies).
  744. static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
  745. const Function *CalledFunc = CS.getCalledFunction();
  746. SetVector<const MDNode *> MD;
  747. // Note: We could only clone the metadata if it is already used in the
  748. // caller. I'm omitting that check here because it might confuse
  749. // inter-procedural alias analysis passes. We can revisit this if it becomes
  750. // an efficiency or overhead problem.
  751. for (const BasicBlock &I : *CalledFunc)
  752. for (const Instruction &J : I) {
  753. if (const MDNode *M = J.getMetadata(LLVMContext::MD_alias_scope))
  754. MD.insert(M);
  755. if (const MDNode *M = J.getMetadata(LLVMContext::MD_noalias))
  756. MD.insert(M);
  757. }
  758. if (MD.empty())
  759. return;
  760. // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
  761. // the set.
  762. SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
  763. while (!Queue.empty()) {
  764. const MDNode *M = cast<MDNode>(Queue.pop_back_val());
  765. for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
  766. if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
  767. if (MD.insert(M1))
  768. Queue.push_back(M1);
  769. }
  770. // Now we have a complete set of all metadata in the chains used to specify
  771. // the noalias scopes and the lists of those scopes.
  772. SmallVector<TempMDTuple, 16> DummyNodes;
  773. DenseMap<const MDNode *, TrackingMDNodeRef> MDMap;
  774. for (const MDNode *I : MD) {
  775. DummyNodes.push_back(MDTuple::getTemporary(CalledFunc->getContext(), None));
  776. MDMap[I].reset(DummyNodes.back().get());
  777. }
  778. // Create new metadata nodes to replace the dummy nodes, replacing old
  779. // metadata references with either a dummy node or an already-created new
  780. // node.
  781. for (const MDNode *I : MD) {
  782. SmallVector<Metadata *, 4> NewOps;
  783. for (unsigned i = 0, ie = I->getNumOperands(); i != ie; ++i) {
  784. const Metadata *V = I->getOperand(i);
  785. if (const MDNode *M = dyn_cast<MDNode>(V))
  786. NewOps.push_back(MDMap[M]);
  787. else
  788. NewOps.push_back(const_cast<Metadata *>(V));
  789. }
  790. MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps);
  791. MDTuple *TempM = cast<MDTuple>(MDMap[I]);
  792. assert(TempM->isTemporary() && "Expected temporary node");
  793. TempM->replaceAllUsesWith(NewM);
  794. }
  795. // Now replace the metadata in the new inlined instructions with the
  796. // repacements from the map.
  797. for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
  798. VMI != VMIE; ++VMI) {
  799. if (!VMI->second)
  800. continue;
  801. Instruction *NI = dyn_cast<Instruction>(VMI->second);
  802. if (!NI)
  803. continue;
  804. if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope)) {
  805. MDNode *NewMD = MDMap[M];
  806. // If the call site also had alias scope metadata (a list of scopes to
  807. // which instructions inside it might belong), propagate those scopes to
  808. // the inlined instructions.
  809. if (MDNode *CSM =
  810. CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
  811. NewMD = MDNode::concatenate(NewMD, CSM);
  812. NI->setMetadata(LLVMContext::MD_alias_scope, NewMD);
  813. } else if (NI->mayReadOrWriteMemory()) {
  814. if (MDNode *M =
  815. CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
  816. NI->setMetadata(LLVMContext::MD_alias_scope, M);
  817. }
  818. if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias)) {
  819. MDNode *NewMD = MDMap[M];
  820. // If the call site also had noalias metadata (a list of scopes with
  821. // which instructions inside it don't alias), propagate those scopes to
  822. // the inlined instructions.
  823. if (MDNode *CSM =
  824. CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
  825. NewMD = MDNode::concatenate(NewMD, CSM);
  826. NI->setMetadata(LLVMContext::MD_noalias, NewMD);
  827. } else if (NI->mayReadOrWriteMemory()) {
  828. if (MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
  829. NI->setMetadata(LLVMContext::MD_noalias, M);
  830. }
  831. }
  832. }
  833. /// If the inlined function has noalias arguments,
  834. /// then add new alias scopes for each noalias argument, tag the mapped noalias
  835. /// parameters with noalias metadata specifying the new scope, and tag all
  836. /// non-derived loads, stores and memory intrinsics with the new alias scopes.
  837. static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
  838. const DataLayout &DL, AAResults *CalleeAAR) {
  839. if (!EnableNoAliasConversion)
  840. return;
  841. const Function *CalledFunc = CS.getCalledFunction();
  842. SmallVector<const Argument *, 4> NoAliasArgs;
  843. for (const Argument &Arg : CalledFunc->args())
  844. if (Arg.hasNoAliasAttr() && !Arg.use_empty())
  845. NoAliasArgs.push_back(&Arg);
  846. if (NoAliasArgs.empty())
  847. return;
  848. // To do a good job, if a noalias variable is captured, we need to know if
  849. // the capture point dominates the particular use we're considering.
  850. DominatorTree DT;
  851. DT.recalculate(const_cast<Function&>(*CalledFunc));
  852. // noalias indicates that pointer values based on the argument do not alias
  853. // pointer values which are not based on it. So we add a new "scope" for each
  854. // noalias function argument. Accesses using pointers based on that argument
  855. // become part of that alias scope, accesses using pointers not based on that
  856. // argument are tagged as noalias with that scope.
  857. DenseMap<const Argument *, MDNode *> NewScopes;
  858. MDBuilder MDB(CalledFunc->getContext());
  859. // Create a new scope domain for this function.
  860. MDNode *NewDomain =
  861. MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
  862. for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
  863. const Argument *A = NoAliasArgs[i];
  864. std::string Name = CalledFunc->getName();
  865. if (A->hasName()) {
  866. Name += ": %";
  867. Name += A->getName();
  868. } else {
  869. Name += ": argument ";
  870. Name += utostr(i);
  871. }
  872. // Note: We always create a new anonymous root here. This is true regardless
  873. // of the linkage of the callee because the aliasing "scope" is not just a
  874. // property of the callee, but also all control dependencies in the caller.
  875. MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
  876. NewScopes.insert(std::make_pair(A, NewScope));
  877. }
  878. // Iterate over all new instructions in the map; for all memory-access
  879. // instructions, add the alias scope metadata.
  880. for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
  881. VMI != VMIE; ++VMI) {
  882. if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
  883. if (!VMI->second)
  884. continue;
  885. Instruction *NI = dyn_cast<Instruction>(VMI->second);
  886. if (!NI)
  887. continue;
  888. bool IsArgMemOnlyCall = false, IsFuncCall = false;
  889. SmallVector<const Value *, 2> PtrArgs;
  890. if (const LoadInst *LI = dyn_cast<LoadInst>(I))
  891. PtrArgs.push_back(LI->getPointerOperand());
  892. else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
  893. PtrArgs.push_back(SI->getPointerOperand());
  894. else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
  895. PtrArgs.push_back(VAAI->getPointerOperand());
  896. else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
  897. PtrArgs.push_back(CXI->getPointerOperand());
  898. else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
  899. PtrArgs.push_back(RMWI->getPointerOperand());
  900. else if (ImmutableCallSite ICS = ImmutableCallSite(I)) {
  901. // If we know that the call does not access memory, then we'll still
  902. // know that about the inlined clone of this call site, and we don't
  903. // need to add metadata.
  904. if (ICS.doesNotAccessMemory())
  905. continue;
  906. IsFuncCall = true;
  907. if (CalleeAAR) {
  908. FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(ICS);
  909. if (MRB == FMRB_OnlyAccessesArgumentPointees ||
  910. MRB == FMRB_OnlyReadsArgumentPointees)
  911. IsArgMemOnlyCall = true;
  912. }
  913. for (Value *Arg : ICS.args()) {
  914. // We need to check the underlying objects of all arguments, not just
  915. // the pointer arguments, because we might be passing pointers as
  916. // integers, etc.
  917. // However, if we know that the call only accesses pointer arguments,
  918. // then we only need to check the pointer arguments.
  919. if (IsArgMemOnlyCall && !Arg->getType()->isPointerTy())
  920. continue;
  921. PtrArgs.push_back(Arg);
  922. }
  923. }
  924. // If we found no pointers, then this instruction is not suitable for
  925. // pairing with an instruction to receive aliasing metadata.
  926. // However, if this is a call, this we might just alias with none of the
  927. // noalias arguments.
  928. if (PtrArgs.empty() && !IsFuncCall)
  929. continue;
  930. // It is possible that there is only one underlying object, but you
  931. // need to go through several PHIs to see it, and thus could be
  932. // repeated in the Objects list.
  933. SmallPtrSet<const Value *, 4> ObjSet;
  934. SmallVector<Metadata *, 4> Scopes, NoAliases;
  935. SmallSetVector<const Argument *, 4> NAPtrArgs;
  936. for (const Value *V : PtrArgs) {
  937. SmallVector<Value *, 4> Objects;
  938. GetUnderlyingObjects(const_cast<Value*>(V),
  939. Objects, DL, /* LI = */ nullptr);
  940. for (Value *O : Objects)
  941. ObjSet.insert(O);
  942. }
  943. // Figure out if we're derived from anything that is not a noalias
  944. // argument.
  945. bool CanDeriveViaCapture = false, UsesAliasingPtr = false;
  946. for (const Value *V : ObjSet) {
  947. // Is this value a constant that cannot be derived from any pointer
  948. // value (we need to exclude constant expressions, for example, that
  949. // are formed from arithmetic on global symbols).
  950. bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
  951. isa<ConstantPointerNull>(V) ||
  952. isa<ConstantDataVector>(V) || isa<UndefValue>(V);
  953. if (IsNonPtrConst)
  954. continue;
  955. // If this is anything other than a noalias argument, then we cannot
  956. // completely describe the aliasing properties using alias.scope
  957. // metadata (and, thus, won't add any).
  958. if (const Argument *A = dyn_cast<Argument>(V)) {
  959. if (!A->hasNoAliasAttr())
  960. UsesAliasingPtr = true;
  961. } else {
  962. UsesAliasingPtr = true;
  963. }
  964. // If this is not some identified function-local object (which cannot
  965. // directly alias a noalias argument), or some other argument (which,
  966. // by definition, also cannot alias a noalias argument), then we could
  967. // alias a noalias argument that has been captured).
  968. if (!isa<Argument>(V) &&
  969. !isIdentifiedFunctionLocal(const_cast<Value*>(V)))
  970. CanDeriveViaCapture = true;
  971. }
  972. // A function call can always get captured noalias pointers (via other
  973. // parameters, globals, etc.).
  974. if (IsFuncCall && !IsArgMemOnlyCall)
  975. CanDeriveViaCapture = true;
  976. // First, we want to figure out all of the sets with which we definitely
  977. // don't alias. Iterate over all noalias set, and add those for which:
  978. // 1. The noalias argument is not in the set of objects from which we
  979. // definitely derive.
  980. // 2. The noalias argument has not yet been captured.
  981. // An arbitrary function that might load pointers could see captured
  982. // noalias arguments via other noalias arguments or globals, and so we
  983. // must always check for prior capture.
  984. for (const Argument *A : NoAliasArgs) {
  985. if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
  986. // It might be tempting to skip the
  987. // PointerMayBeCapturedBefore check if
  988. // A->hasNoCaptureAttr() is true, but this is
  989. // incorrect because nocapture only guarantees
  990. // that no copies outlive the function, not
  991. // that the value cannot be locally captured.
  992. !PointerMayBeCapturedBefore(A,
  993. /* ReturnCaptures */ false,
  994. /* StoreCaptures */ false, I, &DT)))
  995. NoAliases.push_back(NewScopes[A]);
  996. }
  997. if (!NoAliases.empty())
  998. NI->setMetadata(LLVMContext::MD_noalias,
  999. MDNode::concatenate(
  1000. NI->getMetadata(LLVMContext::MD_noalias),
  1001. MDNode::get(CalledFunc->getContext(), NoAliases)));
  1002. // Next, we want to figure out all of the sets to which we might belong.
  1003. // We might belong to a set if the noalias argument is in the set of
  1004. // underlying objects. If there is some non-noalias argument in our list
  1005. // of underlying objects, then we cannot add a scope because the fact
  1006. // that some access does not alias with any set of our noalias arguments
  1007. // cannot itself guarantee that it does not alias with this access
  1008. // (because there is some pointer of unknown origin involved and the
  1009. // other access might also depend on this pointer). We also cannot add
  1010. // scopes to arbitrary functions unless we know they don't access any
  1011. // non-parameter pointer-values.
  1012. bool CanAddScopes = !UsesAliasingPtr;
  1013. if (CanAddScopes && IsFuncCall)
  1014. CanAddScopes = IsArgMemOnlyCall;
  1015. if (CanAddScopes)
  1016. for (const Argument *A : NoAliasArgs) {
  1017. if (ObjSet.count(A))
  1018. Scopes.push_back(NewScopes[A]);
  1019. }
  1020. if (!Scopes.empty())
  1021. NI->setMetadata(
  1022. LLVMContext::MD_alias_scope,
  1023. MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
  1024. MDNode::get(CalledFunc->getContext(), Scopes)));
  1025. }
  1026. }
  1027. }
  1028. /// If the inlined function has non-byval align arguments, then
  1029. /// add @llvm.assume-based alignment assumptions to preserve this information.
  1030. static void AddAlignmentAssumptions(CallSite CS, InlineFunctionInfo &IFI) {
  1031. if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache)
  1032. return;
  1033. AssumptionCache *AC = &(*IFI.GetAssumptionCache)(*CS.getCaller());
  1034. auto &DL = CS.getCaller()->getParent()->getDataLayout();
  1035. // To avoid inserting redundant assumptions, we should check for assumptions
  1036. // already in the caller. To do this, we might need a DT of the caller.
  1037. DominatorTree DT;
  1038. bool DTCalculated = false;
  1039. Function *CalledFunc = CS.getCalledFunction();
  1040. for (Argument &Arg : CalledFunc->args()) {
  1041. unsigned Align = Arg.getType()->isPointerTy() ? Arg.getParamAlignment() : 0;
  1042. if (Align && !Arg.hasByValOrInAllocaAttr() && !Arg.hasNUses(0)) {
  1043. if (!DTCalculated) {
  1044. DT.recalculate(*CS.getCaller());
  1045. DTCalculated = true;
  1046. }
  1047. // If we can already prove the asserted alignment in the context of the
  1048. // caller, then don't bother inserting the assumption.
  1049. Value *ArgVal = CS.getArgument(Arg.getArgNo());
  1050. if (getKnownAlignment(ArgVal, DL, CS.getInstruction(), AC, &DT) >= Align)
  1051. continue;
  1052. CallInst *NewAsmp = IRBuilder<>(CS.getInstruction())
  1053. .CreateAlignmentAssumption(DL, ArgVal, Align);
  1054. AC->registerAssumption(NewAsmp);
  1055. }
  1056. }
  1057. }
  1058. /// Once we have cloned code over from a callee into the caller,
  1059. /// update the specified callgraph to reflect the changes we made.
  1060. /// Note that it's possible that not all code was copied over, so only
  1061. /// some edges of the callgraph may remain.
  1062. static void UpdateCallGraphAfterInlining(CallSite CS,
  1063. Function::iterator FirstNewBlock,
  1064. ValueToValueMapTy &VMap,
  1065. InlineFunctionInfo &IFI) {
  1066. CallGraph &CG = *IFI.CG;
  1067. const Function *Caller = CS.getCaller();
  1068. const Function *Callee = CS.getCalledFunction();
  1069. CallGraphNode *CalleeNode = CG[Callee];
  1070. CallGraphNode *CallerNode = CG[Caller];
  1071. // Since we inlined some uninlined call sites in the callee into the caller,
  1072. // add edges from the caller to all of the callees of the callee.
  1073. CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
  1074. // Consider the case where CalleeNode == CallerNode.
  1075. CallGraphNode::CalledFunctionsVector CallCache;
  1076. if (CalleeNode == CallerNode) {
  1077. CallCache.assign(I, E);
  1078. I = CallCache.begin();
  1079. E = CallCache.end();
  1080. }
  1081. for (; I != E; ++I) {
  1082. const Value *OrigCall = I->first;
  1083. ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
  1084. // Only copy the edge if the call was inlined!
  1085. if (VMI == VMap.end() || VMI->second == nullptr)
  1086. continue;
  1087. // If the call was inlined, but then constant folded, there is no edge to
  1088. // add. Check for this case.
  1089. Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
  1090. if (!NewCall)
  1091. continue;
  1092. // We do not treat intrinsic calls like real function calls because we
  1093. // expect them to become inline code; do not add an edge for an intrinsic.
  1094. CallSite CS = CallSite(NewCall);
  1095. if (CS && CS.getCalledFunction() && CS.getCalledFunction()->isIntrinsic())
  1096. continue;
  1097. // Remember that this call site got inlined for the client of
  1098. // InlineFunction.
  1099. IFI.InlinedCalls.push_back(NewCall);
  1100. // It's possible that inlining the callsite will cause it to go from an
  1101. // indirect to a direct call by resolving a function pointer. If this
  1102. // happens, set the callee of the new call site to a more precise
  1103. // destination. This can also happen if the call graph node of the caller
  1104. // was just unnecessarily imprecise.
  1105. if (!I->second->getFunction())
  1106. if (Function *F = CallSite(NewCall).getCalledFunction()) {
  1107. // Indirect call site resolved to direct call.
  1108. CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
  1109. continue;
  1110. }
  1111. CallerNode->addCalledFunction(CallSite(NewCall), I->second);
  1112. }
  1113. // Update the call graph by deleting the edge from Callee to Caller. We must
  1114. // do this after the loop above in case Caller and Callee are the same.
  1115. CallerNode->removeCallEdgeFor(CS);
  1116. }
  1117. static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
  1118. BasicBlock *InsertBlock,
  1119. InlineFunctionInfo &IFI) {
  1120. Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
  1121. IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
  1122. Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy));
  1123. // Always generate a memcpy of alignment 1 here because we don't know
  1124. // the alignment of the src pointer. Other optimizations can infer
  1125. // better alignment.
  1126. Builder.CreateMemCpy(Dst, /*DstAlign*/1, Src, /*SrcAlign*/1, Size);
  1127. }
  1128. /// When inlining a call site that has a byval argument,
  1129. /// we have to make the implicit memcpy explicit by adding it.
  1130. static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
  1131. const Function *CalledFunc,
  1132. InlineFunctionInfo &IFI,
  1133. unsigned ByValAlignment) {
  1134. PointerType *ArgTy = cast<PointerType>(Arg->getType());
  1135. Type *AggTy = ArgTy->getElementType();
  1136. Function *Caller = TheCall->getFunction();
  1137. const DataLayout &DL = Caller->getParent()->getDataLayout();
  1138. // If the called function is readonly, then it could not mutate the caller's
  1139. // copy of the byval'd memory. In this case, it is safe to elide the copy and
  1140. // temporary.
  1141. if (CalledFunc->onlyReadsMemory()) {
  1142. // If the byval argument has a specified alignment that is greater than the
  1143. // passed in pointer, then we either have to round up the input pointer or
  1144. // give up on this transformation.
  1145. if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment.
  1146. return Arg;
  1147. AssumptionCache *AC =
  1148. IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
  1149. // If the pointer is already known to be sufficiently aligned, or if we can
  1150. // round it up to a larger alignment, then we don't need a temporary.
  1151. if (getOrEnforceKnownAlignment(Arg, ByValAlignment, DL, TheCall, AC) >=
  1152. ByValAlignment)
  1153. return Arg;
  1154. // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
  1155. // for code quality, but rarely happens and is required for correctness.
  1156. }
  1157. // Create the alloca. If we have DataLayout, use nice alignment.
  1158. unsigned Align = DL.getPrefTypeAlignment(AggTy);
  1159. // If the byval had an alignment specified, we *must* use at least that
  1160. // alignment, as it is required by the byval argument (and uses of the
  1161. // pointer inside the callee).
  1162. Align = std::max(Align, ByValAlignment);
  1163. Value *NewAlloca = new AllocaInst(AggTy, DL.getAllocaAddrSpace(),
  1164. nullptr, Align, Arg->getName(),
  1165. &*Caller->begin()->begin());
  1166. IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
  1167. // Uses of the argument in the function should use our new alloca
  1168. // instead.
  1169. return NewAlloca;
  1170. }
  1171. // Check whether this Value is used by a lifetime intrinsic.
  1172. static bool isUsedByLifetimeMarker(Value *V) {
  1173. for (User *U : V->users()) {
  1174. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
  1175. switch (II->getIntrinsicID()) {
  1176. default: break;
  1177. case Intrinsic::lifetime_start:
  1178. case Intrinsic::lifetime_end:
  1179. return true;
  1180. }
  1181. }
  1182. }
  1183. return false;
  1184. }
  1185. // Check whether the given alloca already has
  1186. // lifetime.start or lifetime.end intrinsics.
  1187. static bool hasLifetimeMarkers(AllocaInst *AI) {
  1188. Type *Ty = AI->getType();
  1189. Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
  1190. Ty->getPointerAddressSpace());
  1191. if (Ty == Int8PtrTy)
  1192. return isUsedByLifetimeMarker(AI);
  1193. // Do a scan to find all the casts to i8*.
  1194. for (User *U : AI->users()) {
  1195. if (U->getType() != Int8PtrTy) continue;
  1196. if (U->stripPointerCasts() != AI) continue;
  1197. if (isUsedByLifetimeMarker(U))
  1198. return true;
  1199. }
  1200. return false;
  1201. }
  1202. /// Return the result of AI->isStaticAlloca() if AI were moved to the entry
  1203. /// block. Allocas used in inalloca calls and allocas of dynamic array size
  1204. /// cannot be static.
  1205. static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) {
  1206. return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca();
  1207. }
  1208. /// Update inlined instructions' line numbers to
  1209. /// to encode location where these instructions are inlined.
  1210. static void fixupLineNumbers(Function *Fn, Function::iterator FI,
  1211. Instruction *TheCall, bool CalleeHasDebugInfo) {
  1212. const DebugLoc &TheCallDL = TheCall->getDebugLoc();
  1213. if (!TheCallDL)
  1214. return;
  1215. auto &Ctx = Fn->getContext();
  1216. DILocation *InlinedAtNode = TheCallDL;
  1217. // Create a unique call site, not to be confused with any other call from the
  1218. // same location.
  1219. InlinedAtNode = DILocation::getDistinct(
  1220. Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
  1221. InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());
  1222. // Cache the inlined-at nodes as they're built so they are reused, without
  1223. // this every instruction's inlined-at chain would become distinct from each
  1224. // other.
  1225. DenseMap<const MDNode *, MDNode *> IANodes;
  1226. for (; FI != Fn->end(); ++FI) {
  1227. for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
  1228. BI != BE; ++BI) {
  1229. if (DebugLoc DL = BI->getDebugLoc()) {
  1230. auto IA = DebugLoc::appendInlinedAt(DL, InlinedAtNode, BI->getContext(),
  1231. IANodes);
  1232. auto IDL = DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(), IA);
  1233. BI->setDebugLoc(IDL);
  1234. continue;
  1235. }
  1236. if (CalleeHasDebugInfo)
  1237. continue;
  1238. // If the inlined instruction has no line number, make it look as if it
  1239. // originates from the call location. This is important for
  1240. // ((__always_inline__, __nodebug__)) functions which must use caller
  1241. // location for all instructions in their function body.
  1242. // Don't update static allocas, as they may get moved later.
  1243. if (auto *AI = dyn_cast<AllocaInst>(BI))
  1244. if (allocaWouldBeStaticInEntry(AI))
  1245. continue;
  1246. BI->setDebugLoc(TheCallDL);
  1247. }
  1248. }
  1249. }
  1250. /// Update the block frequencies of the caller after a callee has been inlined.
  1251. ///
  1252. /// Each block cloned into the caller has its block frequency scaled by the
  1253. /// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of
  1254. /// callee's entry block gets the same frequency as the callsite block and the
  1255. /// relative frequencies of all cloned blocks remain the same after cloning.
  1256. static void updateCallerBFI(BasicBlock *CallSiteBlock,
  1257. const ValueToValueMapTy &VMap,
  1258. BlockFrequencyInfo *CallerBFI,
  1259. BlockFrequencyInfo *CalleeBFI,
  1260. const BasicBlock &CalleeEntryBlock) {
  1261. SmallPtrSet<BasicBlock *, 16> ClonedBBs;
  1262. for (auto const &Entry : VMap) {
  1263. if (!isa<BasicBlock>(Entry.first) || !Entry.second)
  1264. continue;
  1265. auto *OrigBB = cast<BasicBlock>(Entry.first);
  1266. auto *ClonedBB = cast<BasicBlock>(Entry.second);
  1267. uint64_t Freq = CalleeBFI->getBlockFreq(OrigBB).getFrequency();
  1268. if (!ClonedBBs.insert(ClonedBB).second) {
  1269. // Multiple blocks in the callee might get mapped to one cloned block in
  1270. // the caller since we prune the callee as we clone it. When that happens,
  1271. // we want to use the maximum among the original blocks' frequencies.
  1272. uint64_t NewFreq = CallerBFI->getBlockFreq(ClonedBB).getFrequency();
  1273. if (NewFreq > Freq)
  1274. Freq = NewFreq;
  1275. }
  1276. CallerBFI->setBlockFreq(ClonedBB, Freq);
  1277. }
  1278. BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock));
  1279. CallerBFI->setBlockFreqAndScale(
  1280. EntryClone, CallerBFI->getBlockFreq(CallSiteBlock).getFrequency(),
  1281. ClonedBBs);
  1282. }
  1283. /// Update the branch metadata for cloned call instructions.
  1284. static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap,
  1285. const ProfileCount &CalleeEntryCount,
  1286. const Instruction *TheCall,
  1287. ProfileSummaryInfo *PSI,
  1288. BlockFrequencyInfo *CallerBFI) {
  1289. if (!CalleeEntryCount.hasValue() || CalleeEntryCount.isSynthetic() ||
  1290. CalleeEntryCount.getCount() < 1)
  1291. return;
  1292. auto CallSiteCount = PSI ? PSI->getProfileCount(TheCall, CallerBFI) : None;
  1293. uint64_t CallCount =
  1294. std::min(CallSiteCount.hasValue() ? CallSiteCount.getValue() : 0,
  1295. CalleeEntryCount.getCount());
  1296. for (auto const &Entry : VMap)
  1297. if (isa<CallInst>(Entry.first))
  1298. if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second))
  1299. CI->updateProfWeight(CallCount, CalleeEntryCount.getCount());
  1300. for (BasicBlock &BB : *Callee)
  1301. // No need to update the callsite if it is pruned during inlining.
  1302. if (VMap.count(&BB))
  1303. for (Instruction &I : BB)
  1304. if (CallInst *CI = dyn_cast<CallInst>(&I))
  1305. CI->updateProfWeight(CalleeEntryCount.getCount() - CallCount,
  1306. CalleeEntryCount.getCount());
  1307. }
  1308. /// Update the entry count of callee after inlining.
  1309. ///
  1310. /// The callsite's block count is subtracted from the callee's function entry
  1311. /// count.
  1312. static void updateCalleeCount(BlockFrequencyInfo *CallerBFI, BasicBlock *CallBB,
  1313. Instruction *CallInst, Function *Callee,
  1314. ProfileSummaryInfo *PSI) {
  1315. // If the callee has a original count of N, and the estimated count of
  1316. // callsite is M, the new callee count is set to N - M. M is estimated from
  1317. // the caller's entry count, its entry block frequency and the block frequency
  1318. // of the callsite.
  1319. auto CalleeCount = Callee->getEntryCount();
  1320. if (!CalleeCount.hasValue() || !PSI)
  1321. return;
  1322. auto CallCount = PSI->getProfileCount(CallInst, CallerBFI);
  1323. if (!CallCount.hasValue())
  1324. return;
  1325. // Since CallSiteCount is an estimate, it could exceed the original callee
  1326. // count and has to be set to 0.
  1327. if (CallCount.getValue() > CalleeCount.getCount())
  1328. CalleeCount.setCount(0);
  1329. else
  1330. CalleeCount.setCount(CalleeCount.getCount() - CallCount.getValue());
  1331. Callee->setEntryCount(CalleeCount);
  1332. }
  1333. /// This function inlines the called function into the basic block of the
  1334. /// caller. This returns false if it is not possible to inline this call.
  1335. /// The program is still in a well defined state if this occurs though.
  1336. ///
  1337. /// Note that this only does one level of inlining. For example, if the
  1338. /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
  1339. /// exists in the instruction stream. Similarly this will inline a recursive
  1340. /// function by one level.
  1341. llvm::InlineResult llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
  1342. AAResults *CalleeAAR,
  1343. bool InsertLifetime,
  1344. Function *ForwardVarArgsTo) {
  1345. Instruction *TheCall = CS.getInstruction();
  1346. assert(TheCall->getParent() && TheCall->getFunction()
  1347. && "Instruction not in function!");
  1348. // If IFI has any state in it, zap it before we fill it in.
  1349. IFI.reset();
  1350. Function *CalledFunc = CS.getCalledFunction();
  1351. if (!CalledFunc || // Can't inline external function or indirect
  1352. CalledFunc->isDeclaration()) // call!
  1353. return "external or indirect";
  1354. // The inliner does not know how to inline through calls with operand bundles
  1355. // in general ...
  1356. if (CS.hasOperandBundles()) {
  1357. for (int i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
  1358. uint32_t Tag = CS.getOperandBundleAt(i).getTagID();
  1359. // ... but it knows how to inline through "deopt" operand bundles ...
  1360. if (Tag == LLVMContext::OB_deopt)
  1361. continue;
  1362. // ... and "funclet" operand bundles.
  1363. if (Tag == LLVMContext::OB_funclet)
  1364. continue;
  1365. return "unsupported operand bundle";
  1366. }
  1367. }
  1368. // If the call to the callee cannot throw, set the 'nounwind' flag on any
  1369. // calls that we inline.
  1370. bool MarkNoUnwind = CS.doesNotThrow();
  1371. BasicBlock *OrigBB = TheCall->getParent();
  1372. Function *Caller = OrigBB->getParent();
  1373. // GC poses two hazards to inlining, which only occur when the callee has GC:
  1374. // 1. If the caller has no GC, then the callee's GC must be propagated to the
  1375. // caller.
  1376. // 2. If the caller has a differing GC, it is invalid to inline.
  1377. if (CalledFunc->hasGC()) {
  1378. if (!Caller->hasGC())
  1379. Caller->setGC(CalledFunc->getGC());
  1380. else if (CalledFunc->getGC() != Caller->getGC())
  1381. return "incompatible GC";
  1382. }
  1383. // Get the personality function from the callee if it contains a landing pad.
  1384. Constant *CalledPersonality =
  1385. CalledFunc->hasPersonalityFn()
  1386. ? CalledFunc->getPersonalityFn()->stripPointerCasts()
  1387. : nullptr;
  1388. // Find the personality function used by the landing pads of the caller. If it
  1389. // exists, then check to see that it matches the personality function used in
  1390. // the callee.
  1391. Constant *CallerPersonality =
  1392. Caller->hasPersonalityFn()
  1393. ? Caller->getPersonalityFn()->stripPointerCasts()
  1394. : nullptr;
  1395. if (CalledPersonality) {
  1396. if (!CallerPersonality)
  1397. Caller->setPersonalityFn(CalledPersonality);
  1398. // If the personality functions match, then we can perform the
  1399. // inlining. Otherwise, we can't inline.
  1400. // TODO: This isn't 100% true. Some personality functions are proper
  1401. // supersets of others and can be used in place of the other.
  1402. else if (CalledPersonality != CallerPersonality)
  1403. return "incompatible personality";
  1404. }
  1405. // We need to figure out which funclet the callsite was in so that we may
  1406. // properly nest the callee.
  1407. Instruction *CallSiteEHPad = nullptr;
  1408. if (CallerPersonality) {
  1409. EHPersonality Personality = classifyEHPersonality(CallerPersonality);
  1410. if (isScopedEHPersonality(Personality)) {
  1411. Optional<OperandBundleUse> ParentFunclet =
  1412. CS.getOperandBundle(LLVMContext::OB_funclet);
  1413. if (ParentFunclet)
  1414. CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front());
  1415. // OK, the inlining site is legal. What about the target function?
  1416. if (CallSiteEHPad) {
  1417. if (Personality == EHPersonality::MSVC_CXX) {
  1418. // The MSVC personality cannot tolerate catches getting inlined into
  1419. // cleanup funclets.
  1420. if (isa<CleanupPadInst>(CallSiteEHPad)) {
  1421. // Ok, the call site is within a cleanuppad. Let's check the callee
  1422. // for catchpads.
  1423. for (const BasicBlock &CalledBB : *CalledFunc) {
  1424. if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI()))
  1425. return "catch in cleanup funclet";
  1426. }
  1427. }
  1428. } else if (isAsynchronousEHPersonality(Personality)) {
  1429. // SEH is even less tolerant, there may not be any sort of exceptional
  1430. // funclet in the callee.
  1431. for (const BasicBlock &CalledBB : *CalledFunc) {
  1432. if (CalledBB.isEHPad())
  1433. return "SEH in cleanup funclet";
  1434. }
  1435. }
  1436. }
  1437. }
  1438. }
  1439. // Determine if we are dealing with a call in an EHPad which does not unwind
  1440. // to caller.
  1441. bool EHPadForCallUnwindsLocally = false;
  1442. if (CallSiteEHPad && CS.isCall()) {
  1443. UnwindDestMemoTy FuncletUnwindMap;
  1444. Value *CallSiteUnwindDestToken =
  1445. getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap);
  1446. EHPadForCallUnwindsLocally =
  1447. CallSiteUnwindDestToken &&
  1448. !isa<ConstantTokenNone>(CallSiteUnwindDestToken);
  1449. }
  1450. // Get an iterator to the last basic block in the function, which will have
  1451. // the new function inlined after it.
  1452. Function::iterator LastBlock = --Caller->end();
  1453. // Make sure to capture all of the return instructions from the cloned
  1454. // function.
  1455. SmallVector<ReturnInst*, 8> Returns;
  1456. ClonedCodeInfo InlinedFunctionInfo;
  1457. Function::iterator FirstNewBlock;
  1458. { // Scope to destroy VMap after cloning.
  1459. ValueToValueMapTy VMap;
  1460. // Keep a list of pair (dst, src) to emit byval initializations.
  1461. SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
  1462. auto &DL = Caller->getParent()->getDataLayout();
  1463. // Calculate the vector of arguments to pass into the function cloner, which
  1464. // matches up the formal to the actual argument values.
  1465. CallSite::arg_iterator AI = CS.arg_begin();
  1466. unsigned ArgNo = 0;
  1467. for (Function::arg_iterator I = CalledFunc->arg_begin(),
  1468. E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
  1469. Value *ActualArg = *AI;
  1470. // When byval arguments actually inlined, we need to make the copy implied
  1471. // by them explicit. However, we don't do this if the callee is readonly
  1472. // or readnone, because the copy would be unneeded: the callee doesn't
  1473. // modify the struct.
  1474. if (CS.isByValArgument(ArgNo)) {
  1475. ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
  1476. CalledFunc->getParamAlignment(ArgNo));
  1477. if (ActualArg != *AI)
  1478. ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
  1479. }
  1480. VMap[&*I] = ActualArg;
  1481. }
  1482. // Add alignment assumptions if necessary. We do this before the inlined
  1483. // instructions are actually cloned into the caller so that we can easily
  1484. // check what will be known at the start of the inlined code.
  1485. AddAlignmentAssumptions(CS, IFI);
  1486. // We want the inliner to prune the code as it copies. We would LOVE to
  1487. // have no dead or constant instructions leftover after inlining occurs
  1488. // (which can happen, e.g., because an argument was constant), but we'll be
  1489. // happy with whatever the cloner can do.
  1490. CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
  1491. /*ModuleLevelChanges=*/false, Returns, ".i",
  1492. &InlinedFunctionInfo, TheCall);
  1493. // Remember the first block that is newly cloned over.
  1494. FirstNewBlock = LastBlock; ++FirstNewBlock;
  1495. if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr)
  1496. // Update the BFI of blocks cloned into the caller.
  1497. updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI,
  1498. CalledFunc->front());
  1499. updateCallProfile(CalledFunc, VMap, CalledFunc->getEntryCount(), TheCall,
  1500. IFI.PSI, IFI.CallerBFI);
  1501. // Update the profile count of callee.
  1502. updateCalleeCount(IFI.CallerBFI, OrigBB, TheCall, CalledFunc, IFI.PSI);
  1503. // Inject byval arguments initialization.
  1504. for (std::pair<Value*, Value*> &Init : ByValInit)
  1505. HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
  1506. &*FirstNewBlock, IFI);
  1507. Optional<OperandBundleUse> ParentDeopt =
  1508. CS.getOperandBundle(LLVMContext::OB_deopt);
  1509. if (ParentDeopt) {
  1510. SmallVector<OperandBundleDef, 2> OpDefs;
  1511. for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
  1512. Instruction *I = dyn_cast_or_null<Instruction>(VH);
  1513. if (!I) continue; // instruction was DCE'd or RAUW'ed to undef
  1514. OpDefs.clear();
  1515. CallSite ICS(I);
  1516. OpDefs.reserve(ICS.getNumOperandBundles());
  1517. for (unsigned i = 0, e = ICS.getNumOperandBundles(); i < e; ++i) {
  1518. auto ChildOB = ICS.getOperandBundleAt(i);
  1519. if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
  1520. // If the inlined call has other operand bundles, let them be
  1521. OpDefs.emplace_back(ChildOB);
  1522. continue;
  1523. }
  1524. // It may be useful to separate this logic (of handling operand
  1525. // bundles) out to a separate "policy" component if this gets crowded.
  1526. // Prepend the parent's deoptimization continuation to the newly
  1527. // inlined call's deoptimization continuation.
  1528. std::vector<Value *> MergedDeoptArgs;
  1529. MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() +
  1530. ChildOB.Inputs.size());
  1531. MergedDeoptArgs.insert(MergedDeoptArgs.end(),
  1532. ParentDeopt->Inputs.begin(),
  1533. ParentDeopt->Inputs.end());
  1534. MergedDeoptArgs.insert(MergedDeoptArgs.end(), ChildOB.Inputs.begin(),
  1535. ChildOB.Inputs.end());
  1536. OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs));
  1537. }
  1538. Instruction *NewI = nullptr;
  1539. if (isa<CallInst>(I))
  1540. NewI = CallInst::Create(cast<CallInst>(I), OpDefs, I);
  1541. else
  1542. NewI = InvokeInst::Create(cast<InvokeInst>(I), OpDefs, I);
  1543. // Note: the RAUW does the appropriate fixup in VMap, so we need to do
  1544. // this even if the call returns void.
  1545. I->replaceAllUsesWith(NewI);
  1546. VH = nullptr;
  1547. I->eraseFromParent();
  1548. }
  1549. }
  1550. // Update the callgraph if requested.
  1551. if (IFI.CG)
  1552. UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
  1553. // For 'nodebug' functions, the associated DISubprogram is always null.
  1554. // Conservatively avoid propagating the callsite debug location to
  1555. // instructions inlined from a function whose DISubprogram is not null.
  1556. fixupLineNumbers(Caller, FirstNewBlock, TheCall,
  1557. CalledFunc->getSubprogram() != nullptr);
  1558. // Clone existing noalias metadata if necessary.
  1559. CloneAliasScopeMetadata(CS, VMap);
  1560. // Add noalias metadata if necessary.
  1561. AddAliasScopeMetadata(CS, VMap, DL, CalleeAAR);
  1562. // Propagate llvm.mem.parallel_loop_access if necessary.
  1563. PropagateParallelLoopAccessMetadata(CS, VMap);
  1564. // Register any cloned assumptions.
  1565. if (IFI.GetAssumptionCache)
  1566. for (BasicBlock &NewBlock :
  1567. make_range(FirstNewBlock->getIterator(), Caller->end()))
  1568. for (Instruction &I : NewBlock) {
  1569. if (auto *II = dyn_cast<IntrinsicInst>(&I))
  1570. if (II->getIntrinsicID() == Intrinsic::assume)
  1571. (*IFI.GetAssumptionCache)(*Caller).registerAssumption(II);
  1572. }
  1573. }
  1574. // If there are any alloca instructions in the block that used to be the entry
  1575. // block for the callee, move them to the entry block of the caller. First
  1576. // calculate which instruction they should be inserted before. We insert the
  1577. // instructions at the end of the current alloca list.
  1578. {
  1579. BasicBlock::iterator InsertPoint = Caller->begin()->begin();
  1580. for (BasicBlock::iterator I = FirstNewBlock->begin(),
  1581. E = FirstNewBlock->end(); I != E; ) {
  1582. AllocaInst *AI = dyn_cast<AllocaInst>(I++);
  1583. if (!AI) continue;
  1584. // If the alloca is now dead, remove it. This often occurs due to code
  1585. // specialization.
  1586. if (AI->use_empty()) {
  1587. AI->eraseFromParent();
  1588. continue;
  1589. }
  1590. if (!allocaWouldBeStaticInEntry(AI))
  1591. continue;
  1592. // Keep track of the static allocas that we inline into the caller.
  1593. IFI.StaticAllocas.push_back(AI);
  1594. // Scan for the block of allocas that we can move over, and move them
  1595. // all at once.
  1596. while (isa<AllocaInst>(I) &&
  1597. allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) {
  1598. IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
  1599. ++I;
  1600. }
  1601. // Transfer all of the allocas over in a block. Using splice means
  1602. // that the instructions aren't removed from the symbol table, then
  1603. // reinserted.
  1604. Caller->getEntryBlock().getInstList().splice(
  1605. InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I);
  1606. }
  1607. // Move any dbg.declares describing the allocas into the entry basic block.
  1608. DIBuilder DIB(*Caller->getParent());
  1609. for (auto &AI : IFI.StaticAllocas)
  1610. replaceDbgDeclareForAlloca(AI, AI, DIB, DIExpression::NoDeref, 0,
  1611. DIExpression::NoDeref);
  1612. }
  1613. SmallVector<Value*,4> VarArgsToForward;
  1614. SmallVector<AttributeSet, 4> VarArgsAttrs;
  1615. for (unsigned i = CalledFunc->getFunctionType()->getNumParams();
  1616. i < CS.getNumArgOperands(); i++) {
  1617. VarArgsToForward.push_back(CS.getArgOperand(i));
  1618. VarArgsAttrs.push_back(CS.getAttributes().getParamAttributes(i));
  1619. }
  1620. bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false;
  1621. if (InlinedFunctionInfo.ContainsCalls) {
  1622. CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
  1623. if (CallInst *CI = dyn_cast<CallInst>(TheCall))
  1624. CallSiteTailKind = CI->getTailCallKind();
  1625. // For inlining purposes, the "notail" marker is the same as no marker.
  1626. if (CallSiteTailKind == CallInst::TCK_NoTail)
  1627. CallSiteTailKind = CallInst::TCK_None;
  1628. for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
  1629. ++BB) {
  1630. for (auto II = BB->begin(); II != BB->end();) {
  1631. Instruction &I = *II++;
  1632. CallInst *CI = dyn_cast<CallInst>(&I);
  1633. if (!CI)
  1634. continue;
  1635. // Forward varargs from inlined call site to calls to the
  1636. // ForwardVarArgsTo function, if requested, and to musttail calls.
  1637. if (!VarArgsToForward.empty() &&
  1638. ((ForwardVarArgsTo &&
  1639. CI->getCalledFunction() == ForwardVarArgsTo) ||
  1640. CI->isMustTailCall())) {
  1641. // Collect attributes for non-vararg parameters.
  1642. AttributeList Attrs = CI->getAttributes();
  1643. SmallVector<AttributeSet, 8> ArgAttrs;
  1644. if (!Attrs.isEmpty() || !VarArgsAttrs.empty()) {
  1645. for (unsigned ArgNo = 0;
  1646. ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo)
  1647. ArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
  1648. }
  1649. // Add VarArg attributes.
  1650. ArgAttrs.append(VarArgsAttrs.begin(), VarArgsAttrs.end());
  1651. Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttributes(),
  1652. Attrs.getRetAttributes(), ArgAttrs);
  1653. // Add VarArgs to existing parameters.
  1654. SmallVector<Value *, 6> Params(CI->arg_operands());
  1655. Params.append(VarArgsToForward.begin(), VarArgsToForward.end());
  1656. CallInst *NewCI =
  1657. CallInst::Create(CI->getCalledFunction() ? CI->getCalledFunction()
  1658. : CI->getCalledValue(),
  1659. Params, "", CI);
  1660. NewCI->setDebugLoc(CI->getDebugLoc());
  1661. NewCI->setAttributes(Attrs);
  1662. NewCI->setCallingConv(CI->getCallingConv());
  1663. CI->replaceAllUsesWith(NewCI);
  1664. CI->eraseFromParent();
  1665. CI = NewCI;
  1666. }
  1667. if (Function *F = CI->getCalledFunction())
  1668. InlinedDeoptimizeCalls |=
  1669. F->getIntrinsicID() == Intrinsic::experimental_deoptimize;
  1670. // We need to reduce the strength of any inlined tail calls. For
  1671. // musttail, we have to avoid introducing potential unbounded stack
  1672. // growth. For example, if functions 'f' and 'g' are mutually recursive
  1673. // with musttail, we can inline 'g' into 'f' so long as we preserve
  1674. // musttail on the cloned call to 'f'. If either the inlined call site
  1675. // or the cloned call site is *not* musttail, the program already has
  1676. // one frame of stack growth, so it's safe to remove musttail. Here is
  1677. // a table of example transformations:
  1678. //
  1679. // f -> musttail g -> musttail f ==> f -> musttail f
  1680. // f -> musttail g -> tail f ==> f -> tail f
  1681. // f -> g -> musttail f ==> f -> f
  1682. // f -> g -> tail f ==> f -> f
  1683. //
  1684. // Inlined notail calls should remain notail calls.
  1685. CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
  1686. if (ChildTCK != CallInst::TCK_NoTail)
  1687. ChildTCK = std::min(CallSiteTailKind, ChildTCK);
  1688. CI->setTailCallKind(ChildTCK);
  1689. InlinedMustTailCalls |= CI->isMustTailCall();
  1690. // Calls inlined through a 'nounwind' call site should be marked
  1691. // 'nounwind'.
  1692. if (MarkNoUnwind)
  1693. CI->setDoesNotThrow();
  1694. }
  1695. }
  1696. }
  1697. // Leave lifetime markers for the static alloca's, scoping them to the
  1698. // function we just inlined.
  1699. if (InsertLifetime && !IFI.StaticAllocas.empty()) {
  1700. IRBuilder<> builder(&FirstNewBlock->front());
  1701. for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
  1702. AllocaInst *AI = IFI.StaticAllocas[ai];
  1703. // Don't mark swifterror allocas. They can't have bitcast uses.
  1704. if (AI->isSwiftError())
  1705. continue;
  1706. // If the alloca is already scoped to something smaller than the whole
  1707. // function then there's no need to add redundant, less accurate markers.
  1708. if (hasLifetimeMarkers(AI))
  1709. continue;
  1710. // Try to determine the size of the allocation.
  1711. ConstantInt *AllocaSize = nullptr;
  1712. if (ConstantInt *AIArraySize =
  1713. dyn_cast<ConstantInt>(AI->getArraySize())) {
  1714. auto &DL = Caller->getParent()->getDataLayout();
  1715. Type *AllocaType = AI->getAllocatedType();
  1716. uint64_t AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
  1717. uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
  1718. // Don't add markers for zero-sized allocas.
  1719. if (AllocaArraySize == 0)
  1720. continue;
  1721. // Check that array size doesn't saturate uint64_t and doesn't
  1722. // overflow when it's multiplied by type size.
  1723. if (AllocaArraySize != std::numeric_limits<uint64_t>::max() &&
  1724. std::numeric_limits<uint64_t>::max() / AllocaArraySize >=
  1725. AllocaTypeSize) {
  1726. AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
  1727. AllocaArraySize * AllocaTypeSize);
  1728. }
  1729. }
  1730. builder.CreateLifetimeStart(AI, AllocaSize);
  1731. for (ReturnInst *RI : Returns) {
  1732. // Don't insert llvm.lifetime.end calls between a musttail or deoptimize
  1733. // call and a return. The return kills all local allocas.
  1734. if (InlinedMustTailCalls &&
  1735. RI->getParent()->getTerminatingMustTailCall())
  1736. continue;
  1737. if (InlinedDeoptimizeCalls &&
  1738. RI->getParent()->getTerminatingDeoptimizeCall())
  1739. continue;
  1740. IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
  1741. }
  1742. }
  1743. }
  1744. // If the inlined code contained dynamic alloca instructions, wrap the inlined
  1745. // code with llvm.stacksave/llvm.stackrestore intrinsics.
  1746. if (InlinedFunctionInfo.ContainsDynamicAllocas) {
  1747. Module *M = Caller->getParent();
  1748. // Get the two intrinsics we care about.
  1749. Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
  1750. Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
  1751. // Insert the llvm.stacksave.
  1752. CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin())
  1753. .CreateCall(StackSave, {}, "savedstack");
  1754. // Insert a call to llvm.stackrestore before any return instructions in the
  1755. // inlined function.
  1756. for (ReturnInst *RI : Returns) {
  1757. // Don't insert llvm.stackrestore calls between a musttail or deoptimize
  1758. // call and a return. The return will restore the stack pointer.
  1759. if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
  1760. continue;
  1761. if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall())
  1762. continue;
  1763. IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
  1764. }
  1765. }
  1766. // If we are inlining for an invoke instruction, we must make sure to rewrite
  1767. // any call instructions into invoke instructions. This is sensitive to which
  1768. // funclet pads were top-level in the inlinee, so must be done before
  1769. // rewriting the "parent pad" links.
  1770. if (auto *II = dyn_cast<InvokeInst>(TheCall)) {
  1771. BasicBlock *UnwindDest = II->getUnwindDest();
  1772. Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI();
  1773. if (isa<LandingPadInst>(FirstNonPHI)) {
  1774. HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
  1775. } else {
  1776. HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
  1777. }
  1778. }
  1779. // Update the lexical scopes of the new funclets and callsites.
  1780. // Anything that had 'none' as its parent is now nested inside the callsite's
  1781. // EHPad.
  1782. if (CallSiteEHPad) {
  1783. for (Function::iterator BB = FirstNewBlock->getIterator(),
  1784. E = Caller->end();
  1785. BB != E; ++BB) {
  1786. // Add bundle operands to any top-level call sites.
  1787. SmallVector<OperandBundleDef, 1> OpBundles;
  1788. for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;) {
  1789. Instruction *I = &*BBI++;
  1790. CallSite CS(I);
  1791. if (!CS)
  1792. continue;
  1793. // Skip call sites which are nounwind intrinsics.
  1794. auto *CalledFn =
  1795. dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
  1796. if (CalledFn && CalledFn->isIntrinsic() && CS.doesNotThrow())
  1797. continue;
  1798. // Skip call sites which already have a "funclet" bundle.
  1799. if (CS.getOperandBundle(LLVMContext::OB_funclet))
  1800. continue;
  1801. CS.getOperandBundlesAsDefs(OpBundles);
  1802. OpBundles.emplace_back("funclet", CallSiteEHPad);
  1803. Instruction *NewInst;
  1804. if (CS.isCall())
  1805. NewInst = CallInst::Create(cast<CallInst>(I), OpBundles, I);
  1806. else
  1807. NewInst = InvokeInst::Create(cast<InvokeInst>(I), OpBundles, I);
  1808. NewInst->takeName(I);
  1809. I->replaceAllUsesWith(NewInst);
  1810. I->eraseFromParent();
  1811. OpBundles.clear();
  1812. }
  1813. // It is problematic if the inlinee has a cleanupret which unwinds to
  1814. // caller and we inline it into a call site which doesn't unwind but into
  1815. // an EH pad that does. Such an edge must be dynamically unreachable.
  1816. // As such, we replace the cleanupret with unreachable.
  1817. if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator()))
  1818. if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally)
  1819. changeToUnreachable(CleanupRet, /*UseLLVMTrap=*/false);
  1820. Instruction *I = BB->getFirstNonPHI();
  1821. if (!I->isEHPad())
  1822. continue;
  1823. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
  1824. if (isa<ConstantTokenNone>(CatchSwitch->getParentPad()))
  1825. CatchSwitch->setParentPad(CallSiteEHPad);
  1826. } else {
  1827. auto *FPI = cast<FuncletPadInst>(I);
  1828. if (isa<ConstantTokenNone>(FPI->getParentPad()))
  1829. FPI->setParentPad(CallSiteEHPad);
  1830. }
  1831. }
  1832. }
  1833. if (InlinedDeoptimizeCalls) {
  1834. // We need to at least remove the deoptimizing returns from the Return set,
  1835. // so that the control flow from those returns does not get merged into the
  1836. // caller (but terminate it instead). If the caller's return type does not
  1837. // match the callee's return type, we also need to change the return type of
  1838. // the intrinsic.
  1839. if (Caller->getReturnType() == TheCall->getType()) {
  1840. auto NewEnd = llvm::remove_if(Returns, [](ReturnInst *RI) {
  1841. return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr;
  1842. });
  1843. Returns.erase(NewEnd, Returns.end());
  1844. } else {
  1845. SmallVector<ReturnInst *, 8> NormalReturns;
  1846. Function *NewDeoptIntrinsic = Intrinsic::getDeclaration(
  1847. Caller->getParent(), Intrinsic::experimental_deoptimize,
  1848. {Caller->getReturnType()});
  1849. for (ReturnInst *RI : Returns) {
  1850. CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall();
  1851. if (!DeoptCall) {
  1852. NormalReturns.push_back(RI);
  1853. continue;
  1854. }
  1855. // The calling convention on the deoptimize call itself may be bogus,
  1856. // since the code we're inlining may have undefined behavior (and may
  1857. // never actually execute at runtime); but all
  1858. // @llvm.experimental.deoptimize declarations have to have the same
  1859. // calling convention in a well-formed module.
  1860. auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv();
  1861. NewDeoptIntrinsic->setCallingConv(CallingConv);
  1862. auto *CurBB = RI->getParent();
  1863. RI->eraseFromParent();
  1864. SmallVector<Value *, 4> CallArgs(DeoptCall->arg_begin(),
  1865. DeoptCall->arg_end());
  1866. SmallVector<OperandBundleDef, 1> OpBundles;
  1867. DeoptCall->getOperandBundlesAsDefs(OpBundles);
  1868. DeoptCall->eraseFromParent();
  1869. assert(!OpBundles.empty() &&
  1870. "Expected at least the deopt operand bundle");
  1871. IRBuilder<> Builder(CurBB);
  1872. CallInst *NewDeoptCall =
  1873. Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles);
  1874. NewDeoptCall->setCallingConv(CallingConv);
  1875. if (NewDeoptCall->getType()->isVoidTy())
  1876. Builder.CreateRetVoid();
  1877. else
  1878. Builder.CreateRet(NewDeoptCall);
  1879. }
  1880. // Leave behind the normal returns so we can merge control flow.
  1881. std::swap(Returns, NormalReturns);
  1882. }
  1883. }
  1884. // Handle any inlined musttail call sites. In order for a new call site to be
  1885. // musttail, the source of the clone and the inlined call site must have been
  1886. // musttail. Therefore it's safe to return without merging control into the
  1887. // phi below.
  1888. if (InlinedMustTailCalls) {
  1889. // Check if we need to bitcast the result of any musttail calls.
  1890. Type *NewRetTy = Caller->getReturnType();
  1891. bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
  1892. // Handle the returns preceded by musttail calls separately.
  1893. SmallVector<ReturnInst *, 8> NormalReturns;
  1894. for (ReturnInst *RI : Returns) {
  1895. CallInst *ReturnedMustTail =
  1896. RI->getParent()->getTerminatingMustTailCall();
  1897. if (!ReturnedMustTail) {
  1898. NormalReturns.push_back(RI);
  1899. continue;
  1900. }
  1901. if (!NeedBitCast)
  1902. continue;
  1903. // Delete the old return and any preceding bitcast.
  1904. BasicBlock *CurBB = RI->getParent();
  1905. auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
  1906. RI->eraseFromParent();
  1907. if (OldCast)
  1908. OldCast->eraseFromParent();
  1909. // Insert a new bitcast and return with the right type.
  1910. IRBuilder<> Builder(CurBB);
  1911. Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
  1912. }
  1913. // Leave behind the normal returns so we can merge control flow.
  1914. std::swap(Returns, NormalReturns);
  1915. }
  1916. // Now that all of the transforms on the inlined code have taken place but
  1917. // before we splice the inlined code into the CFG and lose track of which
  1918. // blocks were actually inlined, collect the call sites. We only do this if
  1919. // call graph updates weren't requested, as those provide value handle based
  1920. // tracking of inlined call sites instead.
  1921. if (InlinedFunctionInfo.ContainsCalls && !IFI.CG) {
  1922. // Otherwise just collect the raw call sites that were inlined.
  1923. for (BasicBlock &NewBB :
  1924. make_range(FirstNewBlock->getIterator(), Caller->end()))
  1925. for (Instruction &I : NewBB)
  1926. if (auto CS = CallSite(&I))
  1927. IFI.InlinedCallSites.push_back(CS);
  1928. }
  1929. // If we cloned in _exactly one_ basic block, and if that block ends in a
  1930. // return instruction, we splice the body of the inlined callee directly into
  1931. // the calling basic block.
  1932. if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
  1933. // Move all of the instructions right before the call.
  1934. OrigBB->getInstList().splice(TheCall->getIterator(),
  1935. FirstNewBlock->getInstList(),
  1936. FirstNewBlock->begin(), FirstNewBlock->end());
  1937. // Remove the cloned basic block.
  1938. Caller->getBasicBlockList().pop_back();
  1939. // If the call site was an invoke instruction, add a branch to the normal
  1940. // destination.
  1941. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
  1942. BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
  1943. NewBr->setDebugLoc(Returns[0]->getDebugLoc());
  1944. }
  1945. // If the return instruction returned a value, replace uses of the call with
  1946. // uses of the returned value.
  1947. if (!TheCall->use_empty()) {
  1948. ReturnInst *R = Returns[0];
  1949. if (TheCall == R->getReturnValue())
  1950. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  1951. else
  1952. TheCall->replaceAllUsesWith(R->getReturnValue());
  1953. }
  1954. // Since we are now done with the Call/Invoke, we can delete it.
  1955. TheCall->eraseFromParent();
  1956. // Since we are now done with the return instruction, delete it also.
  1957. Returns[0]->eraseFromParent();
  1958. // We are now done with the inlining.
  1959. return true;
  1960. }
  1961. // Otherwise, we have the normal case, of more than one block to inline or
  1962. // multiple return sites.
  1963. // We want to clone the entire callee function into the hole between the
  1964. // "starter" and "ender" blocks. How we accomplish this depends on whether
  1965. // this is an invoke instruction or a call instruction.
  1966. BasicBlock *AfterCallBB;
  1967. BranchInst *CreatedBranchToNormalDest = nullptr;
  1968. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
  1969. // Add an unconditional branch to make this look like the CallInst case...
  1970. CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
  1971. // Split the basic block. This guarantees that no PHI nodes will have to be
  1972. // updated due to new incoming edges, and make the invoke case more
  1973. // symmetric to the call case.
  1974. AfterCallBB =
  1975. OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
  1976. CalledFunc->getName() + ".exit");
  1977. } else { // It's a call
  1978. // If this is a call instruction, we need to split the basic block that
  1979. // the call lives in.
  1980. //
  1981. AfterCallBB = OrigBB->splitBasicBlock(TheCall->getIterator(),
  1982. CalledFunc->getName() + ".exit");
  1983. }
  1984. if (IFI.CallerBFI) {
  1985. // Copy original BB's block frequency to AfterCallBB
  1986. IFI.CallerBFI->setBlockFreq(
  1987. AfterCallBB, IFI.CallerBFI->getBlockFreq(OrigBB).getFrequency());
  1988. }
  1989. // Change the branch that used to go to AfterCallBB to branch to the first
  1990. // basic block of the inlined function.
  1991. //
  1992. Instruction *Br = OrigBB->getTerminator();
  1993. assert(Br && Br->getOpcode() == Instruction::Br &&
  1994. "splitBasicBlock broken!");
  1995. Br->setOperand(0, &*FirstNewBlock);
  1996. // Now that the function is correct, make it a little bit nicer. In
  1997. // particular, move the basic blocks inserted from the end of the function
  1998. // into the space made by splitting the source basic block.
  1999. Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
  2000. Caller->getBasicBlockList(), FirstNewBlock,
  2001. Caller->end());
  2002. // Handle all of the return instructions that we just cloned in, and eliminate
  2003. // any users of the original call/invoke instruction.
  2004. Type *RTy = CalledFunc->getReturnType();
  2005. PHINode *PHI = nullptr;
  2006. if (Returns.size() > 1) {
  2007. // The PHI node should go at the front of the new basic block to merge all
  2008. // possible incoming values.
  2009. if (!TheCall->use_empty()) {
  2010. PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
  2011. &AfterCallBB->front());
  2012. // Anything that used the result of the function call should now use the
  2013. // PHI node as their operand.
  2014. TheCall->replaceAllUsesWith(PHI);
  2015. }
  2016. // Loop over all of the return instructions adding entries to the PHI node
  2017. // as appropriate.
  2018. if (PHI) {
  2019. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  2020. ReturnInst *RI = Returns[i];
  2021. assert(RI->getReturnValue()->getType() == PHI->getType() &&
  2022. "Ret value not consistent in function!");
  2023. PHI->addIncoming(RI->getReturnValue(), RI->getParent());
  2024. }
  2025. }
  2026. // Add a branch to the merge points and remove return instructions.
  2027. DebugLoc Loc;
  2028. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  2029. ReturnInst *RI = Returns[i];
  2030. BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
  2031. Loc = RI->getDebugLoc();
  2032. BI->setDebugLoc(Loc);
  2033. RI->eraseFromParent();
  2034. }
  2035. // We need to set the debug location to *somewhere* inside the
  2036. // inlined function. The line number may be nonsensical, but the
  2037. // instruction will at least be associated with the right
  2038. // function.
  2039. if (CreatedBranchToNormalDest)
  2040. CreatedBranchToNormalDest->setDebugLoc(Loc);
  2041. } else if (!Returns.empty()) {
  2042. // Otherwise, if there is exactly one return value, just replace anything
  2043. // using the return value of the call with the computed value.
  2044. if (!TheCall->use_empty()) {
  2045. if (TheCall == Returns[0]->getReturnValue())
  2046. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  2047. else
  2048. TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
  2049. }
  2050. // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
  2051. BasicBlock *ReturnBB = Returns[0]->getParent();
  2052. ReturnBB->replaceAllUsesWith(AfterCallBB);
  2053. // Splice the code from the return block into the block that it will return
  2054. // to, which contains the code that was after the call.
  2055. AfterCallBB->getInstList().splice(AfterCallBB->begin(),
  2056. ReturnBB->getInstList());
  2057. if (CreatedBranchToNormalDest)
  2058. CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
  2059. // Delete the return instruction now and empty ReturnBB now.
  2060. Returns[0]->eraseFromParent();
  2061. ReturnBB->eraseFromParent();
  2062. } else if (!TheCall->use_empty()) {
  2063. // No returns, but something is using the return value of the call. Just
  2064. // nuke the result.
  2065. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  2066. }
  2067. // Since we are now done with the Call/Invoke, we can delete it.
  2068. TheCall->eraseFromParent();
  2069. // If we inlined any musttail calls and the original return is now
  2070. // unreachable, delete it. It can only contain a bitcast and ret.
  2071. if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
  2072. AfterCallBB->eraseFromParent();
  2073. // We should always be able to fold the entry block of the function into the
  2074. // single predecessor of the block...
  2075. assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
  2076. BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
  2077. // Splice the code entry block into calling block, right before the
  2078. // unconditional branch.
  2079. CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
  2080. OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
  2081. // Remove the unconditional branch.
  2082. OrigBB->getInstList().erase(Br);
  2083. // Now we can remove the CalleeEntry block, which is now empty.
  2084. Caller->getBasicBlockList().erase(CalleeEntry);
  2085. // If we inserted a phi node, check to see if it has a single value (e.g. all
  2086. // the entries are the same or undef). If so, remove the PHI so it doesn't
  2087. // block other optimizations.
  2088. if (PHI) {
  2089. AssumptionCache *AC =
  2090. IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
  2091. auto &DL = Caller->getParent()->getDataLayout();
  2092. if (Value *V = SimplifyInstruction(PHI, {DL, nullptr, nullptr, AC})) {
  2093. PHI->replaceAllUsesWith(V);
  2094. PHI->eraseFromParent();
  2095. }
  2096. }
  2097. return true;
  2098. }