InlineFunction.cpp 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915
  1. //===- InlineFunction.cpp - Code to perform function inlining -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements inlining of a function into a call site, resolving
  10. // parameters and the return value as appropriate.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SetVector.h"
  16. #include "llvm/ADT/SmallPtrSet.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/ADT/iterator_range.h"
  20. #include "llvm/Analysis/AliasAnalysis.h"
  21. #include "llvm/Analysis/AssumptionCache.h"
  22. #include "llvm/Analysis/BlockFrequencyInfo.h"
  23. #include "llvm/Analysis/CallGraph.h"
  24. #include "llvm/Analysis/CaptureTracking.h"
  25. #include "llvm/Analysis/EHPersonalities.h"
  26. #include "llvm/Analysis/InstructionSimplify.h"
  27. #include "llvm/Analysis/MemoryProfileInfo.h"
  28. #include "llvm/Analysis/ObjCARCAnalysisUtils.h"
  29. #include "llvm/Analysis/ObjCARCUtil.h"
  30. #include "llvm/Analysis/ProfileSummaryInfo.h"
  31. #include "llvm/Analysis/ValueTracking.h"
  32. #include "llvm/Analysis/VectorUtils.h"
  33. #include "llvm/IR/Argument.h"
  34. #include "llvm/IR/BasicBlock.h"
  35. #include "llvm/IR/CFG.h"
  36. #include "llvm/IR/Constant.h"
  37. #include "llvm/IR/Constants.h"
  38. #include "llvm/IR/DataLayout.h"
  39. #include "llvm/IR/DebugInfo.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/InlineAsm.h"
  47. #include "llvm/IR/InstrTypes.h"
  48. #include "llvm/IR/Instruction.h"
  49. #include "llvm/IR/Instructions.h"
  50. #include "llvm/IR/IntrinsicInst.h"
  51. #include "llvm/IR/Intrinsics.h"
  52. #include "llvm/IR/LLVMContext.h"
  53. #include "llvm/IR/MDBuilder.h"
  54. #include "llvm/IR/Metadata.h"
  55. #include "llvm/IR/Module.h"
  56. #include "llvm/IR/Type.h"
  57. #include "llvm/IR/User.h"
  58. #include "llvm/IR/Value.h"
  59. #include "llvm/Support/Casting.h"
  60. #include "llvm/Support/CommandLine.h"
  61. #include "llvm/Support/ErrorHandling.h"
  62. #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
  63. #include "llvm/Transforms/Utils/Cloning.h"
  64. #include "llvm/Transforms/Utils/Local.h"
  65. #include "llvm/Transforms/Utils/ValueMapper.h"
  66. #include <algorithm>
  67. #include <cassert>
  68. #include <cstdint>
  69. #include <iterator>
  70. #include <limits>
  71. #include <optional>
  72. #include <string>
  73. #include <utility>
  74. #include <vector>
  75. #define DEBUG_TYPE "inline-function"
  76. using namespace llvm;
  77. using namespace llvm::memprof;
  78. using ProfileCount = Function::ProfileCount;
  79. static cl::opt<bool>
  80. EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
  81. cl::Hidden,
  82. cl::desc("Convert noalias attributes to metadata during inlining."));
  83. static cl::opt<bool>
  84. UseNoAliasIntrinsic("use-noalias-intrinsic-during-inlining", cl::Hidden,
  85. cl::init(true),
  86. cl::desc("Use the llvm.experimental.noalias.scope.decl "
  87. "intrinsic during inlining."));
  88. // Disabled by default, because the added alignment assumptions may increase
  89. // compile-time and block optimizations. This option is not suitable for use
  90. // with frontends that emit comprehensive parameter alignment annotations.
  91. static cl::opt<bool>
  92. PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
  93. cl::init(false), cl::Hidden,
  94. cl::desc("Convert align attributes to assumptions during inlining."));
  95. static cl::opt<bool> UpdateReturnAttributes(
  96. "update-return-attrs", cl::init(true), cl::Hidden,
  97. cl::desc("Update return attributes on calls within inlined body"));
  98. static cl::opt<unsigned> InlinerAttributeWindow(
  99. "max-inst-checked-for-throw-during-inlining", cl::Hidden,
  100. cl::desc("the maximum number of instructions analyzed for may throw during "
  101. "attribute inference in inlined body"),
  102. cl::init(4));
  103. namespace {
  104. /// A class for recording information about inlining a landing pad.
  105. class LandingPadInliningInfo {
  106. /// Destination of the invoke's unwind.
  107. BasicBlock *OuterResumeDest;
  108. /// Destination for the callee's resume.
  109. BasicBlock *InnerResumeDest = nullptr;
  110. /// LandingPadInst associated with the invoke.
  111. LandingPadInst *CallerLPad = nullptr;
  112. /// PHI for EH values from landingpad insts.
  113. PHINode *InnerEHValuesPHI = nullptr;
  114. SmallVector<Value*, 8> UnwindDestPHIValues;
  115. public:
  116. LandingPadInliningInfo(InvokeInst *II)
  117. : OuterResumeDest(II->getUnwindDest()) {
  118. // If there are PHI nodes in the unwind destination block, we need to keep
  119. // track of which values came into them from the invoke before removing
  120. // the edge from this block.
  121. BasicBlock *InvokeBB = II->getParent();
  122. BasicBlock::iterator I = OuterResumeDest->begin();
  123. for (; isa<PHINode>(I); ++I) {
  124. // Save the value to use for this edge.
  125. PHINode *PHI = cast<PHINode>(I);
  126. UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
  127. }
  128. CallerLPad = cast<LandingPadInst>(I);
  129. }
  130. /// The outer unwind destination is the target of
  131. /// unwind edges introduced for calls within the inlined function.
  132. BasicBlock *getOuterResumeDest() const {
  133. return OuterResumeDest;
  134. }
  135. BasicBlock *getInnerResumeDest();
  136. LandingPadInst *getLandingPadInst() const { return CallerLPad; }
  137. /// Forward the 'resume' instruction to the caller's landing pad block.
  138. /// When the landing pad block has only one predecessor, this is
  139. /// a simple branch. When there is more than one predecessor, we need to
  140. /// split the landing pad block after the landingpad instruction and jump
  141. /// to there.
  142. void forwardResume(ResumeInst *RI,
  143. SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
  144. /// Add incoming-PHI values to the unwind destination block for the given
  145. /// basic block, using the values for the original invoke's source block.
  146. void addIncomingPHIValuesFor(BasicBlock *BB) const {
  147. addIncomingPHIValuesForInto(BB, OuterResumeDest);
  148. }
  149. void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
  150. BasicBlock::iterator I = dest->begin();
  151. for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
  152. PHINode *phi = cast<PHINode>(I);
  153. phi->addIncoming(UnwindDestPHIValues[i], src);
  154. }
  155. }
  156. };
  157. } // end anonymous namespace
  158. /// Get or create a target for the branch from ResumeInsts.
  159. BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
  160. if (InnerResumeDest) return InnerResumeDest;
  161. // Split the landing pad.
  162. BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
  163. InnerResumeDest =
  164. OuterResumeDest->splitBasicBlock(SplitPoint,
  165. OuterResumeDest->getName() + ".body");
  166. // The number of incoming edges we expect to the inner landing pad.
  167. const unsigned PHICapacity = 2;
  168. // Create corresponding new PHIs for all the PHIs in the outer landing pad.
  169. Instruction *InsertPoint = &InnerResumeDest->front();
  170. BasicBlock::iterator I = OuterResumeDest->begin();
  171. for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
  172. PHINode *OuterPHI = cast<PHINode>(I);
  173. PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
  174. OuterPHI->getName() + ".lpad-body",
  175. InsertPoint);
  176. OuterPHI->replaceAllUsesWith(InnerPHI);
  177. InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
  178. }
  179. // Create a PHI for the exception values.
  180. InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
  181. "eh.lpad-body", InsertPoint);
  182. CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
  183. InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
  184. // All done.
  185. return InnerResumeDest;
  186. }
  187. /// Forward the 'resume' instruction to the caller's landing pad block.
  188. /// When the landing pad block has only one predecessor, this is a simple
  189. /// branch. When there is more than one predecessor, we need to split the
  190. /// landing pad block after the landingpad instruction and jump to there.
  191. void LandingPadInliningInfo::forwardResume(
  192. ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
  193. BasicBlock *Dest = getInnerResumeDest();
  194. BasicBlock *Src = RI->getParent();
  195. BranchInst::Create(Dest, Src);
  196. // Update the PHIs in the destination. They were inserted in an order which
  197. // makes this work.
  198. addIncomingPHIValuesForInto(Src, Dest);
  199. InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
  200. RI->eraseFromParent();
  201. }
  202. /// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
  203. static Value *getParentPad(Value *EHPad) {
  204. if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
  205. return FPI->getParentPad();
  206. return cast<CatchSwitchInst>(EHPad)->getParentPad();
  207. }
  208. using UnwindDestMemoTy = DenseMap<Instruction *, Value *>;
  209. /// Helper for getUnwindDestToken that does the descendant-ward part of
  210. /// the search.
  211. static Value *getUnwindDestTokenHelper(Instruction *EHPad,
  212. UnwindDestMemoTy &MemoMap) {
  213. SmallVector<Instruction *, 8> Worklist(1, EHPad);
  214. while (!Worklist.empty()) {
  215. Instruction *CurrentPad = Worklist.pop_back_val();
  216. // We only put pads on the worklist that aren't in the MemoMap. When
  217. // we find an unwind dest for a pad we may update its ancestors, but
  218. // the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
  219. // so they should never get updated while queued on the worklist.
  220. assert(!MemoMap.count(CurrentPad));
  221. Value *UnwindDestToken = nullptr;
  222. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) {
  223. if (CatchSwitch->hasUnwindDest()) {
  224. UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI();
  225. } else {
  226. // Catchswitch doesn't have a 'nounwind' variant, and one might be
  227. // annotated as "unwinds to caller" when really it's nounwind (see
  228. // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
  229. // parent's unwind dest from this. We can check its catchpads'
  230. // descendants, since they might include a cleanuppad with an
  231. // "unwinds to caller" cleanupret, which can be trusted.
  232. for (auto HI = CatchSwitch->handler_begin(),
  233. HE = CatchSwitch->handler_end();
  234. HI != HE && !UnwindDestToken; ++HI) {
  235. BasicBlock *HandlerBlock = *HI;
  236. auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI());
  237. for (User *Child : CatchPad->users()) {
  238. // Intentionally ignore invokes here -- since the catchswitch is
  239. // marked "unwind to caller", it would be a verifier error if it
  240. // contained an invoke which unwinds out of it, so any invoke we'd
  241. // encounter must unwind to some child of the catch.
  242. if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child))
  243. continue;
  244. Instruction *ChildPad = cast<Instruction>(Child);
  245. auto Memo = MemoMap.find(ChildPad);
  246. if (Memo == MemoMap.end()) {
  247. // Haven't figured out this child pad yet; queue it.
  248. Worklist.push_back(ChildPad);
  249. continue;
  250. }
  251. // We've already checked this child, but might have found that
  252. // it offers no proof either way.
  253. Value *ChildUnwindDestToken = Memo->second;
  254. if (!ChildUnwindDestToken)
  255. continue;
  256. // We already know the child's unwind dest, which can either
  257. // be ConstantTokenNone to indicate unwind to caller, or can
  258. // be another child of the catchpad. Only the former indicates
  259. // the unwind dest of the catchswitch.
  260. if (isa<ConstantTokenNone>(ChildUnwindDestToken)) {
  261. UnwindDestToken = ChildUnwindDestToken;
  262. break;
  263. }
  264. assert(getParentPad(ChildUnwindDestToken) == CatchPad);
  265. }
  266. }
  267. }
  268. } else {
  269. auto *CleanupPad = cast<CleanupPadInst>(CurrentPad);
  270. for (User *U : CleanupPad->users()) {
  271. if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
  272. if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
  273. UnwindDestToken = RetUnwindDest->getFirstNonPHI();
  274. else
  275. UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext());
  276. break;
  277. }
  278. Value *ChildUnwindDestToken;
  279. if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
  280. ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI();
  281. } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
  282. Instruction *ChildPad = cast<Instruction>(U);
  283. auto Memo = MemoMap.find(ChildPad);
  284. if (Memo == MemoMap.end()) {
  285. // Haven't resolved this child yet; queue it and keep searching.
  286. Worklist.push_back(ChildPad);
  287. continue;
  288. }
  289. // We've checked this child, but still need to ignore it if it
  290. // had no proof either way.
  291. ChildUnwindDestToken = Memo->second;
  292. if (!ChildUnwindDestToken)
  293. continue;
  294. } else {
  295. // Not a relevant user of the cleanuppad
  296. continue;
  297. }
  298. // In a well-formed program, the child/invoke must either unwind to
  299. // an(other) child of the cleanup, or exit the cleanup. In the
  300. // first case, continue searching.
  301. if (isa<Instruction>(ChildUnwindDestToken) &&
  302. getParentPad(ChildUnwindDestToken) == CleanupPad)
  303. continue;
  304. UnwindDestToken = ChildUnwindDestToken;
  305. break;
  306. }
  307. }
  308. // If we haven't found an unwind dest for CurrentPad, we may have queued its
  309. // children, so move on to the next in the worklist.
  310. if (!UnwindDestToken)
  311. continue;
  312. // Now we know that CurrentPad unwinds to UnwindDestToken. It also exits
  313. // any ancestors of CurrentPad up to but not including UnwindDestToken's
  314. // parent pad. Record this in the memo map, and check to see if the
  315. // original EHPad being queried is one of the ones exited.
  316. Value *UnwindParent;
  317. if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken))
  318. UnwindParent = getParentPad(UnwindPad);
  319. else
  320. UnwindParent = nullptr;
  321. bool ExitedOriginalPad = false;
  322. for (Instruction *ExitedPad = CurrentPad;
  323. ExitedPad && ExitedPad != UnwindParent;
  324. ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) {
  325. // Skip over catchpads since they just follow their catchswitches.
  326. if (isa<CatchPadInst>(ExitedPad))
  327. continue;
  328. MemoMap[ExitedPad] = UnwindDestToken;
  329. ExitedOriginalPad |= (ExitedPad == EHPad);
  330. }
  331. if (ExitedOriginalPad)
  332. return UnwindDestToken;
  333. // Continue the search.
  334. }
  335. // No definitive information is contained within this funclet.
  336. return nullptr;
  337. }
  338. /// Given an EH pad, find where it unwinds. If it unwinds to an EH pad,
  339. /// return that pad instruction. If it unwinds to caller, return
  340. /// ConstantTokenNone. If it does not have a definitive unwind destination,
  341. /// return nullptr.
  342. ///
  343. /// This routine gets invoked for calls in funclets in inlinees when inlining
  344. /// an invoke. Since many funclets don't have calls inside them, it's queried
  345. /// on-demand rather than building a map of pads to unwind dests up front.
  346. /// Determining a funclet's unwind dest may require recursively searching its
  347. /// descendants, and also ancestors and cousins if the descendants don't provide
  348. /// an answer. Since most funclets will have their unwind dest immediately
  349. /// available as the unwind dest of a catchswitch or cleanupret, this routine
  350. /// searches top-down from the given pad and then up. To avoid worst-case
  351. /// quadratic run-time given that approach, it uses a memo map to avoid
  352. /// re-processing funclet trees. The callers that rewrite the IR as they go
  353. /// take advantage of this, for correctness, by checking/forcing rewritten
  354. /// pads' entries to match the original callee view.
  355. static Value *getUnwindDestToken(Instruction *EHPad,
  356. UnwindDestMemoTy &MemoMap) {
  357. // Catchpads unwind to the same place as their catchswitch;
  358. // redirct any queries on catchpads so the code below can
  359. // deal with just catchswitches and cleanuppads.
  360. if (auto *CPI = dyn_cast<CatchPadInst>(EHPad))
  361. EHPad = CPI->getCatchSwitch();
  362. // Check if we've already determined the unwind dest for this pad.
  363. auto Memo = MemoMap.find(EHPad);
  364. if (Memo != MemoMap.end())
  365. return Memo->second;
  366. // Search EHPad and, if necessary, its descendants.
  367. Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
  368. assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
  369. if (UnwindDestToken)
  370. return UnwindDestToken;
  371. // No information is available for this EHPad from itself or any of its
  372. // descendants. An unwind all the way out to a pad in the caller would
  373. // need also to agree with the unwind dest of the parent funclet, so
  374. // search up the chain to try to find a funclet with information. Put
  375. // null entries in the memo map to avoid re-processing as we go up.
  376. MemoMap[EHPad] = nullptr;
  377. #ifndef NDEBUG
  378. SmallPtrSet<Instruction *, 4> TempMemos;
  379. TempMemos.insert(EHPad);
  380. #endif
  381. Instruction *LastUselessPad = EHPad;
  382. Value *AncestorToken;
  383. for (AncestorToken = getParentPad(EHPad);
  384. auto *AncestorPad = dyn_cast<Instruction>(AncestorToken);
  385. AncestorToken = getParentPad(AncestorToken)) {
  386. // Skip over catchpads since they just follow their catchswitches.
  387. if (isa<CatchPadInst>(AncestorPad))
  388. continue;
  389. // If the MemoMap had an entry mapping AncestorPad to nullptr, since we
  390. // haven't yet called getUnwindDestTokenHelper for AncestorPad in this
  391. // call to getUnwindDestToken, that would mean that AncestorPad had no
  392. // information in itself, its descendants, or its ancestors. If that
  393. // were the case, then we should also have recorded the lack of information
  394. // for the descendant that we're coming from. So assert that we don't
  395. // find a null entry in the MemoMap for AncestorPad.
  396. assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
  397. auto AncestorMemo = MemoMap.find(AncestorPad);
  398. if (AncestorMemo == MemoMap.end()) {
  399. UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap);
  400. } else {
  401. UnwindDestToken = AncestorMemo->second;
  402. }
  403. if (UnwindDestToken)
  404. break;
  405. LastUselessPad = AncestorPad;
  406. MemoMap[LastUselessPad] = nullptr;
  407. #ifndef NDEBUG
  408. TempMemos.insert(LastUselessPad);
  409. #endif
  410. }
  411. // We know that getUnwindDestTokenHelper was called on LastUselessPad and
  412. // returned nullptr (and likewise for EHPad and any of its ancestors up to
  413. // LastUselessPad), so LastUselessPad has no information from below. Since
  414. // getUnwindDestTokenHelper must investigate all downward paths through
  415. // no-information nodes to prove that a node has no information like this,
  416. // and since any time it finds information it records it in the MemoMap for
  417. // not just the immediately-containing funclet but also any ancestors also
  418. // exited, it must be the case that, walking downward from LastUselessPad,
  419. // visiting just those nodes which have not been mapped to an unwind dest
  420. // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
  421. // they are just used to keep getUnwindDestTokenHelper from repeating work),
  422. // any node visited must have been exhaustively searched with no information
  423. // for it found.
  424. SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
  425. while (!Worklist.empty()) {
  426. Instruction *UselessPad = Worklist.pop_back_val();
  427. auto Memo = MemoMap.find(UselessPad);
  428. if (Memo != MemoMap.end() && Memo->second) {
  429. // Here the name 'UselessPad' is a bit of a misnomer, because we've found
  430. // that it is a funclet that does have information about unwinding to
  431. // a particular destination; its parent was a useless pad.
  432. // Since its parent has no information, the unwind edge must not escape
  433. // the parent, and must target a sibling of this pad. This local unwind
  434. // gives us no information about EHPad. Leave it and the subtree rooted
  435. // at it alone.
  436. assert(getParentPad(Memo->second) == getParentPad(UselessPad));
  437. continue;
  438. }
  439. // We know we don't have information for UselesPad. If it has an entry in
  440. // the MemoMap (mapping it to nullptr), it must be one of the TempMemos
  441. // added on this invocation of getUnwindDestToken; if a previous invocation
  442. // recorded nullptr, it would have had to prove that the ancestors of
  443. // UselessPad, which include LastUselessPad, had no information, and that
  444. // in turn would have required proving that the descendants of
  445. // LastUselesPad, which include EHPad, have no information about
  446. // LastUselessPad, which would imply that EHPad was mapped to nullptr in
  447. // the MemoMap on that invocation, which isn't the case if we got here.
  448. assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
  449. // Assert as we enumerate users that 'UselessPad' doesn't have any unwind
  450. // information that we'd be contradicting by making a map entry for it
  451. // (which is something that getUnwindDestTokenHelper must have proved for
  452. // us to get here). Just assert on is direct users here; the checks in
  453. // this downward walk at its descendants will verify that they don't have
  454. // any unwind edges that exit 'UselessPad' either (i.e. they either have no
  455. // unwind edges or unwind to a sibling).
  456. MemoMap[UselessPad] = UnwindDestToken;
  457. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) {
  458. assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
  459. for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
  460. auto *CatchPad = HandlerBlock->getFirstNonPHI();
  461. for (User *U : CatchPad->users()) {
  462. assert(
  463. (!isa<InvokeInst>(U) ||
  464. (getParentPad(
  465. cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
  466. CatchPad)) &&
  467. "Expected useless pad");
  468. if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
  469. Worklist.push_back(cast<Instruction>(U));
  470. }
  471. }
  472. } else {
  473. assert(isa<CleanupPadInst>(UselessPad));
  474. for (User *U : UselessPad->users()) {
  475. assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
  476. assert((!isa<InvokeInst>(U) ||
  477. (getParentPad(
  478. cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
  479. UselessPad)) &&
  480. "Expected useless pad");
  481. if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
  482. Worklist.push_back(cast<Instruction>(U));
  483. }
  484. }
  485. }
  486. return UnwindDestToken;
  487. }
  488. /// When we inline a basic block into an invoke,
  489. /// we have to turn all of the calls that can throw into invokes.
  490. /// This function analyze BB to see if there are any calls, and if so,
  491. /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
  492. /// nodes in that block with the values specified in InvokeDestPHIValues.
  493. static BasicBlock *HandleCallsInBlockInlinedThroughInvoke(
  494. BasicBlock *BB, BasicBlock *UnwindEdge,
  495. UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
  496. for (Instruction &I : llvm::make_early_inc_range(*BB)) {
  497. // We only need to check for function calls: inlined invoke
  498. // instructions require no special handling.
  499. CallInst *CI = dyn_cast<CallInst>(&I);
  500. if (!CI || CI->doesNotThrow())
  501. continue;
  502. // We do not need to (and in fact, cannot) convert possibly throwing calls
  503. // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
  504. // invokes. The caller's "segment" of the deoptimization continuation
  505. // attached to the newly inlined @llvm.experimental_deoptimize
  506. // (resp. @llvm.experimental.guard) call should contain the exception
  507. // handling logic, if any.
  508. if (auto *F = CI->getCalledFunction())
  509. if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
  510. F->getIntrinsicID() == Intrinsic::experimental_guard)
  511. continue;
  512. if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
  513. // This call is nested inside a funclet. If that funclet has an unwind
  514. // destination within the inlinee, then unwinding out of this call would
  515. // be UB. Rewriting this call to an invoke which targets the inlined
  516. // invoke's unwind dest would give the call's parent funclet multiple
  517. // unwind destinations, which is something that subsequent EH table
  518. // generation can't handle and that the veirifer rejects. So when we
  519. // see such a call, leave it as a call.
  520. auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]);
  521. Value *UnwindDestToken =
  522. getUnwindDestToken(FuncletPad, *FuncletUnwindMap);
  523. if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
  524. continue;
  525. #ifndef NDEBUG
  526. Instruction *MemoKey;
  527. if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
  528. MemoKey = CatchPad->getCatchSwitch();
  529. else
  530. MemoKey = FuncletPad;
  531. assert(FuncletUnwindMap->count(MemoKey) &&
  532. (*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
  533. "must get memoized to avoid confusing later searches");
  534. #endif // NDEBUG
  535. }
  536. changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
  537. return BB;
  538. }
  539. return nullptr;
  540. }
  541. /// If we inlined an invoke site, we need to convert calls
  542. /// in the body of the inlined function into invokes.
  543. ///
  544. /// II is the invoke instruction being inlined. FirstNewBlock is the first
  545. /// block of the inlined code (the last block is the end of the function),
  546. /// and InlineCodeInfo is information about the code that got inlined.
  547. static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
  548. ClonedCodeInfo &InlinedCodeInfo) {
  549. BasicBlock *InvokeDest = II->getUnwindDest();
  550. Function *Caller = FirstNewBlock->getParent();
  551. // The inlined code is currently at the end of the function, scan from the
  552. // start of the inlined code to its end, checking for stuff we need to
  553. // rewrite.
  554. LandingPadInliningInfo Invoke(II);
  555. // Get all of the inlined landing pad instructions.
  556. SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
  557. for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
  558. I != E; ++I)
  559. if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
  560. InlinedLPads.insert(II->getLandingPadInst());
  561. // Append the clauses from the outer landing pad instruction into the inlined
  562. // landing pad instructions.
  563. LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
  564. for (LandingPadInst *InlinedLPad : InlinedLPads) {
  565. unsigned OuterNum = OuterLPad->getNumClauses();
  566. InlinedLPad->reserveClauses(OuterNum);
  567. for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
  568. InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
  569. if (OuterLPad->isCleanup())
  570. InlinedLPad->setCleanup(true);
  571. }
  572. for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
  573. BB != E; ++BB) {
  574. if (InlinedCodeInfo.ContainsCalls)
  575. if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
  576. &*BB, Invoke.getOuterResumeDest()))
  577. // Update any PHI nodes in the exceptional block to indicate that there
  578. // is now a new entry in them.
  579. Invoke.addIncomingPHIValuesFor(NewBB);
  580. // Forward any resumes that are remaining here.
  581. if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
  582. Invoke.forwardResume(RI, InlinedLPads);
  583. }
  584. // Now that everything is happy, we have one final detail. The PHI nodes in
  585. // the exception destination block still have entries due to the original
  586. // invoke instruction. Eliminate these entries (which might even delete the
  587. // PHI node) now.
  588. InvokeDest->removePredecessor(II->getParent());
  589. }
  590. /// If we inlined an invoke site, we need to convert calls
  591. /// in the body of the inlined function into invokes.
  592. ///
  593. /// II is the invoke instruction being inlined. FirstNewBlock is the first
  594. /// block of the inlined code (the last block is the end of the function),
  595. /// and InlineCodeInfo is information about the code that got inlined.
  596. static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
  597. ClonedCodeInfo &InlinedCodeInfo) {
  598. BasicBlock *UnwindDest = II->getUnwindDest();
  599. Function *Caller = FirstNewBlock->getParent();
  600. assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
  601. // If there are PHI nodes in the unwind destination block, we need to keep
  602. // track of which values came into them from the invoke before removing the
  603. // edge from this block.
  604. SmallVector<Value *, 8> UnwindDestPHIValues;
  605. BasicBlock *InvokeBB = II->getParent();
  606. for (PHINode &PHI : UnwindDest->phis()) {
  607. // Save the value to use for this edge.
  608. UnwindDestPHIValues.push_back(PHI.getIncomingValueForBlock(InvokeBB));
  609. }
  610. // Add incoming-PHI values to the unwind destination block for the given basic
  611. // block, using the values for the original invoke's source block.
  612. auto UpdatePHINodes = [&](BasicBlock *Src) {
  613. BasicBlock::iterator I = UnwindDest->begin();
  614. for (Value *V : UnwindDestPHIValues) {
  615. PHINode *PHI = cast<PHINode>(I);
  616. PHI->addIncoming(V, Src);
  617. ++I;
  618. }
  619. };
  620. // This connects all the instructions which 'unwind to caller' to the invoke
  621. // destination.
  622. UnwindDestMemoTy FuncletUnwindMap;
  623. for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
  624. BB != E; ++BB) {
  625. if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
  626. if (CRI->unwindsToCaller()) {
  627. auto *CleanupPad = CRI->getCleanupPad();
  628. CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI);
  629. CRI->eraseFromParent();
  630. UpdatePHINodes(&*BB);
  631. // Finding a cleanupret with an unwind destination would confuse
  632. // subsequent calls to getUnwindDestToken, so map the cleanuppad
  633. // to short-circuit any such calls and recognize this as an "unwind
  634. // to caller" cleanup.
  635. assert(!FuncletUnwindMap.count(CleanupPad) ||
  636. isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
  637. FuncletUnwindMap[CleanupPad] =
  638. ConstantTokenNone::get(Caller->getContext());
  639. }
  640. }
  641. Instruction *I = BB->getFirstNonPHI();
  642. if (!I->isEHPad())
  643. continue;
  644. Instruction *Replacement = nullptr;
  645. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
  646. if (CatchSwitch->unwindsToCaller()) {
  647. Value *UnwindDestToken;
  648. if (auto *ParentPad =
  649. dyn_cast<Instruction>(CatchSwitch->getParentPad())) {
  650. // This catchswitch is nested inside another funclet. If that
  651. // funclet has an unwind destination within the inlinee, then
  652. // unwinding out of this catchswitch would be UB. Rewriting this
  653. // catchswitch to unwind to the inlined invoke's unwind dest would
  654. // give the parent funclet multiple unwind destinations, which is
  655. // something that subsequent EH table generation can't handle and
  656. // that the veirifer rejects. So when we see such a call, leave it
  657. // as "unwind to caller".
  658. UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap);
  659. if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
  660. continue;
  661. } else {
  662. // This catchswitch has no parent to inherit constraints from, and
  663. // none of its descendants can have an unwind edge that exits it and
  664. // targets another funclet in the inlinee. It may or may not have a
  665. // descendant that definitively has an unwind to caller. In either
  666. // case, we'll have to assume that any unwinds out of it may need to
  667. // be routed to the caller, so treat it as though it has a definitive
  668. // unwind to caller.
  669. UnwindDestToken = ConstantTokenNone::get(Caller->getContext());
  670. }
  671. auto *NewCatchSwitch = CatchSwitchInst::Create(
  672. CatchSwitch->getParentPad(), UnwindDest,
  673. CatchSwitch->getNumHandlers(), CatchSwitch->getName(),
  674. CatchSwitch);
  675. for (BasicBlock *PadBB : CatchSwitch->handlers())
  676. NewCatchSwitch->addHandler(PadBB);
  677. // Propagate info for the old catchswitch over to the new one in
  678. // the unwind map. This also serves to short-circuit any subsequent
  679. // checks for the unwind dest of this catchswitch, which would get
  680. // confused if they found the outer handler in the callee.
  681. FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
  682. Replacement = NewCatchSwitch;
  683. }
  684. } else if (!isa<FuncletPadInst>(I)) {
  685. llvm_unreachable("unexpected EHPad!");
  686. }
  687. if (Replacement) {
  688. Replacement->takeName(I);
  689. I->replaceAllUsesWith(Replacement);
  690. I->eraseFromParent();
  691. UpdatePHINodes(&*BB);
  692. }
  693. }
  694. if (InlinedCodeInfo.ContainsCalls)
  695. for (Function::iterator BB = FirstNewBlock->getIterator(),
  696. E = Caller->end();
  697. BB != E; ++BB)
  698. if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
  699. &*BB, UnwindDest, &FuncletUnwindMap))
  700. // Update any PHI nodes in the exceptional block to indicate that there
  701. // is now a new entry in them.
  702. UpdatePHINodes(NewBB);
  703. // Now that everything is happy, we have one final detail. The PHI nodes in
  704. // the exception destination block still have entries due to the original
  705. // invoke instruction. Eliminate these entries (which might even delete the
  706. // PHI node) now.
  707. UnwindDest->removePredecessor(InvokeBB);
  708. }
  709. static bool haveCommonPrefix(MDNode *MIBStackContext,
  710. MDNode *CallsiteStackContext) {
  711. assert(MIBStackContext->getNumOperands() > 0 &&
  712. CallsiteStackContext->getNumOperands() > 0);
  713. // Because of the context trimming performed during matching, the callsite
  714. // context could have more stack ids than the MIB. We match up to the end of
  715. // the shortest stack context.
  716. for (auto MIBStackIter = MIBStackContext->op_begin(),
  717. CallsiteStackIter = CallsiteStackContext->op_begin();
  718. MIBStackIter != MIBStackContext->op_end() &&
  719. CallsiteStackIter != CallsiteStackContext->op_end();
  720. MIBStackIter++, CallsiteStackIter++) {
  721. auto *Val1 = mdconst::dyn_extract<ConstantInt>(*MIBStackIter);
  722. auto *Val2 = mdconst::dyn_extract<ConstantInt>(*CallsiteStackIter);
  723. assert(Val1 && Val2);
  724. if (Val1->getZExtValue() != Val2->getZExtValue())
  725. return false;
  726. }
  727. return true;
  728. }
  729. static void removeMemProfMetadata(CallBase *Call) {
  730. Call->setMetadata(LLVMContext::MD_memprof, nullptr);
  731. }
  732. static void removeCallsiteMetadata(CallBase *Call) {
  733. Call->setMetadata(LLVMContext::MD_callsite, nullptr);
  734. }
  735. static void updateMemprofMetadata(CallBase *CI,
  736. const std::vector<Metadata *> &MIBList) {
  737. assert(!MIBList.empty());
  738. // Remove existing memprof, which will either be replaced or may not be needed
  739. // if we are able to use a single allocation type function attribute.
  740. removeMemProfMetadata(CI);
  741. CallStackTrie CallStack;
  742. for (Metadata *MIB : MIBList)
  743. CallStack.addCallStack(cast<MDNode>(MIB));
  744. bool MemprofMDAttached = CallStack.buildAndAttachMIBMetadata(CI);
  745. assert(MemprofMDAttached == CI->hasMetadata(LLVMContext::MD_memprof));
  746. if (!MemprofMDAttached)
  747. // If we used a function attribute remove the callsite metadata as well.
  748. removeCallsiteMetadata(CI);
  749. }
  750. // Update the metadata on the inlined copy ClonedCall of a call OrigCall in the
  751. // inlined callee body, based on the callsite metadata InlinedCallsiteMD from
  752. // the call that was inlined.
  753. static void propagateMemProfHelper(const CallBase *OrigCall,
  754. CallBase *ClonedCall,
  755. MDNode *InlinedCallsiteMD) {
  756. MDNode *OrigCallsiteMD = ClonedCall->getMetadata(LLVMContext::MD_callsite);
  757. MDNode *ClonedCallsiteMD = nullptr;
  758. // Check if the call originally had callsite metadata, and update it for the
  759. // new call in the inlined body.
  760. if (OrigCallsiteMD) {
  761. // The cloned call's context is now the concatenation of the original call's
  762. // callsite metadata and the callsite metadata on the call where it was
  763. // inlined.
  764. ClonedCallsiteMD = MDNode::concatenate(OrigCallsiteMD, InlinedCallsiteMD);
  765. ClonedCall->setMetadata(LLVMContext::MD_callsite, ClonedCallsiteMD);
  766. }
  767. // Update any memprof metadata on the cloned call.
  768. MDNode *OrigMemProfMD = ClonedCall->getMetadata(LLVMContext::MD_memprof);
  769. if (!OrigMemProfMD)
  770. return;
  771. // We currently expect that allocations with memprof metadata also have
  772. // callsite metadata for the allocation's part of the context.
  773. assert(OrigCallsiteMD);
  774. // New call's MIB list.
  775. std::vector<Metadata *> NewMIBList;
  776. // For each MIB metadata, check if its call stack context starts with the
  777. // new clone's callsite metadata. If so, that MIB goes onto the cloned call in
  778. // the inlined body. If not, it stays on the out-of-line original call.
  779. for (auto &MIBOp : OrigMemProfMD->operands()) {
  780. MDNode *MIB = dyn_cast<MDNode>(MIBOp);
  781. // Stack is first operand of MIB.
  782. MDNode *StackMD = getMIBStackNode(MIB);
  783. assert(StackMD);
  784. // See if the new cloned callsite context matches this profiled context.
  785. if (haveCommonPrefix(StackMD, ClonedCallsiteMD))
  786. // Add it to the cloned call's MIB list.
  787. NewMIBList.push_back(MIB);
  788. }
  789. if (NewMIBList.empty()) {
  790. removeMemProfMetadata(ClonedCall);
  791. removeCallsiteMetadata(ClonedCall);
  792. return;
  793. }
  794. if (NewMIBList.size() < OrigMemProfMD->getNumOperands())
  795. updateMemprofMetadata(ClonedCall, NewMIBList);
  796. }
  797. // Update memprof related metadata (!memprof and !callsite) based on the
  798. // inlining of Callee into the callsite at CB. The updates include merging the
  799. // inlined callee's callsite metadata with that of the inlined call,
  800. // and moving the subset of any memprof contexts to the inlined callee
  801. // allocations if they match the new inlined call stack.
  802. // FIXME: Replace memprof metadata with function attribute if all MIB end up
  803. // having the same behavior. Do other context trimming/merging optimizations
  804. // too.
  805. static void
  806. propagateMemProfMetadata(Function *Callee, CallBase &CB,
  807. bool ContainsMemProfMetadata,
  808. const ValueMap<const Value *, WeakTrackingVH> &VMap) {
  809. MDNode *CallsiteMD = CB.getMetadata(LLVMContext::MD_callsite);
  810. // Only need to update if the inlined callsite had callsite metadata, or if
  811. // there was any memprof metadata inlined.
  812. if (!CallsiteMD && !ContainsMemProfMetadata)
  813. return;
  814. // Propagate metadata onto the cloned calls in the inlined callee.
  815. for (const auto &Entry : VMap) {
  816. // See if this is a call that has been inlined and remapped, and not
  817. // simplified away in the process.
  818. auto *OrigCall = dyn_cast_or_null<CallBase>(Entry.first);
  819. auto *ClonedCall = dyn_cast_or_null<CallBase>(Entry.second);
  820. if (!OrigCall || !ClonedCall)
  821. continue;
  822. // If the inlined callsite did not have any callsite metadata, then it isn't
  823. // involved in any profiled call contexts, and we can remove any memprof
  824. // metadata on the cloned call.
  825. if (!CallsiteMD) {
  826. removeMemProfMetadata(ClonedCall);
  827. removeCallsiteMetadata(ClonedCall);
  828. continue;
  829. }
  830. propagateMemProfHelper(OrigCall, ClonedCall, CallsiteMD);
  831. }
  832. }
  833. /// When inlining a call site that has !llvm.mem.parallel_loop_access,
  834. /// !llvm.access.group, !alias.scope or !noalias metadata, that metadata should
  835. /// be propagated to all memory-accessing cloned instructions.
  836. static void PropagateCallSiteMetadata(CallBase &CB, Function::iterator FStart,
  837. Function::iterator FEnd) {
  838. MDNode *MemParallelLoopAccess =
  839. CB.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
  840. MDNode *AccessGroup = CB.getMetadata(LLVMContext::MD_access_group);
  841. MDNode *AliasScope = CB.getMetadata(LLVMContext::MD_alias_scope);
  842. MDNode *NoAlias = CB.getMetadata(LLVMContext::MD_noalias);
  843. if (!MemParallelLoopAccess && !AccessGroup && !AliasScope && !NoAlias)
  844. return;
  845. for (BasicBlock &BB : make_range(FStart, FEnd)) {
  846. for (Instruction &I : BB) {
  847. // This metadata is only relevant for instructions that access memory.
  848. if (!I.mayReadOrWriteMemory())
  849. continue;
  850. if (MemParallelLoopAccess) {
  851. // TODO: This probably should not overwrite MemParalleLoopAccess.
  852. MemParallelLoopAccess = MDNode::concatenate(
  853. I.getMetadata(LLVMContext::MD_mem_parallel_loop_access),
  854. MemParallelLoopAccess);
  855. I.setMetadata(LLVMContext::MD_mem_parallel_loop_access,
  856. MemParallelLoopAccess);
  857. }
  858. if (AccessGroup)
  859. I.setMetadata(LLVMContext::MD_access_group, uniteAccessGroups(
  860. I.getMetadata(LLVMContext::MD_access_group), AccessGroup));
  861. if (AliasScope)
  862. I.setMetadata(LLVMContext::MD_alias_scope, MDNode::concatenate(
  863. I.getMetadata(LLVMContext::MD_alias_scope), AliasScope));
  864. if (NoAlias)
  865. I.setMetadata(LLVMContext::MD_noalias, MDNode::concatenate(
  866. I.getMetadata(LLVMContext::MD_noalias), NoAlias));
  867. }
  868. }
  869. }
  870. /// Bundle operands of the inlined function must be added to inlined call sites.
  871. static void PropagateOperandBundles(Function::iterator InlinedBB,
  872. Instruction *CallSiteEHPad) {
  873. for (Instruction &II : llvm::make_early_inc_range(*InlinedBB)) {
  874. CallBase *I = dyn_cast<CallBase>(&II);
  875. if (!I)
  876. continue;
  877. // Skip call sites which already have a "funclet" bundle.
  878. if (I->getOperandBundle(LLVMContext::OB_funclet))
  879. continue;
  880. // Skip call sites which are nounwind intrinsics (as long as they don't
  881. // lower into regular function calls in the course of IR transformations).
  882. auto *CalledFn =
  883. dyn_cast<Function>(I->getCalledOperand()->stripPointerCasts());
  884. if (CalledFn && CalledFn->isIntrinsic() && I->doesNotThrow() &&
  885. !IntrinsicInst::mayLowerToFunctionCall(CalledFn->getIntrinsicID()))
  886. continue;
  887. SmallVector<OperandBundleDef, 1> OpBundles;
  888. I->getOperandBundlesAsDefs(OpBundles);
  889. OpBundles.emplace_back("funclet", CallSiteEHPad);
  890. Instruction *NewInst = CallBase::Create(I, OpBundles, I);
  891. NewInst->takeName(I);
  892. I->replaceAllUsesWith(NewInst);
  893. I->eraseFromParent();
  894. }
  895. }
  896. namespace {
  897. /// Utility for cloning !noalias and !alias.scope metadata. When a code region
  898. /// using scoped alias metadata is inlined, the aliasing relationships may not
  899. /// hold between the two version. It is necessary to create a deep clone of the
  900. /// metadata, putting the two versions in separate scope domains.
  901. class ScopedAliasMetadataDeepCloner {
  902. using MetadataMap = DenseMap<const MDNode *, TrackingMDNodeRef>;
  903. SetVector<const MDNode *> MD;
  904. MetadataMap MDMap;
  905. void addRecursiveMetadataUses();
  906. public:
  907. ScopedAliasMetadataDeepCloner(const Function *F);
  908. /// Create a new clone of the scoped alias metadata, which will be used by
  909. /// subsequent remap() calls.
  910. void clone();
  911. /// Remap instructions in the given range from the original to the cloned
  912. /// metadata.
  913. void remap(Function::iterator FStart, Function::iterator FEnd);
  914. };
  915. } // namespace
  916. ScopedAliasMetadataDeepCloner::ScopedAliasMetadataDeepCloner(
  917. const Function *F) {
  918. for (const BasicBlock &BB : *F) {
  919. for (const Instruction &I : BB) {
  920. if (const MDNode *M = I.getMetadata(LLVMContext::MD_alias_scope))
  921. MD.insert(M);
  922. if (const MDNode *M = I.getMetadata(LLVMContext::MD_noalias))
  923. MD.insert(M);
  924. // We also need to clone the metadata in noalias intrinsics.
  925. if (const auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
  926. MD.insert(Decl->getScopeList());
  927. }
  928. }
  929. addRecursiveMetadataUses();
  930. }
  931. void ScopedAliasMetadataDeepCloner::addRecursiveMetadataUses() {
  932. SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
  933. while (!Queue.empty()) {
  934. const MDNode *M = cast<MDNode>(Queue.pop_back_val());
  935. for (const Metadata *Op : M->operands())
  936. if (const MDNode *OpMD = dyn_cast<MDNode>(Op))
  937. if (MD.insert(OpMD))
  938. Queue.push_back(OpMD);
  939. }
  940. }
  941. void ScopedAliasMetadataDeepCloner::clone() {
  942. assert(MDMap.empty() && "clone() already called ?");
  943. SmallVector<TempMDTuple, 16> DummyNodes;
  944. for (const MDNode *I : MD) {
  945. DummyNodes.push_back(MDTuple::getTemporary(I->getContext(), std::nullopt));
  946. MDMap[I].reset(DummyNodes.back().get());
  947. }
  948. // Create new metadata nodes to replace the dummy nodes, replacing old
  949. // metadata references with either a dummy node or an already-created new
  950. // node.
  951. SmallVector<Metadata *, 4> NewOps;
  952. for (const MDNode *I : MD) {
  953. for (const Metadata *Op : I->operands()) {
  954. if (const MDNode *M = dyn_cast<MDNode>(Op))
  955. NewOps.push_back(MDMap[M]);
  956. else
  957. NewOps.push_back(const_cast<Metadata *>(Op));
  958. }
  959. MDNode *NewM = MDNode::get(I->getContext(), NewOps);
  960. MDTuple *TempM = cast<MDTuple>(MDMap[I]);
  961. assert(TempM->isTemporary() && "Expected temporary node");
  962. TempM->replaceAllUsesWith(NewM);
  963. NewOps.clear();
  964. }
  965. }
  966. void ScopedAliasMetadataDeepCloner::remap(Function::iterator FStart,
  967. Function::iterator FEnd) {
  968. if (MDMap.empty())
  969. return; // Nothing to do.
  970. for (BasicBlock &BB : make_range(FStart, FEnd)) {
  971. for (Instruction &I : BB) {
  972. // TODO: The null checks for the MDMap.lookup() results should no longer
  973. // be necessary.
  974. if (MDNode *M = I.getMetadata(LLVMContext::MD_alias_scope))
  975. if (MDNode *MNew = MDMap.lookup(M))
  976. I.setMetadata(LLVMContext::MD_alias_scope, MNew);
  977. if (MDNode *M = I.getMetadata(LLVMContext::MD_noalias))
  978. if (MDNode *MNew = MDMap.lookup(M))
  979. I.setMetadata(LLVMContext::MD_noalias, MNew);
  980. if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
  981. if (MDNode *MNew = MDMap.lookup(Decl->getScopeList()))
  982. Decl->setScopeList(MNew);
  983. }
  984. }
  985. }
  986. /// If the inlined function has noalias arguments,
  987. /// then add new alias scopes for each noalias argument, tag the mapped noalias
  988. /// parameters with noalias metadata specifying the new scope, and tag all
  989. /// non-derived loads, stores and memory intrinsics with the new alias scopes.
  990. static void AddAliasScopeMetadata(CallBase &CB, ValueToValueMapTy &VMap,
  991. const DataLayout &DL, AAResults *CalleeAAR,
  992. ClonedCodeInfo &InlinedFunctionInfo) {
  993. if (!EnableNoAliasConversion)
  994. return;
  995. const Function *CalledFunc = CB.getCalledFunction();
  996. SmallVector<const Argument *, 4> NoAliasArgs;
  997. for (const Argument &Arg : CalledFunc->args())
  998. if (CB.paramHasAttr(Arg.getArgNo(), Attribute::NoAlias) && !Arg.use_empty())
  999. NoAliasArgs.push_back(&Arg);
  1000. if (NoAliasArgs.empty())
  1001. return;
  1002. // To do a good job, if a noalias variable is captured, we need to know if
  1003. // the capture point dominates the particular use we're considering.
  1004. DominatorTree DT;
  1005. DT.recalculate(const_cast<Function&>(*CalledFunc));
  1006. // noalias indicates that pointer values based on the argument do not alias
  1007. // pointer values which are not based on it. So we add a new "scope" for each
  1008. // noalias function argument. Accesses using pointers based on that argument
  1009. // become part of that alias scope, accesses using pointers not based on that
  1010. // argument are tagged as noalias with that scope.
  1011. DenseMap<const Argument *, MDNode *> NewScopes;
  1012. MDBuilder MDB(CalledFunc->getContext());
  1013. // Create a new scope domain for this function.
  1014. MDNode *NewDomain =
  1015. MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
  1016. for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
  1017. const Argument *A = NoAliasArgs[i];
  1018. std::string Name = std::string(CalledFunc->getName());
  1019. if (A->hasName()) {
  1020. Name += ": %";
  1021. Name += A->getName();
  1022. } else {
  1023. Name += ": argument ";
  1024. Name += utostr(i);
  1025. }
  1026. // Note: We always create a new anonymous root here. This is true regardless
  1027. // of the linkage of the callee because the aliasing "scope" is not just a
  1028. // property of the callee, but also all control dependencies in the caller.
  1029. MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
  1030. NewScopes.insert(std::make_pair(A, NewScope));
  1031. if (UseNoAliasIntrinsic) {
  1032. // Introduce a llvm.experimental.noalias.scope.decl for the noalias
  1033. // argument.
  1034. MDNode *AScopeList = MDNode::get(CalledFunc->getContext(), NewScope);
  1035. auto *NoAliasDecl =
  1036. IRBuilder<>(&CB).CreateNoAliasScopeDeclaration(AScopeList);
  1037. // Ignore the result for now. The result will be used when the
  1038. // llvm.noalias intrinsic is introduced.
  1039. (void)NoAliasDecl;
  1040. }
  1041. }
  1042. // Iterate over all new instructions in the map; for all memory-access
  1043. // instructions, add the alias scope metadata.
  1044. for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
  1045. VMI != VMIE; ++VMI) {
  1046. if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
  1047. if (!VMI->second)
  1048. continue;
  1049. Instruction *NI = dyn_cast<Instruction>(VMI->second);
  1050. if (!NI || InlinedFunctionInfo.isSimplified(I, NI))
  1051. continue;
  1052. bool IsArgMemOnlyCall = false, IsFuncCall = false;
  1053. SmallVector<const Value *, 2> PtrArgs;
  1054. if (const LoadInst *LI = dyn_cast<LoadInst>(I))
  1055. PtrArgs.push_back(LI->getPointerOperand());
  1056. else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
  1057. PtrArgs.push_back(SI->getPointerOperand());
  1058. else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
  1059. PtrArgs.push_back(VAAI->getPointerOperand());
  1060. else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
  1061. PtrArgs.push_back(CXI->getPointerOperand());
  1062. else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
  1063. PtrArgs.push_back(RMWI->getPointerOperand());
  1064. else if (const auto *Call = dyn_cast<CallBase>(I)) {
  1065. // If we know that the call does not access memory, then we'll still
  1066. // know that about the inlined clone of this call site, and we don't
  1067. // need to add metadata.
  1068. if (Call->doesNotAccessMemory())
  1069. continue;
  1070. IsFuncCall = true;
  1071. if (CalleeAAR) {
  1072. MemoryEffects ME = CalleeAAR->getMemoryEffects(Call);
  1073. // We'll retain this knowledge without additional metadata.
  1074. if (ME.onlyAccessesInaccessibleMem())
  1075. continue;
  1076. if (ME.onlyAccessesArgPointees())
  1077. IsArgMemOnlyCall = true;
  1078. }
  1079. for (Value *Arg : Call->args()) {
  1080. // Only care about pointer arguments. If a noalias argument is
  1081. // accessed through a non-pointer argument, it must be captured
  1082. // first (e.g. via ptrtoint), and we protect against captures below.
  1083. if (!Arg->getType()->isPointerTy())
  1084. continue;
  1085. PtrArgs.push_back(Arg);
  1086. }
  1087. }
  1088. // If we found no pointers, then this instruction is not suitable for
  1089. // pairing with an instruction to receive aliasing metadata.
  1090. // However, if this is a call, this we might just alias with none of the
  1091. // noalias arguments.
  1092. if (PtrArgs.empty() && !IsFuncCall)
  1093. continue;
  1094. // It is possible that there is only one underlying object, but you
  1095. // need to go through several PHIs to see it, and thus could be
  1096. // repeated in the Objects list.
  1097. SmallPtrSet<const Value *, 4> ObjSet;
  1098. SmallVector<Metadata *, 4> Scopes, NoAliases;
  1099. SmallSetVector<const Argument *, 4> NAPtrArgs;
  1100. for (const Value *V : PtrArgs) {
  1101. SmallVector<const Value *, 4> Objects;
  1102. getUnderlyingObjects(V, Objects, /* LI = */ nullptr);
  1103. for (const Value *O : Objects)
  1104. ObjSet.insert(O);
  1105. }
  1106. // Figure out if we're derived from anything that is not a noalias
  1107. // argument.
  1108. bool RequiresNoCaptureBefore = false, UsesAliasingPtr = false,
  1109. UsesUnknownObject = false;
  1110. for (const Value *V : ObjSet) {
  1111. // Is this value a constant that cannot be derived from any pointer
  1112. // value (we need to exclude constant expressions, for example, that
  1113. // are formed from arithmetic on global symbols).
  1114. bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
  1115. isa<ConstantPointerNull>(V) ||
  1116. isa<ConstantDataVector>(V) || isa<UndefValue>(V);
  1117. if (IsNonPtrConst)
  1118. continue;
  1119. // If this is anything other than a noalias argument, then we cannot
  1120. // completely describe the aliasing properties using alias.scope
  1121. // metadata (and, thus, won't add any).
  1122. if (const Argument *A = dyn_cast<Argument>(V)) {
  1123. if (!CB.paramHasAttr(A->getArgNo(), Attribute::NoAlias))
  1124. UsesAliasingPtr = true;
  1125. } else {
  1126. UsesAliasingPtr = true;
  1127. }
  1128. if (isEscapeSource(V)) {
  1129. // An escape source can only alias with a noalias argument if it has
  1130. // been captured beforehand.
  1131. RequiresNoCaptureBefore = true;
  1132. } else if (!isa<Argument>(V) && !isIdentifiedObject(V)) {
  1133. // If this is neither an escape source, nor some identified object
  1134. // (which cannot directly alias a noalias argument), nor some other
  1135. // argument (which, by definition, also cannot alias a noalias
  1136. // argument), conservatively do not make any assumptions.
  1137. UsesUnknownObject = true;
  1138. }
  1139. }
  1140. // Nothing we can do if the used underlying object cannot be reliably
  1141. // determined.
  1142. if (UsesUnknownObject)
  1143. continue;
  1144. // A function call can always get captured noalias pointers (via other
  1145. // parameters, globals, etc.).
  1146. if (IsFuncCall && !IsArgMemOnlyCall)
  1147. RequiresNoCaptureBefore = true;
  1148. // First, we want to figure out all of the sets with which we definitely
  1149. // don't alias. Iterate over all noalias set, and add those for which:
  1150. // 1. The noalias argument is not in the set of objects from which we
  1151. // definitely derive.
  1152. // 2. The noalias argument has not yet been captured.
  1153. // An arbitrary function that might load pointers could see captured
  1154. // noalias arguments via other noalias arguments or globals, and so we
  1155. // must always check for prior capture.
  1156. for (const Argument *A : NoAliasArgs) {
  1157. if (ObjSet.contains(A))
  1158. continue; // May be based on a noalias argument.
  1159. // It might be tempting to skip the PointerMayBeCapturedBefore check if
  1160. // A->hasNoCaptureAttr() is true, but this is incorrect because
  1161. // nocapture only guarantees that no copies outlive the function, not
  1162. // that the value cannot be locally captured.
  1163. if (!RequiresNoCaptureBefore ||
  1164. !PointerMayBeCapturedBefore(A, /* ReturnCaptures */ false,
  1165. /* StoreCaptures */ false, I, &DT))
  1166. NoAliases.push_back(NewScopes[A]);
  1167. }
  1168. if (!NoAliases.empty())
  1169. NI->setMetadata(LLVMContext::MD_noalias,
  1170. MDNode::concatenate(
  1171. NI->getMetadata(LLVMContext::MD_noalias),
  1172. MDNode::get(CalledFunc->getContext(), NoAliases)));
  1173. // Next, we want to figure out all of the sets to which we might belong.
  1174. // We might belong to a set if the noalias argument is in the set of
  1175. // underlying objects. If there is some non-noalias argument in our list
  1176. // of underlying objects, then we cannot add a scope because the fact
  1177. // that some access does not alias with any set of our noalias arguments
  1178. // cannot itself guarantee that it does not alias with this access
  1179. // (because there is some pointer of unknown origin involved and the
  1180. // other access might also depend on this pointer). We also cannot add
  1181. // scopes to arbitrary functions unless we know they don't access any
  1182. // non-parameter pointer-values.
  1183. bool CanAddScopes = !UsesAliasingPtr;
  1184. if (CanAddScopes && IsFuncCall)
  1185. CanAddScopes = IsArgMemOnlyCall;
  1186. if (CanAddScopes)
  1187. for (const Argument *A : NoAliasArgs) {
  1188. if (ObjSet.count(A))
  1189. Scopes.push_back(NewScopes[A]);
  1190. }
  1191. if (!Scopes.empty())
  1192. NI->setMetadata(
  1193. LLVMContext::MD_alias_scope,
  1194. MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
  1195. MDNode::get(CalledFunc->getContext(), Scopes)));
  1196. }
  1197. }
  1198. }
  1199. static bool MayContainThrowingOrExitingCall(Instruction *Begin,
  1200. Instruction *End) {
  1201. assert(Begin->getParent() == End->getParent() &&
  1202. "Expected to be in same basic block!");
  1203. return !llvm::isGuaranteedToTransferExecutionToSuccessor(
  1204. Begin->getIterator(), End->getIterator(), InlinerAttributeWindow + 1);
  1205. }
  1206. static AttrBuilder IdentifyValidAttributes(CallBase &CB) {
  1207. AttrBuilder AB(CB.getContext(), CB.getAttributes().getRetAttrs());
  1208. if (!AB.hasAttributes())
  1209. return AB;
  1210. AttrBuilder Valid(CB.getContext());
  1211. // Only allow these white listed attributes to be propagated back to the
  1212. // callee. This is because other attributes may only be valid on the call
  1213. // itself, i.e. attributes such as signext and zeroext.
  1214. if (auto DerefBytes = AB.getDereferenceableBytes())
  1215. Valid.addDereferenceableAttr(DerefBytes);
  1216. if (auto DerefOrNullBytes = AB.getDereferenceableOrNullBytes())
  1217. Valid.addDereferenceableOrNullAttr(DerefOrNullBytes);
  1218. if (AB.contains(Attribute::NoAlias))
  1219. Valid.addAttribute(Attribute::NoAlias);
  1220. if (AB.contains(Attribute::NonNull))
  1221. Valid.addAttribute(Attribute::NonNull);
  1222. return Valid;
  1223. }
  1224. static void AddReturnAttributes(CallBase &CB, ValueToValueMapTy &VMap) {
  1225. if (!UpdateReturnAttributes)
  1226. return;
  1227. AttrBuilder Valid = IdentifyValidAttributes(CB);
  1228. if (!Valid.hasAttributes())
  1229. return;
  1230. auto *CalledFunction = CB.getCalledFunction();
  1231. auto &Context = CalledFunction->getContext();
  1232. for (auto &BB : *CalledFunction) {
  1233. auto *RI = dyn_cast<ReturnInst>(BB.getTerminator());
  1234. if (!RI || !isa<CallBase>(RI->getOperand(0)))
  1235. continue;
  1236. auto *RetVal = cast<CallBase>(RI->getOperand(0));
  1237. // Check that the cloned RetVal exists and is a call, otherwise we cannot
  1238. // add the attributes on the cloned RetVal. Simplification during inlining
  1239. // could have transformed the cloned instruction.
  1240. auto *NewRetVal = dyn_cast_or_null<CallBase>(VMap.lookup(RetVal));
  1241. if (!NewRetVal)
  1242. continue;
  1243. // Backward propagation of attributes to the returned value may be incorrect
  1244. // if it is control flow dependent.
  1245. // Consider:
  1246. // @callee {
  1247. // %rv = call @foo()
  1248. // %rv2 = call @bar()
  1249. // if (%rv2 != null)
  1250. // return %rv2
  1251. // if (%rv == null)
  1252. // exit()
  1253. // return %rv
  1254. // }
  1255. // caller() {
  1256. // %val = call nonnull @callee()
  1257. // }
  1258. // Here we cannot add the nonnull attribute on either foo or bar. So, we
  1259. // limit the check to both RetVal and RI are in the same basic block and
  1260. // there are no throwing/exiting instructions between these instructions.
  1261. if (RI->getParent() != RetVal->getParent() ||
  1262. MayContainThrowingOrExitingCall(RetVal, RI))
  1263. continue;
  1264. // Add to the existing attributes of NewRetVal, i.e. the cloned call
  1265. // instruction.
  1266. // NB! When we have the same attribute already existing on NewRetVal, but
  1267. // with a differing value, the AttributeList's merge API honours the already
  1268. // existing attribute value (i.e. attributes such as dereferenceable,
  1269. // dereferenceable_or_null etc). See AttrBuilder::merge for more details.
  1270. AttributeList AL = NewRetVal->getAttributes();
  1271. AttributeList NewAL = AL.addRetAttributes(Context, Valid);
  1272. NewRetVal->setAttributes(NewAL);
  1273. }
  1274. }
  1275. /// If the inlined function has non-byval align arguments, then
  1276. /// add @llvm.assume-based alignment assumptions to preserve this information.
  1277. static void AddAlignmentAssumptions(CallBase &CB, InlineFunctionInfo &IFI) {
  1278. if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache)
  1279. return;
  1280. AssumptionCache *AC = &IFI.GetAssumptionCache(*CB.getCaller());
  1281. auto &DL = CB.getCaller()->getParent()->getDataLayout();
  1282. // To avoid inserting redundant assumptions, we should check for assumptions
  1283. // already in the caller. To do this, we might need a DT of the caller.
  1284. DominatorTree DT;
  1285. bool DTCalculated = false;
  1286. Function *CalledFunc = CB.getCalledFunction();
  1287. for (Argument &Arg : CalledFunc->args()) {
  1288. if (!Arg.getType()->isPointerTy() || Arg.hasPassPointeeByValueCopyAttr() ||
  1289. Arg.hasNUses(0))
  1290. continue;
  1291. MaybeAlign Alignment = Arg.getParamAlign();
  1292. if (!Alignment)
  1293. continue;
  1294. if (!DTCalculated) {
  1295. DT.recalculate(*CB.getCaller());
  1296. DTCalculated = true;
  1297. }
  1298. // If we can already prove the asserted alignment in the context of the
  1299. // caller, then don't bother inserting the assumption.
  1300. Value *ArgVal = CB.getArgOperand(Arg.getArgNo());
  1301. if (getKnownAlignment(ArgVal, DL, &CB, AC, &DT) >= *Alignment)
  1302. continue;
  1303. CallInst *NewAsmp = IRBuilder<>(&CB).CreateAlignmentAssumption(
  1304. DL, ArgVal, Alignment->value());
  1305. AC->registerAssumption(cast<AssumeInst>(NewAsmp));
  1306. }
  1307. }
  1308. /// Once we have cloned code over from a callee into the caller,
  1309. /// update the specified callgraph to reflect the changes we made.
  1310. /// Note that it's possible that not all code was copied over, so only
  1311. /// some edges of the callgraph may remain.
  1312. static void UpdateCallGraphAfterInlining(CallBase &CB,
  1313. Function::iterator FirstNewBlock,
  1314. ValueToValueMapTy &VMap,
  1315. InlineFunctionInfo &IFI) {
  1316. CallGraph &CG = *IFI.CG;
  1317. const Function *Caller = CB.getCaller();
  1318. const Function *Callee = CB.getCalledFunction();
  1319. CallGraphNode *CalleeNode = CG[Callee];
  1320. CallGraphNode *CallerNode = CG[Caller];
  1321. // Since we inlined some uninlined call sites in the callee into the caller,
  1322. // add edges from the caller to all of the callees of the callee.
  1323. CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
  1324. // Consider the case where CalleeNode == CallerNode.
  1325. CallGraphNode::CalledFunctionsVector CallCache;
  1326. if (CalleeNode == CallerNode) {
  1327. CallCache.assign(I, E);
  1328. I = CallCache.begin();
  1329. E = CallCache.end();
  1330. }
  1331. for (; I != E; ++I) {
  1332. // Skip 'refererence' call records.
  1333. if (!I->first)
  1334. continue;
  1335. const Value *OrigCall = *I->first;
  1336. ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
  1337. // Only copy the edge if the call was inlined!
  1338. if (VMI == VMap.end() || VMI->second == nullptr)
  1339. continue;
  1340. // If the call was inlined, but then constant folded, there is no edge to
  1341. // add. Check for this case.
  1342. auto *NewCall = dyn_cast<CallBase>(VMI->second);
  1343. if (!NewCall)
  1344. continue;
  1345. // We do not treat intrinsic calls like real function calls because we
  1346. // expect them to become inline code; do not add an edge for an intrinsic.
  1347. if (NewCall->getCalledFunction() &&
  1348. NewCall->getCalledFunction()->isIntrinsic())
  1349. continue;
  1350. // Remember that this call site got inlined for the client of
  1351. // InlineFunction.
  1352. IFI.InlinedCalls.push_back(NewCall);
  1353. // It's possible that inlining the callsite will cause it to go from an
  1354. // indirect to a direct call by resolving a function pointer. If this
  1355. // happens, set the callee of the new call site to a more precise
  1356. // destination. This can also happen if the call graph node of the caller
  1357. // was just unnecessarily imprecise.
  1358. if (!I->second->getFunction())
  1359. if (Function *F = NewCall->getCalledFunction()) {
  1360. // Indirect call site resolved to direct call.
  1361. CallerNode->addCalledFunction(NewCall, CG[F]);
  1362. continue;
  1363. }
  1364. CallerNode->addCalledFunction(NewCall, I->second);
  1365. }
  1366. // Update the call graph by deleting the edge from Callee to Caller. We must
  1367. // do this after the loop above in case Caller and Callee are the same.
  1368. CallerNode->removeCallEdgeFor(*cast<CallBase>(&CB));
  1369. }
  1370. static void HandleByValArgumentInit(Type *ByValType, Value *Dst, Value *Src,
  1371. Module *M, BasicBlock *InsertBlock,
  1372. InlineFunctionInfo &IFI) {
  1373. IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
  1374. Value *Size =
  1375. Builder.getInt64(M->getDataLayout().getTypeStoreSize(ByValType));
  1376. // Always generate a memcpy of alignment 1 here because we don't know
  1377. // the alignment of the src pointer. Other optimizations can infer
  1378. // better alignment.
  1379. Builder.CreateMemCpy(Dst, /*DstAlign*/ Align(1), Src,
  1380. /*SrcAlign*/ Align(1), Size);
  1381. }
  1382. /// When inlining a call site that has a byval argument,
  1383. /// we have to make the implicit memcpy explicit by adding it.
  1384. static Value *HandleByValArgument(Type *ByValType, Value *Arg,
  1385. Instruction *TheCall,
  1386. const Function *CalledFunc,
  1387. InlineFunctionInfo &IFI,
  1388. MaybeAlign ByValAlignment) {
  1389. assert(cast<PointerType>(Arg->getType())
  1390. ->isOpaqueOrPointeeTypeMatches(ByValType));
  1391. Function *Caller = TheCall->getFunction();
  1392. const DataLayout &DL = Caller->getParent()->getDataLayout();
  1393. // If the called function is readonly, then it could not mutate the caller's
  1394. // copy of the byval'd memory. In this case, it is safe to elide the copy and
  1395. // temporary.
  1396. if (CalledFunc->onlyReadsMemory()) {
  1397. // If the byval argument has a specified alignment that is greater than the
  1398. // passed in pointer, then we either have to round up the input pointer or
  1399. // give up on this transformation.
  1400. if (ByValAlignment.valueOrOne() == 1)
  1401. return Arg;
  1402. AssumptionCache *AC =
  1403. IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr;
  1404. // If the pointer is already known to be sufficiently aligned, or if we can
  1405. // round it up to a larger alignment, then we don't need a temporary.
  1406. if (getOrEnforceKnownAlignment(Arg, *ByValAlignment, DL, TheCall, AC) >=
  1407. *ByValAlignment)
  1408. return Arg;
  1409. // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
  1410. // for code quality, but rarely happens and is required for correctness.
  1411. }
  1412. // Create the alloca. If we have DataLayout, use nice alignment.
  1413. Align Alignment = DL.getPrefTypeAlign(ByValType);
  1414. // If the byval had an alignment specified, we *must* use at least that
  1415. // alignment, as it is required by the byval argument (and uses of the
  1416. // pointer inside the callee).
  1417. if (ByValAlignment)
  1418. Alignment = std::max(Alignment, *ByValAlignment);
  1419. Value *NewAlloca =
  1420. new AllocaInst(ByValType, DL.getAllocaAddrSpace(), nullptr, Alignment,
  1421. Arg->getName(), &*Caller->begin()->begin());
  1422. IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
  1423. // Uses of the argument in the function should use our new alloca
  1424. // instead.
  1425. return NewAlloca;
  1426. }
  1427. // Check whether this Value is used by a lifetime intrinsic.
  1428. static bool isUsedByLifetimeMarker(Value *V) {
  1429. for (User *U : V->users())
  1430. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U))
  1431. if (II->isLifetimeStartOrEnd())
  1432. return true;
  1433. return false;
  1434. }
  1435. // Check whether the given alloca already has
  1436. // lifetime.start or lifetime.end intrinsics.
  1437. static bool hasLifetimeMarkers(AllocaInst *AI) {
  1438. Type *Ty = AI->getType();
  1439. Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
  1440. Ty->getPointerAddressSpace());
  1441. if (Ty == Int8PtrTy)
  1442. return isUsedByLifetimeMarker(AI);
  1443. // Do a scan to find all the casts to i8*.
  1444. for (User *U : AI->users()) {
  1445. if (U->getType() != Int8PtrTy) continue;
  1446. if (U->stripPointerCasts() != AI) continue;
  1447. if (isUsedByLifetimeMarker(U))
  1448. return true;
  1449. }
  1450. return false;
  1451. }
  1452. /// Return the result of AI->isStaticAlloca() if AI were moved to the entry
  1453. /// block. Allocas used in inalloca calls and allocas of dynamic array size
  1454. /// cannot be static.
  1455. static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) {
  1456. return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca();
  1457. }
  1458. /// Returns a DebugLoc for a new DILocation which is a clone of \p OrigDL
  1459. /// inlined at \p InlinedAt. \p IANodes is an inlined-at cache.
  1460. static DebugLoc inlineDebugLoc(DebugLoc OrigDL, DILocation *InlinedAt,
  1461. LLVMContext &Ctx,
  1462. DenseMap<const MDNode *, MDNode *> &IANodes) {
  1463. auto IA = DebugLoc::appendInlinedAt(OrigDL, InlinedAt, Ctx, IANodes);
  1464. return DILocation::get(Ctx, OrigDL.getLine(), OrigDL.getCol(),
  1465. OrigDL.getScope(), IA);
  1466. }
  1467. /// Update inlined instructions' line numbers to
  1468. /// to encode location where these instructions are inlined.
  1469. static void fixupLineNumbers(Function *Fn, Function::iterator FI,
  1470. Instruction *TheCall, bool CalleeHasDebugInfo) {
  1471. const DebugLoc &TheCallDL = TheCall->getDebugLoc();
  1472. if (!TheCallDL)
  1473. return;
  1474. auto &Ctx = Fn->getContext();
  1475. DILocation *InlinedAtNode = TheCallDL;
  1476. // Create a unique call site, not to be confused with any other call from the
  1477. // same location.
  1478. InlinedAtNode = DILocation::getDistinct(
  1479. Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
  1480. InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());
  1481. // Cache the inlined-at nodes as they're built so they are reused, without
  1482. // this every instruction's inlined-at chain would become distinct from each
  1483. // other.
  1484. DenseMap<const MDNode *, MDNode *> IANodes;
  1485. // Check if we are not generating inline line tables and want to use
  1486. // the call site location instead.
  1487. bool NoInlineLineTables = Fn->hasFnAttribute("no-inline-line-tables");
  1488. for (; FI != Fn->end(); ++FI) {
  1489. for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
  1490. BI != BE; ++BI) {
  1491. // Loop metadata needs to be updated so that the start and end locs
  1492. // reference inlined-at locations.
  1493. auto updateLoopInfoLoc = [&Ctx, &InlinedAtNode,
  1494. &IANodes](Metadata *MD) -> Metadata * {
  1495. if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
  1496. return inlineDebugLoc(Loc, InlinedAtNode, Ctx, IANodes).get();
  1497. return MD;
  1498. };
  1499. updateLoopMetadataDebugLocations(*BI, updateLoopInfoLoc);
  1500. if (!NoInlineLineTables)
  1501. if (DebugLoc DL = BI->getDebugLoc()) {
  1502. DebugLoc IDL =
  1503. inlineDebugLoc(DL, InlinedAtNode, BI->getContext(), IANodes);
  1504. BI->setDebugLoc(IDL);
  1505. continue;
  1506. }
  1507. if (CalleeHasDebugInfo && !NoInlineLineTables)
  1508. continue;
  1509. // If the inlined instruction has no line number, or if inline info
  1510. // is not being generated, make it look as if it originates from the call
  1511. // location. This is important for ((__always_inline, __nodebug__))
  1512. // functions which must use caller location for all instructions in their
  1513. // function body.
  1514. // Don't update static allocas, as they may get moved later.
  1515. if (auto *AI = dyn_cast<AllocaInst>(BI))
  1516. if (allocaWouldBeStaticInEntry(AI))
  1517. continue;
  1518. BI->setDebugLoc(TheCallDL);
  1519. }
  1520. // Remove debug info intrinsics if we're not keeping inline info.
  1521. if (NoInlineLineTables) {
  1522. BasicBlock::iterator BI = FI->begin();
  1523. while (BI != FI->end()) {
  1524. if (isa<DbgInfoIntrinsic>(BI)) {
  1525. BI = BI->eraseFromParent();
  1526. continue;
  1527. }
  1528. ++BI;
  1529. }
  1530. }
  1531. }
  1532. }
  1533. #undef DEBUG_TYPE
  1534. #define DEBUG_TYPE "assignment-tracking"
  1535. /// Find Alloca and linked DbgAssignIntrinsic for locals escaped by \p CB.
  1536. static at::StorageToVarsMap collectEscapedLocals(const DataLayout &DL,
  1537. const CallBase &CB) {
  1538. at::StorageToVarsMap EscapedLocals;
  1539. SmallPtrSet<const Value *, 4> SeenBases;
  1540. LLVM_DEBUG(
  1541. errs() << "# Finding caller local variables escaped by callee\n");
  1542. for (const Value *Arg : CB.args()) {
  1543. LLVM_DEBUG(errs() << "INSPECT: " << *Arg << "\n");
  1544. if (!Arg->getType()->isPointerTy()) {
  1545. LLVM_DEBUG(errs() << " | SKIP: Not a pointer\n");
  1546. continue;
  1547. }
  1548. const Instruction *I = dyn_cast<Instruction>(Arg);
  1549. if (!I) {
  1550. LLVM_DEBUG(errs() << " | SKIP: Not result of instruction\n");
  1551. continue;
  1552. }
  1553. // Walk back to the base storage.
  1554. assert(Arg->getType()->isPtrOrPtrVectorTy());
  1555. APInt TmpOffset(DL.getIndexTypeSizeInBits(Arg->getType()), 0, false);
  1556. const AllocaInst *Base = dyn_cast<AllocaInst>(
  1557. Arg->stripAndAccumulateConstantOffsets(DL, TmpOffset, true));
  1558. if (!Base) {
  1559. LLVM_DEBUG(errs() << " | SKIP: Couldn't walk back to base storage\n");
  1560. continue;
  1561. }
  1562. assert(Base);
  1563. LLVM_DEBUG(errs() << " | BASE: " << *Base << "\n");
  1564. // We only need to process each base address once - skip any duplicates.
  1565. if (!SeenBases.insert(Base).second)
  1566. continue;
  1567. // Find all local variables associated with the backing storage.
  1568. for (auto *DAI : at::getAssignmentMarkers(Base)) {
  1569. // Skip variables from inlined functions - they are not local variables.
  1570. if (DAI->getDebugLoc().getInlinedAt())
  1571. continue;
  1572. LLVM_DEBUG(errs() << " > DEF : " << *DAI << "\n");
  1573. EscapedLocals[Base].insert(at::VarRecord(DAI));
  1574. }
  1575. }
  1576. return EscapedLocals;
  1577. }
  1578. static void trackInlinedStores(Function::iterator Start, Function::iterator End,
  1579. const CallBase &CB) {
  1580. LLVM_DEBUG(errs() << "trackInlinedStores into "
  1581. << Start->getParent()->getName() << " from "
  1582. << CB.getCalledFunction()->getName() << "\n");
  1583. std::unique_ptr<DataLayout> DL = std::make_unique<DataLayout>(CB.getModule());
  1584. at::trackAssignments(Start, End, collectEscapedLocals(*DL, CB), *DL);
  1585. }
  1586. /// Update inlined instructions' DIAssignID metadata. We need to do this
  1587. /// otherwise a function inlined more than once into the same function
  1588. /// will cause DIAssignID to be shared by many instructions.
  1589. static void fixupAssignments(Function::iterator Start, Function::iterator End) {
  1590. // Map {Old, New} metadata. Not used directly - use GetNewID.
  1591. DenseMap<DIAssignID *, DIAssignID *> Map;
  1592. auto GetNewID = [&Map](Metadata *Old) {
  1593. DIAssignID *OldID = cast<DIAssignID>(Old);
  1594. if (DIAssignID *NewID = Map.lookup(OldID))
  1595. return NewID;
  1596. DIAssignID *NewID = DIAssignID::getDistinct(OldID->getContext());
  1597. Map[OldID] = NewID;
  1598. return NewID;
  1599. };
  1600. // Loop over all the inlined instructions. If we find a DIAssignID
  1601. // attachment or use, replace it with a new version.
  1602. for (auto BBI = Start; BBI != End; ++BBI) {
  1603. for (Instruction &I : *BBI) {
  1604. if (auto *ID = I.getMetadata(LLVMContext::MD_DIAssignID))
  1605. I.setMetadata(LLVMContext::MD_DIAssignID, GetNewID(ID));
  1606. else if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&I))
  1607. DAI->setAssignId(GetNewID(DAI->getAssignID()));
  1608. }
  1609. }
  1610. }
  1611. #undef DEBUG_TYPE
  1612. #define DEBUG_TYPE "inline-function"
  1613. /// Update the block frequencies of the caller after a callee has been inlined.
  1614. ///
  1615. /// Each block cloned into the caller has its block frequency scaled by the
  1616. /// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of
  1617. /// callee's entry block gets the same frequency as the callsite block and the
  1618. /// relative frequencies of all cloned blocks remain the same after cloning.
  1619. static void updateCallerBFI(BasicBlock *CallSiteBlock,
  1620. const ValueToValueMapTy &VMap,
  1621. BlockFrequencyInfo *CallerBFI,
  1622. BlockFrequencyInfo *CalleeBFI,
  1623. const BasicBlock &CalleeEntryBlock) {
  1624. SmallPtrSet<BasicBlock *, 16> ClonedBBs;
  1625. for (auto Entry : VMap) {
  1626. if (!isa<BasicBlock>(Entry.first) || !Entry.second)
  1627. continue;
  1628. auto *OrigBB = cast<BasicBlock>(Entry.first);
  1629. auto *ClonedBB = cast<BasicBlock>(Entry.second);
  1630. uint64_t Freq = CalleeBFI->getBlockFreq(OrigBB).getFrequency();
  1631. if (!ClonedBBs.insert(ClonedBB).second) {
  1632. // Multiple blocks in the callee might get mapped to one cloned block in
  1633. // the caller since we prune the callee as we clone it. When that happens,
  1634. // we want to use the maximum among the original blocks' frequencies.
  1635. uint64_t NewFreq = CallerBFI->getBlockFreq(ClonedBB).getFrequency();
  1636. if (NewFreq > Freq)
  1637. Freq = NewFreq;
  1638. }
  1639. CallerBFI->setBlockFreq(ClonedBB, Freq);
  1640. }
  1641. BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock));
  1642. CallerBFI->setBlockFreqAndScale(
  1643. EntryClone, CallerBFI->getBlockFreq(CallSiteBlock).getFrequency(),
  1644. ClonedBBs);
  1645. }
  1646. /// Update the branch metadata for cloned call instructions.
  1647. static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap,
  1648. const ProfileCount &CalleeEntryCount,
  1649. const CallBase &TheCall, ProfileSummaryInfo *PSI,
  1650. BlockFrequencyInfo *CallerBFI) {
  1651. if (CalleeEntryCount.isSynthetic() || CalleeEntryCount.getCount() < 1)
  1652. return;
  1653. auto CallSiteCount =
  1654. PSI ? PSI->getProfileCount(TheCall, CallerBFI) : std::nullopt;
  1655. int64_t CallCount =
  1656. std::min(CallSiteCount.value_or(0), CalleeEntryCount.getCount());
  1657. updateProfileCallee(Callee, -CallCount, &VMap);
  1658. }
  1659. void llvm::updateProfileCallee(
  1660. Function *Callee, int64_t EntryDelta,
  1661. const ValueMap<const Value *, WeakTrackingVH> *VMap) {
  1662. auto CalleeCount = Callee->getEntryCount();
  1663. if (!CalleeCount)
  1664. return;
  1665. const uint64_t PriorEntryCount = CalleeCount->getCount();
  1666. // Since CallSiteCount is an estimate, it could exceed the original callee
  1667. // count and has to be set to 0 so guard against underflow.
  1668. const uint64_t NewEntryCount =
  1669. (EntryDelta < 0 && static_cast<uint64_t>(-EntryDelta) > PriorEntryCount)
  1670. ? 0
  1671. : PriorEntryCount + EntryDelta;
  1672. // During inlining ?
  1673. if (VMap) {
  1674. uint64_t CloneEntryCount = PriorEntryCount - NewEntryCount;
  1675. for (auto Entry : *VMap)
  1676. if (isa<CallInst>(Entry.first))
  1677. if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second))
  1678. CI->updateProfWeight(CloneEntryCount, PriorEntryCount);
  1679. }
  1680. if (EntryDelta) {
  1681. Callee->setEntryCount(NewEntryCount);
  1682. for (BasicBlock &BB : *Callee)
  1683. // No need to update the callsite if it is pruned during inlining.
  1684. if (!VMap || VMap->count(&BB))
  1685. for (Instruction &I : BB)
  1686. if (CallInst *CI = dyn_cast<CallInst>(&I))
  1687. CI->updateProfWeight(NewEntryCount, PriorEntryCount);
  1688. }
  1689. }
  1690. /// An operand bundle "clang.arc.attachedcall" on a call indicates the call
  1691. /// result is implicitly consumed by a call to retainRV or claimRV immediately
  1692. /// after the call. This function inlines the retainRV/claimRV calls.
  1693. ///
  1694. /// There are three cases to consider:
  1695. ///
  1696. /// 1. If there is a call to autoreleaseRV that takes a pointer to the returned
  1697. /// object in the callee return block, the autoreleaseRV call and the
  1698. /// retainRV/claimRV call in the caller cancel out. If the call in the caller
  1699. /// is a claimRV call, a call to objc_release is emitted.
  1700. ///
  1701. /// 2. If there is a call in the callee return block that doesn't have operand
  1702. /// bundle "clang.arc.attachedcall", the operand bundle on the original call
  1703. /// is transferred to the call in the callee.
  1704. ///
  1705. /// 3. Otherwise, a call to objc_retain is inserted if the call in the caller is
  1706. /// a retainRV call.
  1707. static void
  1708. inlineRetainOrClaimRVCalls(CallBase &CB, objcarc::ARCInstKind RVCallKind,
  1709. const SmallVectorImpl<ReturnInst *> &Returns) {
  1710. Module *Mod = CB.getModule();
  1711. assert(objcarc::isRetainOrClaimRV(RVCallKind) && "unexpected ARC function");
  1712. bool IsRetainRV = RVCallKind == objcarc::ARCInstKind::RetainRV,
  1713. IsUnsafeClaimRV = !IsRetainRV;
  1714. for (auto *RI : Returns) {
  1715. Value *RetOpnd = objcarc::GetRCIdentityRoot(RI->getOperand(0));
  1716. bool InsertRetainCall = IsRetainRV;
  1717. IRBuilder<> Builder(RI->getContext());
  1718. // Walk backwards through the basic block looking for either a matching
  1719. // autoreleaseRV call or an unannotated call.
  1720. auto InstRange = llvm::make_range(++(RI->getIterator().getReverse()),
  1721. RI->getParent()->rend());
  1722. for (Instruction &I : llvm::make_early_inc_range(InstRange)) {
  1723. // Ignore casts.
  1724. if (isa<CastInst>(I))
  1725. continue;
  1726. if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
  1727. if (II->getIntrinsicID() != Intrinsic::objc_autoreleaseReturnValue ||
  1728. !II->hasNUses(0) ||
  1729. objcarc::GetRCIdentityRoot(II->getOperand(0)) != RetOpnd)
  1730. break;
  1731. // If we've found a matching authoreleaseRV call:
  1732. // - If claimRV is attached to the call, insert a call to objc_release
  1733. // and erase the autoreleaseRV call.
  1734. // - If retainRV is attached to the call, just erase the autoreleaseRV
  1735. // call.
  1736. if (IsUnsafeClaimRV) {
  1737. Builder.SetInsertPoint(II);
  1738. Function *IFn =
  1739. Intrinsic::getDeclaration(Mod, Intrinsic::objc_release);
  1740. Value *BC = Builder.CreateBitCast(RetOpnd, IFn->getArg(0)->getType());
  1741. Builder.CreateCall(IFn, BC, "");
  1742. }
  1743. II->eraseFromParent();
  1744. InsertRetainCall = false;
  1745. break;
  1746. }
  1747. auto *CI = dyn_cast<CallInst>(&I);
  1748. if (!CI)
  1749. break;
  1750. if (objcarc::GetRCIdentityRoot(CI) != RetOpnd ||
  1751. objcarc::hasAttachedCallOpBundle(CI))
  1752. break;
  1753. // If we've found an unannotated call that defines RetOpnd, add a
  1754. // "clang.arc.attachedcall" operand bundle.
  1755. Value *BundleArgs[] = {*objcarc::getAttachedARCFunction(&CB)};
  1756. OperandBundleDef OB("clang.arc.attachedcall", BundleArgs);
  1757. auto *NewCall = CallBase::addOperandBundle(
  1758. CI, LLVMContext::OB_clang_arc_attachedcall, OB, CI);
  1759. NewCall->copyMetadata(*CI);
  1760. CI->replaceAllUsesWith(NewCall);
  1761. CI->eraseFromParent();
  1762. InsertRetainCall = false;
  1763. break;
  1764. }
  1765. if (InsertRetainCall) {
  1766. // The retainRV is attached to the call and we've failed to find a
  1767. // matching autoreleaseRV or an annotated call in the callee. Emit a call
  1768. // to objc_retain.
  1769. Builder.SetInsertPoint(RI);
  1770. Function *IFn = Intrinsic::getDeclaration(Mod, Intrinsic::objc_retain);
  1771. Value *BC = Builder.CreateBitCast(RetOpnd, IFn->getArg(0)->getType());
  1772. Builder.CreateCall(IFn, BC, "");
  1773. }
  1774. }
  1775. }
  1776. /// This function inlines the called function into the basic block of the
  1777. /// caller. This returns false if it is not possible to inline this call.
  1778. /// The program is still in a well defined state if this occurs though.
  1779. ///
  1780. /// Note that this only does one level of inlining. For example, if the
  1781. /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
  1782. /// exists in the instruction stream. Similarly this will inline a recursive
  1783. /// function by one level.
  1784. llvm::InlineResult llvm::InlineFunction(CallBase &CB, InlineFunctionInfo &IFI,
  1785. bool MergeAttributes,
  1786. AAResults *CalleeAAR,
  1787. bool InsertLifetime,
  1788. Function *ForwardVarArgsTo) {
  1789. assert(CB.getParent() && CB.getFunction() && "Instruction not in function!");
  1790. // FIXME: we don't inline callbr yet.
  1791. if (isa<CallBrInst>(CB))
  1792. return InlineResult::failure("We don't inline callbr yet.");
  1793. // If IFI has any state in it, zap it before we fill it in.
  1794. IFI.reset();
  1795. Function *CalledFunc = CB.getCalledFunction();
  1796. if (!CalledFunc || // Can't inline external function or indirect
  1797. CalledFunc->isDeclaration()) // call!
  1798. return InlineResult::failure("external or indirect");
  1799. // The inliner does not know how to inline through calls with operand bundles
  1800. // in general ...
  1801. if (CB.hasOperandBundles()) {
  1802. for (int i = 0, e = CB.getNumOperandBundles(); i != e; ++i) {
  1803. uint32_t Tag = CB.getOperandBundleAt(i).getTagID();
  1804. // ... but it knows how to inline through "deopt" operand bundles ...
  1805. if (Tag == LLVMContext::OB_deopt)
  1806. continue;
  1807. // ... and "funclet" operand bundles.
  1808. if (Tag == LLVMContext::OB_funclet)
  1809. continue;
  1810. if (Tag == LLVMContext::OB_clang_arc_attachedcall)
  1811. continue;
  1812. if (Tag == LLVMContext::OB_kcfi)
  1813. continue;
  1814. return InlineResult::failure("unsupported operand bundle");
  1815. }
  1816. }
  1817. // If the call to the callee cannot throw, set the 'nounwind' flag on any
  1818. // calls that we inline.
  1819. bool MarkNoUnwind = CB.doesNotThrow();
  1820. BasicBlock *OrigBB = CB.getParent();
  1821. Function *Caller = OrigBB->getParent();
  1822. // Do not inline strictfp function into non-strictfp one. It would require
  1823. // conversion of all FP operations in host function to constrained intrinsics.
  1824. if (CalledFunc->getAttributes().hasFnAttr(Attribute::StrictFP) &&
  1825. !Caller->getAttributes().hasFnAttr(Attribute::StrictFP)) {
  1826. return InlineResult::failure("incompatible strictfp attributes");
  1827. }
  1828. // GC poses two hazards to inlining, which only occur when the callee has GC:
  1829. // 1. If the caller has no GC, then the callee's GC must be propagated to the
  1830. // caller.
  1831. // 2. If the caller has a differing GC, it is invalid to inline.
  1832. if (CalledFunc->hasGC()) {
  1833. if (!Caller->hasGC())
  1834. Caller->setGC(CalledFunc->getGC());
  1835. else if (CalledFunc->getGC() != Caller->getGC())
  1836. return InlineResult::failure("incompatible GC");
  1837. }
  1838. // Get the personality function from the callee if it contains a landing pad.
  1839. Constant *CalledPersonality =
  1840. CalledFunc->hasPersonalityFn()
  1841. ? CalledFunc->getPersonalityFn()->stripPointerCasts()
  1842. : nullptr;
  1843. // Find the personality function used by the landing pads of the caller. If it
  1844. // exists, then check to see that it matches the personality function used in
  1845. // the callee.
  1846. Constant *CallerPersonality =
  1847. Caller->hasPersonalityFn()
  1848. ? Caller->getPersonalityFn()->stripPointerCasts()
  1849. : nullptr;
  1850. if (CalledPersonality) {
  1851. if (!CallerPersonality)
  1852. Caller->setPersonalityFn(CalledPersonality);
  1853. // If the personality functions match, then we can perform the
  1854. // inlining. Otherwise, we can't inline.
  1855. // TODO: This isn't 100% true. Some personality functions are proper
  1856. // supersets of others and can be used in place of the other.
  1857. else if (CalledPersonality != CallerPersonality)
  1858. return InlineResult::failure("incompatible personality");
  1859. }
  1860. // We need to figure out which funclet the callsite was in so that we may
  1861. // properly nest the callee.
  1862. Instruction *CallSiteEHPad = nullptr;
  1863. if (CallerPersonality) {
  1864. EHPersonality Personality = classifyEHPersonality(CallerPersonality);
  1865. if (isScopedEHPersonality(Personality)) {
  1866. std::optional<OperandBundleUse> ParentFunclet =
  1867. CB.getOperandBundle(LLVMContext::OB_funclet);
  1868. if (ParentFunclet)
  1869. CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front());
  1870. // OK, the inlining site is legal. What about the target function?
  1871. if (CallSiteEHPad) {
  1872. if (Personality == EHPersonality::MSVC_CXX) {
  1873. // The MSVC personality cannot tolerate catches getting inlined into
  1874. // cleanup funclets.
  1875. if (isa<CleanupPadInst>(CallSiteEHPad)) {
  1876. // Ok, the call site is within a cleanuppad. Let's check the callee
  1877. // for catchpads.
  1878. for (const BasicBlock &CalledBB : *CalledFunc) {
  1879. if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI()))
  1880. return InlineResult::failure("catch in cleanup funclet");
  1881. }
  1882. }
  1883. } else if (isAsynchronousEHPersonality(Personality)) {
  1884. // SEH is even less tolerant, there may not be any sort of exceptional
  1885. // funclet in the callee.
  1886. for (const BasicBlock &CalledBB : *CalledFunc) {
  1887. if (CalledBB.isEHPad())
  1888. return InlineResult::failure("SEH in cleanup funclet");
  1889. }
  1890. }
  1891. }
  1892. }
  1893. }
  1894. // Determine if we are dealing with a call in an EHPad which does not unwind
  1895. // to caller.
  1896. bool EHPadForCallUnwindsLocally = false;
  1897. if (CallSiteEHPad && isa<CallInst>(CB)) {
  1898. UnwindDestMemoTy FuncletUnwindMap;
  1899. Value *CallSiteUnwindDestToken =
  1900. getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap);
  1901. EHPadForCallUnwindsLocally =
  1902. CallSiteUnwindDestToken &&
  1903. !isa<ConstantTokenNone>(CallSiteUnwindDestToken);
  1904. }
  1905. // Get an iterator to the last basic block in the function, which will have
  1906. // the new function inlined after it.
  1907. Function::iterator LastBlock = --Caller->end();
  1908. // Make sure to capture all of the return instructions from the cloned
  1909. // function.
  1910. SmallVector<ReturnInst*, 8> Returns;
  1911. ClonedCodeInfo InlinedFunctionInfo;
  1912. Function::iterator FirstNewBlock;
  1913. { // Scope to destroy VMap after cloning.
  1914. ValueToValueMapTy VMap;
  1915. struct ByValInit {
  1916. Value *Dst;
  1917. Value *Src;
  1918. Type *Ty;
  1919. };
  1920. // Keep a list of pair (dst, src) to emit byval initializations.
  1921. SmallVector<ByValInit, 4> ByValInits;
  1922. // When inlining a function that contains noalias scope metadata,
  1923. // this metadata needs to be cloned so that the inlined blocks
  1924. // have different "unique scopes" at every call site.
  1925. // Track the metadata that must be cloned. Do this before other changes to
  1926. // the function, so that we do not get in trouble when inlining caller ==
  1927. // callee.
  1928. ScopedAliasMetadataDeepCloner SAMetadataCloner(CB.getCalledFunction());
  1929. auto &DL = Caller->getParent()->getDataLayout();
  1930. // Calculate the vector of arguments to pass into the function cloner, which
  1931. // matches up the formal to the actual argument values.
  1932. auto AI = CB.arg_begin();
  1933. unsigned ArgNo = 0;
  1934. for (Function::arg_iterator I = CalledFunc->arg_begin(),
  1935. E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
  1936. Value *ActualArg = *AI;
  1937. // When byval arguments actually inlined, we need to make the copy implied
  1938. // by them explicit. However, we don't do this if the callee is readonly
  1939. // or readnone, because the copy would be unneeded: the callee doesn't
  1940. // modify the struct.
  1941. if (CB.isByValArgument(ArgNo)) {
  1942. ActualArg = HandleByValArgument(CB.getParamByValType(ArgNo), ActualArg,
  1943. &CB, CalledFunc, IFI,
  1944. CalledFunc->getParamAlign(ArgNo));
  1945. if (ActualArg != *AI)
  1946. ByValInits.push_back(
  1947. {ActualArg, (Value *)*AI, CB.getParamByValType(ArgNo)});
  1948. }
  1949. VMap[&*I] = ActualArg;
  1950. }
  1951. // TODO: Remove this when users have been updated to the assume bundles.
  1952. // Add alignment assumptions if necessary. We do this before the inlined
  1953. // instructions are actually cloned into the caller so that we can easily
  1954. // check what will be known at the start of the inlined code.
  1955. AddAlignmentAssumptions(CB, IFI);
  1956. AssumptionCache *AC =
  1957. IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr;
  1958. /// Preserve all attributes on of the call and its parameters.
  1959. salvageKnowledge(&CB, AC);
  1960. // We want the inliner to prune the code as it copies. We would LOVE to
  1961. // have no dead or constant instructions leftover after inlining occurs
  1962. // (which can happen, e.g., because an argument was constant), but we'll be
  1963. // happy with whatever the cloner can do.
  1964. CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
  1965. /*ModuleLevelChanges=*/false, Returns, ".i",
  1966. &InlinedFunctionInfo);
  1967. // Remember the first block that is newly cloned over.
  1968. FirstNewBlock = LastBlock; ++FirstNewBlock;
  1969. // Insert retainRV/clainRV runtime calls.
  1970. objcarc::ARCInstKind RVCallKind = objcarc::getAttachedARCFunctionKind(&CB);
  1971. if (RVCallKind != objcarc::ARCInstKind::None)
  1972. inlineRetainOrClaimRVCalls(CB, RVCallKind, Returns);
  1973. // Updated caller/callee profiles only when requested. For sample loader
  1974. // inlining, the context-sensitive inlinee profile doesn't need to be
  1975. // subtracted from callee profile, and the inlined clone also doesn't need
  1976. // to be scaled based on call site count.
  1977. if (IFI.UpdateProfile) {
  1978. if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr)
  1979. // Update the BFI of blocks cloned into the caller.
  1980. updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI,
  1981. CalledFunc->front());
  1982. if (auto Profile = CalledFunc->getEntryCount())
  1983. updateCallProfile(CalledFunc, VMap, *Profile, CB, IFI.PSI,
  1984. IFI.CallerBFI);
  1985. }
  1986. // Inject byval arguments initialization.
  1987. for (ByValInit &Init : ByValInits)
  1988. HandleByValArgumentInit(Init.Ty, Init.Dst, Init.Src, Caller->getParent(),
  1989. &*FirstNewBlock, IFI);
  1990. std::optional<OperandBundleUse> ParentDeopt =
  1991. CB.getOperandBundle(LLVMContext::OB_deopt);
  1992. if (ParentDeopt) {
  1993. SmallVector<OperandBundleDef, 2> OpDefs;
  1994. for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
  1995. CallBase *ICS = dyn_cast_or_null<CallBase>(VH);
  1996. if (!ICS)
  1997. continue; // instruction was DCE'd or RAUW'ed to undef
  1998. OpDefs.clear();
  1999. OpDefs.reserve(ICS->getNumOperandBundles());
  2000. for (unsigned COBi = 0, COBe = ICS->getNumOperandBundles(); COBi < COBe;
  2001. ++COBi) {
  2002. auto ChildOB = ICS->getOperandBundleAt(COBi);
  2003. if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
  2004. // If the inlined call has other operand bundles, let them be
  2005. OpDefs.emplace_back(ChildOB);
  2006. continue;
  2007. }
  2008. // It may be useful to separate this logic (of handling operand
  2009. // bundles) out to a separate "policy" component if this gets crowded.
  2010. // Prepend the parent's deoptimization continuation to the newly
  2011. // inlined call's deoptimization continuation.
  2012. std::vector<Value *> MergedDeoptArgs;
  2013. MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() +
  2014. ChildOB.Inputs.size());
  2015. llvm::append_range(MergedDeoptArgs, ParentDeopt->Inputs);
  2016. llvm::append_range(MergedDeoptArgs, ChildOB.Inputs);
  2017. OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs));
  2018. }
  2019. Instruction *NewI = CallBase::Create(ICS, OpDefs, ICS);
  2020. // Note: the RAUW does the appropriate fixup in VMap, so we need to do
  2021. // this even if the call returns void.
  2022. ICS->replaceAllUsesWith(NewI);
  2023. VH = nullptr;
  2024. ICS->eraseFromParent();
  2025. }
  2026. }
  2027. // Update the callgraph if requested.
  2028. if (IFI.CG)
  2029. UpdateCallGraphAfterInlining(CB, FirstNewBlock, VMap, IFI);
  2030. // For 'nodebug' functions, the associated DISubprogram is always null.
  2031. // Conservatively avoid propagating the callsite debug location to
  2032. // instructions inlined from a function whose DISubprogram is not null.
  2033. fixupLineNumbers(Caller, FirstNewBlock, &CB,
  2034. CalledFunc->getSubprogram() != nullptr);
  2035. if (isAssignmentTrackingEnabled(*Caller->getParent())) {
  2036. // Interpret inlined stores to caller-local variables as assignments.
  2037. trackInlinedStores(FirstNewBlock, Caller->end(), CB);
  2038. // Update DIAssignID metadata attachments and uses so that they are
  2039. // unique to this inlined instance.
  2040. fixupAssignments(FirstNewBlock, Caller->end());
  2041. }
  2042. // Now clone the inlined noalias scope metadata.
  2043. SAMetadataCloner.clone();
  2044. SAMetadataCloner.remap(FirstNewBlock, Caller->end());
  2045. // Add noalias metadata if necessary.
  2046. AddAliasScopeMetadata(CB, VMap, DL, CalleeAAR, InlinedFunctionInfo);
  2047. // Clone return attributes on the callsite into the calls within the inlined
  2048. // function which feed into its return value.
  2049. AddReturnAttributes(CB, VMap);
  2050. propagateMemProfMetadata(CalledFunc, CB,
  2051. InlinedFunctionInfo.ContainsMemProfMetadata, VMap);
  2052. // Propagate metadata on the callsite if necessary.
  2053. PropagateCallSiteMetadata(CB, FirstNewBlock, Caller->end());
  2054. // Register any cloned assumptions.
  2055. if (IFI.GetAssumptionCache)
  2056. for (BasicBlock &NewBlock :
  2057. make_range(FirstNewBlock->getIterator(), Caller->end()))
  2058. for (Instruction &I : NewBlock)
  2059. if (auto *II = dyn_cast<CondGuardInst>(&I))
  2060. IFI.GetAssumptionCache(*Caller).registerAssumption(II);
  2061. }
  2062. // If there are any alloca instructions in the block that used to be the entry
  2063. // block for the callee, move them to the entry block of the caller. First
  2064. // calculate which instruction they should be inserted before. We insert the
  2065. // instructions at the end of the current alloca list.
  2066. {
  2067. BasicBlock::iterator InsertPoint = Caller->begin()->begin();
  2068. for (BasicBlock::iterator I = FirstNewBlock->begin(),
  2069. E = FirstNewBlock->end(); I != E; ) {
  2070. AllocaInst *AI = dyn_cast<AllocaInst>(I++);
  2071. if (!AI) continue;
  2072. // If the alloca is now dead, remove it. This often occurs due to code
  2073. // specialization.
  2074. if (AI->use_empty()) {
  2075. AI->eraseFromParent();
  2076. continue;
  2077. }
  2078. if (!allocaWouldBeStaticInEntry(AI))
  2079. continue;
  2080. // Keep track of the static allocas that we inline into the caller.
  2081. IFI.StaticAllocas.push_back(AI);
  2082. // Scan for the block of allocas that we can move over, and move them
  2083. // all at once.
  2084. while (isa<AllocaInst>(I) &&
  2085. !cast<AllocaInst>(I)->use_empty() &&
  2086. allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) {
  2087. IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
  2088. ++I;
  2089. }
  2090. // Transfer all of the allocas over in a block. Using splice means
  2091. // that the instructions aren't removed from the symbol table, then
  2092. // reinserted.
  2093. Caller->getEntryBlock().splice(InsertPoint, &*FirstNewBlock,
  2094. AI->getIterator(), I);
  2095. }
  2096. }
  2097. SmallVector<Value*,4> VarArgsToForward;
  2098. SmallVector<AttributeSet, 4> VarArgsAttrs;
  2099. for (unsigned i = CalledFunc->getFunctionType()->getNumParams();
  2100. i < CB.arg_size(); i++) {
  2101. VarArgsToForward.push_back(CB.getArgOperand(i));
  2102. VarArgsAttrs.push_back(CB.getAttributes().getParamAttrs(i));
  2103. }
  2104. bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false;
  2105. if (InlinedFunctionInfo.ContainsCalls) {
  2106. CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
  2107. if (CallInst *CI = dyn_cast<CallInst>(&CB))
  2108. CallSiteTailKind = CI->getTailCallKind();
  2109. // For inlining purposes, the "notail" marker is the same as no marker.
  2110. if (CallSiteTailKind == CallInst::TCK_NoTail)
  2111. CallSiteTailKind = CallInst::TCK_None;
  2112. for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
  2113. ++BB) {
  2114. for (Instruction &I : llvm::make_early_inc_range(*BB)) {
  2115. CallInst *CI = dyn_cast<CallInst>(&I);
  2116. if (!CI)
  2117. continue;
  2118. // Forward varargs from inlined call site to calls to the
  2119. // ForwardVarArgsTo function, if requested, and to musttail calls.
  2120. if (!VarArgsToForward.empty() &&
  2121. ((ForwardVarArgsTo &&
  2122. CI->getCalledFunction() == ForwardVarArgsTo) ||
  2123. CI->isMustTailCall())) {
  2124. // Collect attributes for non-vararg parameters.
  2125. AttributeList Attrs = CI->getAttributes();
  2126. SmallVector<AttributeSet, 8> ArgAttrs;
  2127. if (!Attrs.isEmpty() || !VarArgsAttrs.empty()) {
  2128. for (unsigned ArgNo = 0;
  2129. ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo)
  2130. ArgAttrs.push_back(Attrs.getParamAttrs(ArgNo));
  2131. }
  2132. // Add VarArg attributes.
  2133. ArgAttrs.append(VarArgsAttrs.begin(), VarArgsAttrs.end());
  2134. Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttrs(),
  2135. Attrs.getRetAttrs(), ArgAttrs);
  2136. // Add VarArgs to existing parameters.
  2137. SmallVector<Value *, 6> Params(CI->args());
  2138. Params.append(VarArgsToForward.begin(), VarArgsToForward.end());
  2139. CallInst *NewCI = CallInst::Create(
  2140. CI->getFunctionType(), CI->getCalledOperand(), Params, "", CI);
  2141. NewCI->setDebugLoc(CI->getDebugLoc());
  2142. NewCI->setAttributes(Attrs);
  2143. NewCI->setCallingConv(CI->getCallingConv());
  2144. CI->replaceAllUsesWith(NewCI);
  2145. CI->eraseFromParent();
  2146. CI = NewCI;
  2147. }
  2148. if (Function *F = CI->getCalledFunction())
  2149. InlinedDeoptimizeCalls |=
  2150. F->getIntrinsicID() == Intrinsic::experimental_deoptimize;
  2151. // We need to reduce the strength of any inlined tail calls. For
  2152. // musttail, we have to avoid introducing potential unbounded stack
  2153. // growth. For example, if functions 'f' and 'g' are mutually recursive
  2154. // with musttail, we can inline 'g' into 'f' so long as we preserve
  2155. // musttail on the cloned call to 'f'. If either the inlined call site
  2156. // or the cloned call site is *not* musttail, the program already has
  2157. // one frame of stack growth, so it's safe to remove musttail. Here is
  2158. // a table of example transformations:
  2159. //
  2160. // f -> musttail g -> musttail f ==> f -> musttail f
  2161. // f -> musttail g -> tail f ==> f -> tail f
  2162. // f -> g -> musttail f ==> f -> f
  2163. // f -> g -> tail f ==> f -> f
  2164. //
  2165. // Inlined notail calls should remain notail calls.
  2166. CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
  2167. if (ChildTCK != CallInst::TCK_NoTail)
  2168. ChildTCK = std::min(CallSiteTailKind, ChildTCK);
  2169. CI->setTailCallKind(ChildTCK);
  2170. InlinedMustTailCalls |= CI->isMustTailCall();
  2171. // Call sites inlined through a 'nounwind' call site should be
  2172. // 'nounwind' as well. However, avoid marking call sites explicitly
  2173. // where possible. This helps expose more opportunities for CSE after
  2174. // inlining, commonly when the callee is an intrinsic.
  2175. if (MarkNoUnwind && !CI->doesNotThrow())
  2176. CI->setDoesNotThrow();
  2177. }
  2178. }
  2179. }
  2180. // Leave lifetime markers for the static alloca's, scoping them to the
  2181. // function we just inlined.
  2182. // We need to insert lifetime intrinsics even at O0 to avoid invalid
  2183. // access caused by multithreaded coroutines. The check
  2184. // `Caller->isPresplitCoroutine()` would affect AlwaysInliner at O0 only.
  2185. if ((InsertLifetime || Caller->isPresplitCoroutine()) &&
  2186. !IFI.StaticAllocas.empty()) {
  2187. IRBuilder<> builder(&FirstNewBlock->front());
  2188. for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
  2189. AllocaInst *AI = IFI.StaticAllocas[ai];
  2190. // Don't mark swifterror allocas. They can't have bitcast uses.
  2191. if (AI->isSwiftError())
  2192. continue;
  2193. // If the alloca is already scoped to something smaller than the whole
  2194. // function then there's no need to add redundant, less accurate markers.
  2195. if (hasLifetimeMarkers(AI))
  2196. continue;
  2197. // Try to determine the size of the allocation.
  2198. ConstantInt *AllocaSize = nullptr;
  2199. if (ConstantInt *AIArraySize =
  2200. dyn_cast<ConstantInt>(AI->getArraySize())) {
  2201. auto &DL = Caller->getParent()->getDataLayout();
  2202. Type *AllocaType = AI->getAllocatedType();
  2203. TypeSize AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
  2204. uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
  2205. // Don't add markers for zero-sized allocas.
  2206. if (AllocaArraySize == 0)
  2207. continue;
  2208. // Check that array size doesn't saturate uint64_t and doesn't
  2209. // overflow when it's multiplied by type size.
  2210. if (!AllocaTypeSize.isScalable() &&
  2211. AllocaArraySize != std::numeric_limits<uint64_t>::max() &&
  2212. std::numeric_limits<uint64_t>::max() / AllocaArraySize >=
  2213. AllocaTypeSize.getFixedValue()) {
  2214. AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
  2215. AllocaArraySize * AllocaTypeSize);
  2216. }
  2217. }
  2218. builder.CreateLifetimeStart(AI, AllocaSize);
  2219. for (ReturnInst *RI : Returns) {
  2220. // Don't insert llvm.lifetime.end calls between a musttail or deoptimize
  2221. // call and a return. The return kills all local allocas.
  2222. if (InlinedMustTailCalls &&
  2223. RI->getParent()->getTerminatingMustTailCall())
  2224. continue;
  2225. if (InlinedDeoptimizeCalls &&
  2226. RI->getParent()->getTerminatingDeoptimizeCall())
  2227. continue;
  2228. IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
  2229. }
  2230. }
  2231. }
  2232. // If the inlined code contained dynamic alloca instructions, wrap the inlined
  2233. // code with llvm.stacksave/llvm.stackrestore intrinsics.
  2234. if (InlinedFunctionInfo.ContainsDynamicAllocas) {
  2235. Module *M = Caller->getParent();
  2236. // Get the two intrinsics we care about.
  2237. Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
  2238. Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
  2239. // Insert the llvm.stacksave.
  2240. CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin())
  2241. .CreateCall(StackSave, {}, "savedstack");
  2242. // Insert a call to llvm.stackrestore before any return instructions in the
  2243. // inlined function.
  2244. for (ReturnInst *RI : Returns) {
  2245. // Don't insert llvm.stackrestore calls between a musttail or deoptimize
  2246. // call and a return. The return will restore the stack pointer.
  2247. if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
  2248. continue;
  2249. if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall())
  2250. continue;
  2251. IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
  2252. }
  2253. }
  2254. // If we are inlining for an invoke instruction, we must make sure to rewrite
  2255. // any call instructions into invoke instructions. This is sensitive to which
  2256. // funclet pads were top-level in the inlinee, so must be done before
  2257. // rewriting the "parent pad" links.
  2258. if (auto *II = dyn_cast<InvokeInst>(&CB)) {
  2259. BasicBlock *UnwindDest = II->getUnwindDest();
  2260. Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI();
  2261. if (isa<LandingPadInst>(FirstNonPHI)) {
  2262. HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
  2263. } else {
  2264. HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
  2265. }
  2266. }
  2267. // Update the lexical scopes of the new funclets and callsites.
  2268. // Anything that had 'none' as its parent is now nested inside the callsite's
  2269. // EHPad.
  2270. if (CallSiteEHPad) {
  2271. for (Function::iterator BB = FirstNewBlock->getIterator(),
  2272. E = Caller->end();
  2273. BB != E; ++BB) {
  2274. // Add bundle operands to inlined call sites.
  2275. PropagateOperandBundles(BB, CallSiteEHPad);
  2276. // It is problematic if the inlinee has a cleanupret which unwinds to
  2277. // caller and we inline it into a call site which doesn't unwind but into
  2278. // an EH pad that does. Such an edge must be dynamically unreachable.
  2279. // As such, we replace the cleanupret with unreachable.
  2280. if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator()))
  2281. if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally)
  2282. changeToUnreachable(CleanupRet);
  2283. Instruction *I = BB->getFirstNonPHI();
  2284. if (!I->isEHPad())
  2285. continue;
  2286. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
  2287. if (isa<ConstantTokenNone>(CatchSwitch->getParentPad()))
  2288. CatchSwitch->setParentPad(CallSiteEHPad);
  2289. } else {
  2290. auto *FPI = cast<FuncletPadInst>(I);
  2291. if (isa<ConstantTokenNone>(FPI->getParentPad()))
  2292. FPI->setParentPad(CallSiteEHPad);
  2293. }
  2294. }
  2295. }
  2296. if (InlinedDeoptimizeCalls) {
  2297. // We need to at least remove the deoptimizing returns from the Return set,
  2298. // so that the control flow from those returns does not get merged into the
  2299. // caller (but terminate it instead). If the caller's return type does not
  2300. // match the callee's return type, we also need to change the return type of
  2301. // the intrinsic.
  2302. if (Caller->getReturnType() == CB.getType()) {
  2303. llvm::erase_if(Returns, [](ReturnInst *RI) {
  2304. return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr;
  2305. });
  2306. } else {
  2307. SmallVector<ReturnInst *, 8> NormalReturns;
  2308. Function *NewDeoptIntrinsic = Intrinsic::getDeclaration(
  2309. Caller->getParent(), Intrinsic::experimental_deoptimize,
  2310. {Caller->getReturnType()});
  2311. for (ReturnInst *RI : Returns) {
  2312. CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall();
  2313. if (!DeoptCall) {
  2314. NormalReturns.push_back(RI);
  2315. continue;
  2316. }
  2317. // The calling convention on the deoptimize call itself may be bogus,
  2318. // since the code we're inlining may have undefined behavior (and may
  2319. // never actually execute at runtime); but all
  2320. // @llvm.experimental.deoptimize declarations have to have the same
  2321. // calling convention in a well-formed module.
  2322. auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv();
  2323. NewDeoptIntrinsic->setCallingConv(CallingConv);
  2324. auto *CurBB = RI->getParent();
  2325. RI->eraseFromParent();
  2326. SmallVector<Value *, 4> CallArgs(DeoptCall->args());
  2327. SmallVector<OperandBundleDef, 1> OpBundles;
  2328. DeoptCall->getOperandBundlesAsDefs(OpBundles);
  2329. auto DeoptAttributes = DeoptCall->getAttributes();
  2330. DeoptCall->eraseFromParent();
  2331. assert(!OpBundles.empty() &&
  2332. "Expected at least the deopt operand bundle");
  2333. IRBuilder<> Builder(CurBB);
  2334. CallInst *NewDeoptCall =
  2335. Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles);
  2336. NewDeoptCall->setCallingConv(CallingConv);
  2337. NewDeoptCall->setAttributes(DeoptAttributes);
  2338. if (NewDeoptCall->getType()->isVoidTy())
  2339. Builder.CreateRetVoid();
  2340. else
  2341. Builder.CreateRet(NewDeoptCall);
  2342. }
  2343. // Leave behind the normal returns so we can merge control flow.
  2344. std::swap(Returns, NormalReturns);
  2345. }
  2346. }
  2347. // Handle any inlined musttail call sites. In order for a new call site to be
  2348. // musttail, the source of the clone and the inlined call site must have been
  2349. // musttail. Therefore it's safe to return without merging control into the
  2350. // phi below.
  2351. if (InlinedMustTailCalls) {
  2352. // Check if we need to bitcast the result of any musttail calls.
  2353. Type *NewRetTy = Caller->getReturnType();
  2354. bool NeedBitCast = !CB.use_empty() && CB.getType() != NewRetTy;
  2355. // Handle the returns preceded by musttail calls separately.
  2356. SmallVector<ReturnInst *, 8> NormalReturns;
  2357. for (ReturnInst *RI : Returns) {
  2358. CallInst *ReturnedMustTail =
  2359. RI->getParent()->getTerminatingMustTailCall();
  2360. if (!ReturnedMustTail) {
  2361. NormalReturns.push_back(RI);
  2362. continue;
  2363. }
  2364. if (!NeedBitCast)
  2365. continue;
  2366. // Delete the old return and any preceding bitcast.
  2367. BasicBlock *CurBB = RI->getParent();
  2368. auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
  2369. RI->eraseFromParent();
  2370. if (OldCast)
  2371. OldCast->eraseFromParent();
  2372. // Insert a new bitcast and return with the right type.
  2373. IRBuilder<> Builder(CurBB);
  2374. Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
  2375. }
  2376. // Leave behind the normal returns so we can merge control flow.
  2377. std::swap(Returns, NormalReturns);
  2378. }
  2379. // Now that all of the transforms on the inlined code have taken place but
  2380. // before we splice the inlined code into the CFG and lose track of which
  2381. // blocks were actually inlined, collect the call sites. We only do this if
  2382. // call graph updates weren't requested, as those provide value handle based
  2383. // tracking of inlined call sites instead. Calls to intrinsics are not
  2384. // collected because they are not inlineable.
  2385. if (InlinedFunctionInfo.ContainsCalls && !IFI.CG) {
  2386. // Otherwise just collect the raw call sites that were inlined.
  2387. for (BasicBlock &NewBB :
  2388. make_range(FirstNewBlock->getIterator(), Caller->end()))
  2389. for (Instruction &I : NewBB)
  2390. if (auto *CB = dyn_cast<CallBase>(&I))
  2391. if (!(CB->getCalledFunction() &&
  2392. CB->getCalledFunction()->isIntrinsic()))
  2393. IFI.InlinedCallSites.push_back(CB);
  2394. }
  2395. // If we cloned in _exactly one_ basic block, and if that block ends in a
  2396. // return instruction, we splice the body of the inlined callee directly into
  2397. // the calling basic block.
  2398. if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
  2399. // Move all of the instructions right before the call.
  2400. OrigBB->splice(CB.getIterator(), &*FirstNewBlock, FirstNewBlock->begin(),
  2401. FirstNewBlock->end());
  2402. // Remove the cloned basic block.
  2403. Caller->back().eraseFromParent();
  2404. // If the call site was an invoke instruction, add a branch to the normal
  2405. // destination.
  2406. if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
  2407. BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), &CB);
  2408. NewBr->setDebugLoc(Returns[0]->getDebugLoc());
  2409. }
  2410. // If the return instruction returned a value, replace uses of the call with
  2411. // uses of the returned value.
  2412. if (!CB.use_empty()) {
  2413. ReturnInst *R = Returns[0];
  2414. if (&CB == R->getReturnValue())
  2415. CB.replaceAllUsesWith(UndefValue::get(CB.getType()));
  2416. else
  2417. CB.replaceAllUsesWith(R->getReturnValue());
  2418. }
  2419. // Since we are now done with the Call/Invoke, we can delete it.
  2420. CB.eraseFromParent();
  2421. // Since we are now done with the return instruction, delete it also.
  2422. Returns[0]->eraseFromParent();
  2423. if (MergeAttributes)
  2424. AttributeFuncs::mergeAttributesForInlining(*Caller, *CalledFunc);
  2425. // We are now done with the inlining.
  2426. return InlineResult::success();
  2427. }
  2428. // Otherwise, we have the normal case, of more than one block to inline or
  2429. // multiple return sites.
  2430. // We want to clone the entire callee function into the hole between the
  2431. // "starter" and "ender" blocks. How we accomplish this depends on whether
  2432. // this is an invoke instruction or a call instruction.
  2433. BasicBlock *AfterCallBB;
  2434. BranchInst *CreatedBranchToNormalDest = nullptr;
  2435. if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
  2436. // Add an unconditional branch to make this look like the CallInst case...
  2437. CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), &CB);
  2438. // Split the basic block. This guarantees that no PHI nodes will have to be
  2439. // updated due to new incoming edges, and make the invoke case more
  2440. // symmetric to the call case.
  2441. AfterCallBB =
  2442. OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
  2443. CalledFunc->getName() + ".exit");
  2444. } else { // It's a call
  2445. // If this is a call instruction, we need to split the basic block that
  2446. // the call lives in.
  2447. //
  2448. AfterCallBB = OrigBB->splitBasicBlock(CB.getIterator(),
  2449. CalledFunc->getName() + ".exit");
  2450. }
  2451. if (IFI.CallerBFI) {
  2452. // Copy original BB's block frequency to AfterCallBB
  2453. IFI.CallerBFI->setBlockFreq(
  2454. AfterCallBB, IFI.CallerBFI->getBlockFreq(OrigBB).getFrequency());
  2455. }
  2456. // Change the branch that used to go to AfterCallBB to branch to the first
  2457. // basic block of the inlined function.
  2458. //
  2459. Instruction *Br = OrigBB->getTerminator();
  2460. assert(Br && Br->getOpcode() == Instruction::Br &&
  2461. "splitBasicBlock broken!");
  2462. Br->setOperand(0, &*FirstNewBlock);
  2463. // Now that the function is correct, make it a little bit nicer. In
  2464. // particular, move the basic blocks inserted from the end of the function
  2465. // into the space made by splitting the source basic block.
  2466. Caller->splice(AfterCallBB->getIterator(), Caller, FirstNewBlock,
  2467. Caller->end());
  2468. // Handle all of the return instructions that we just cloned in, and eliminate
  2469. // any users of the original call/invoke instruction.
  2470. Type *RTy = CalledFunc->getReturnType();
  2471. PHINode *PHI = nullptr;
  2472. if (Returns.size() > 1) {
  2473. // The PHI node should go at the front of the new basic block to merge all
  2474. // possible incoming values.
  2475. if (!CB.use_empty()) {
  2476. PHI = PHINode::Create(RTy, Returns.size(), CB.getName(),
  2477. &AfterCallBB->front());
  2478. // Anything that used the result of the function call should now use the
  2479. // PHI node as their operand.
  2480. CB.replaceAllUsesWith(PHI);
  2481. }
  2482. // Loop over all of the return instructions adding entries to the PHI node
  2483. // as appropriate.
  2484. if (PHI) {
  2485. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  2486. ReturnInst *RI = Returns[i];
  2487. assert(RI->getReturnValue()->getType() == PHI->getType() &&
  2488. "Ret value not consistent in function!");
  2489. PHI->addIncoming(RI->getReturnValue(), RI->getParent());
  2490. }
  2491. }
  2492. // Add a branch to the merge points and remove return instructions.
  2493. DebugLoc Loc;
  2494. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  2495. ReturnInst *RI = Returns[i];
  2496. BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
  2497. Loc = RI->getDebugLoc();
  2498. BI->setDebugLoc(Loc);
  2499. RI->eraseFromParent();
  2500. }
  2501. // We need to set the debug location to *somewhere* inside the
  2502. // inlined function. The line number may be nonsensical, but the
  2503. // instruction will at least be associated with the right
  2504. // function.
  2505. if (CreatedBranchToNormalDest)
  2506. CreatedBranchToNormalDest->setDebugLoc(Loc);
  2507. } else if (!Returns.empty()) {
  2508. // Otherwise, if there is exactly one return value, just replace anything
  2509. // using the return value of the call with the computed value.
  2510. if (!CB.use_empty()) {
  2511. if (&CB == Returns[0]->getReturnValue())
  2512. CB.replaceAllUsesWith(UndefValue::get(CB.getType()));
  2513. else
  2514. CB.replaceAllUsesWith(Returns[0]->getReturnValue());
  2515. }
  2516. // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
  2517. BasicBlock *ReturnBB = Returns[0]->getParent();
  2518. ReturnBB->replaceAllUsesWith(AfterCallBB);
  2519. // Splice the code from the return block into the block that it will return
  2520. // to, which contains the code that was after the call.
  2521. AfterCallBB->splice(AfterCallBB->begin(), ReturnBB);
  2522. if (CreatedBranchToNormalDest)
  2523. CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
  2524. // Delete the return instruction now and empty ReturnBB now.
  2525. Returns[0]->eraseFromParent();
  2526. ReturnBB->eraseFromParent();
  2527. } else if (!CB.use_empty()) {
  2528. // No returns, but something is using the return value of the call. Just
  2529. // nuke the result.
  2530. CB.replaceAllUsesWith(PoisonValue::get(CB.getType()));
  2531. }
  2532. // Since we are now done with the Call/Invoke, we can delete it.
  2533. CB.eraseFromParent();
  2534. // If we inlined any musttail calls and the original return is now
  2535. // unreachable, delete it. It can only contain a bitcast and ret.
  2536. if (InlinedMustTailCalls && pred_empty(AfterCallBB))
  2537. AfterCallBB->eraseFromParent();
  2538. // We should always be able to fold the entry block of the function into the
  2539. // single predecessor of the block...
  2540. assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
  2541. BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
  2542. // Splice the code entry block into calling block, right before the
  2543. // unconditional branch.
  2544. CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
  2545. OrigBB->splice(Br->getIterator(), CalleeEntry);
  2546. // Remove the unconditional branch.
  2547. Br->eraseFromParent();
  2548. // Now we can remove the CalleeEntry block, which is now empty.
  2549. CalleeEntry->eraseFromParent();
  2550. // If we inserted a phi node, check to see if it has a single value (e.g. all
  2551. // the entries are the same or undef). If so, remove the PHI so it doesn't
  2552. // block other optimizations.
  2553. if (PHI) {
  2554. AssumptionCache *AC =
  2555. IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr;
  2556. auto &DL = Caller->getParent()->getDataLayout();
  2557. if (Value *V = simplifyInstruction(PHI, {DL, nullptr, nullptr, AC})) {
  2558. PHI->replaceAllUsesWith(V);
  2559. PHI->eraseFromParent();
  2560. }
  2561. }
  2562. if (MergeAttributes)
  2563. AttributeFuncs::mergeAttributesForInlining(*Caller, *CalledFunc);
  2564. return InlineResult::success();
  2565. }