InlineFunction.cpp 97 KB

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