Inliner.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. //===- Inliner.cpp - Code common to all inliners --------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the mechanics required to implement inlining without
  11. // missing any calls and updating the call graph. The decisions of which calls
  12. // are profitable to inline are implemented elsewhere.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Transforms/IPO/InlinerPass.h"
  16. #include "llvm/ADT/SmallPtrSet.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/Analysis/AliasAnalysis.h"
  19. #include "llvm/Analysis/AssumptionCache.h"
  20. #include "llvm/Analysis/CallGraph.h"
  21. #include "llvm/Analysis/InlineCost.h"
  22. #include "llvm/Analysis/TargetLibraryInfo.h"
  23. #include "llvm/IR/CallSite.h"
  24. #include "llvm/IR/DataLayout.h"
  25. #include "llvm/IR/DiagnosticInfo.h"
  26. #include "llvm/IR/Instructions.h"
  27. #include "llvm/IR/IntrinsicInst.h"
  28. #include "llvm/IR/Module.h"
  29. #include "llvm/Support/CommandLine.h"
  30. #include "llvm/Support/Debug.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include "llvm/Transforms/Utils/Cloning.h"
  33. #include "llvm/Transforms/Utils/Local.h"
  34. using namespace llvm;
  35. #define DEBUG_TYPE "inline"
  36. STATISTIC(NumInlined, "Number of functions inlined");
  37. STATISTIC(NumCallsDeleted, "Number of call sites deleted, not inlined");
  38. STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
  39. STATISTIC(NumMergedAllocas, "Number of allocas merged together");
  40. // This weirdly named statistic tracks the number of times that, when attempting
  41. // to inline a function A into B, we analyze the callers of B in order to see
  42. // if those would be more profitable and blocked inline steps.
  43. STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed");
  44. static cl::opt<int>
  45. InlineLimit("inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
  46. cl::desc("Control the amount of inlining to perform (default = 225)"));
  47. static cl::opt<int>
  48. HintThreshold("inlinehint-threshold", cl::Hidden, cl::init(325),
  49. cl::desc("Threshold for inlining functions with inline hint"));
  50. // We instroduce this threshold to help performance of instrumentation based
  51. // PGO before we actually hook up inliner with analysis passes such as BPI and
  52. // BFI.
  53. static cl::opt<int>
  54. ColdThreshold("inlinecold-threshold", cl::Hidden, cl::init(225),
  55. cl::desc("Threshold for inlining functions with cold attribute"));
  56. // Threshold to use when optsize is specified (and there is no -inline-limit).
  57. const int OptSizeThreshold = 75;
  58. Inliner::Inliner(char &ID)
  59. : CallGraphSCCPass(ID), InlineThreshold(InlineLimit), InsertLifetime(true) {}
  60. Inliner::Inliner(char &ID, int Threshold, bool InsertLifetime)
  61. : CallGraphSCCPass(ID), InlineThreshold(InlineLimit.getNumOccurrences() > 0 ?
  62. InlineLimit : Threshold),
  63. InsertLifetime(InsertLifetime) {}
  64. /// For this class, we declare that we require and preserve the call graph.
  65. /// If the derived class implements this method, it should
  66. /// always explicitly call the implementation here.
  67. void Inliner::getAnalysisUsage(AnalysisUsage &AU) const {
  68. AU.addRequired<AliasAnalysis>();
  69. AU.addRequired<AssumptionCacheTracker>();
  70. CallGraphSCCPass::getAnalysisUsage(AU);
  71. }
  72. typedef DenseMap<ArrayType*, std::vector<AllocaInst*> >
  73. InlinedArrayAllocasTy;
  74. /// \brief If the inlined function had a higher stack protection level than the
  75. /// calling function, then bump up the caller's stack protection level.
  76. static void AdjustCallerSSPLevel(Function *Caller, Function *Callee) {
  77. // If upgrading the SSP attribute, clear out the old SSP Attributes first.
  78. // Having multiple SSP attributes doesn't actually hurt, but it adds useless
  79. // clutter to the IR.
  80. AttrBuilder B;
  81. B.addAttribute(Attribute::StackProtect)
  82. .addAttribute(Attribute::StackProtectStrong)
  83. .addAttribute(Attribute::StackProtectReq);
  84. AttributeSet OldSSPAttr = AttributeSet::get(Caller->getContext(),
  85. AttributeSet::FunctionIndex,
  86. B);
  87. if (Callee->hasFnAttribute(Attribute::SafeStack)) {
  88. Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr);
  89. Caller->addFnAttr(Attribute::SafeStack);
  90. } else if (Callee->hasFnAttribute(Attribute::StackProtectReq) &&
  91. !Caller->hasFnAttribute(Attribute::SafeStack)) {
  92. Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr);
  93. Caller->addFnAttr(Attribute::StackProtectReq);
  94. } else if (Callee->hasFnAttribute(Attribute::StackProtectStrong) &&
  95. !Caller->hasFnAttribute(Attribute::SafeStack) &&
  96. !Caller->hasFnAttribute(Attribute::StackProtectReq)) {
  97. Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr);
  98. Caller->addFnAttr(Attribute::StackProtectStrong);
  99. } else if (Callee->hasFnAttribute(Attribute::StackProtect) &&
  100. !Caller->hasFnAttribute(Attribute::SafeStack) &&
  101. !Caller->hasFnAttribute(Attribute::StackProtectReq) &&
  102. !Caller->hasFnAttribute(Attribute::StackProtectStrong))
  103. Caller->addFnAttr(Attribute::StackProtect);
  104. }
  105. /// If it is possible to inline the specified call site,
  106. /// do so and update the CallGraph for this operation.
  107. ///
  108. /// This function also does some basic book-keeping to update the IR. The
  109. /// InlinedArrayAllocas map keeps track of any allocas that are already
  110. /// available from other functions inlined into the caller. If we are able to
  111. /// inline this call site we attempt to reuse already available allocas or add
  112. /// any new allocas to the set if not possible.
  113. static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI,
  114. InlinedArrayAllocasTy &InlinedArrayAllocas,
  115. int InlineHistory, bool InsertLifetime) {
  116. Function *Callee = CS.getCalledFunction();
  117. Function *Caller = CS.getCaller();
  118. // Try to inline the function. Get the list of static allocas that were
  119. // inlined.
  120. if (!InlineFunction(CS, IFI, InsertLifetime))
  121. return false;
  122. AdjustCallerSSPLevel(Caller, Callee);
  123. // Look at all of the allocas that we inlined through this call site. If we
  124. // have already inlined other allocas through other calls into this function,
  125. // then we know that they have disjoint lifetimes and that we can merge them.
  126. //
  127. // There are many heuristics possible for merging these allocas, and the
  128. // different options have different tradeoffs. One thing that we *really*
  129. // don't want to hurt is SRoA: once inlining happens, often allocas are no
  130. // longer address taken and so they can be promoted.
  131. //
  132. // Our "solution" for that is to only merge allocas whose outermost type is an
  133. // array type. These are usually not promoted because someone is using a
  134. // variable index into them. These are also often the most important ones to
  135. // merge.
  136. //
  137. // A better solution would be to have real memory lifetime markers in the IR
  138. // and not have the inliner do any merging of allocas at all. This would
  139. // allow the backend to do proper stack slot coloring of all allocas that
  140. // *actually make it to the backend*, which is really what we want.
  141. //
  142. // Because we don't have this information, we do this simple and useful hack.
  143. //
  144. SmallPtrSet<AllocaInst*, 16> UsedAllocas;
  145. // When processing our SCC, check to see if CS was inlined from some other
  146. // call site. For example, if we're processing "A" in this code:
  147. // A() { B() }
  148. // B() { x = alloca ... C() }
  149. // C() { y = alloca ... }
  150. // Assume that C was not inlined into B initially, and so we're processing A
  151. // and decide to inline B into A. Doing this makes an alloca available for
  152. // reuse and makes a callsite (C) available for inlining. When we process
  153. // the C call site we don't want to do any alloca merging between X and Y
  154. // because their scopes are not disjoint. We could make this smarter by
  155. // keeping track of the inline history for each alloca in the
  156. // InlinedArrayAllocas but this isn't likely to be a significant win.
  157. if (InlineHistory != -1) // Only do merging for top-level call sites in SCC.
  158. return true;
  159. // Loop over all the allocas we have so far and see if they can be merged with
  160. // a previously inlined alloca. If not, remember that we had it.
  161. for (unsigned AllocaNo = 0, e = IFI.StaticAllocas.size();
  162. AllocaNo != e; ++AllocaNo) {
  163. AllocaInst *AI = IFI.StaticAllocas[AllocaNo];
  164. // Don't bother trying to merge array allocations (they will usually be
  165. // canonicalized to be an allocation *of* an array), or allocations whose
  166. // type is not itself an array (because we're afraid of pessimizing SRoA).
  167. ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType());
  168. if (!ATy || AI->isArrayAllocation())
  169. continue;
  170. // Get the list of all available allocas for this array type.
  171. std::vector<AllocaInst*> &AllocasForType = InlinedArrayAllocas[ATy];
  172. // Loop over the allocas in AllocasForType to see if we can reuse one. Note
  173. // that we have to be careful not to reuse the same "available" alloca for
  174. // multiple different allocas that we just inlined, we use the 'UsedAllocas'
  175. // set to keep track of which "available" allocas are being used by this
  176. // function. Also, AllocasForType can be empty of course!
  177. bool MergedAwayAlloca = false;
  178. for (AllocaInst *AvailableAlloca : AllocasForType) {
  179. unsigned Align1 = AI->getAlignment(),
  180. Align2 = AvailableAlloca->getAlignment();
  181. // The available alloca has to be in the right function, not in some other
  182. // function in this SCC.
  183. if (AvailableAlloca->getParent() != AI->getParent())
  184. continue;
  185. // If the inlined function already uses this alloca then we can't reuse
  186. // it.
  187. if (!UsedAllocas.insert(AvailableAlloca).second)
  188. continue;
  189. // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare
  190. // success!
  191. DEBUG(dbgs() << " ***MERGED ALLOCA: " << *AI << "\n\t\tINTO: "
  192. << *AvailableAlloca << '\n');
  193. AI->replaceAllUsesWith(AvailableAlloca);
  194. if (Align1 != Align2) {
  195. if (!Align1 || !Align2) {
  196. const DataLayout &DL = Caller->getParent()->getDataLayout();
  197. unsigned TypeAlign = DL.getABITypeAlignment(AI->getAllocatedType());
  198. Align1 = Align1 ? Align1 : TypeAlign;
  199. Align2 = Align2 ? Align2 : TypeAlign;
  200. }
  201. if (Align1 > Align2)
  202. AvailableAlloca->setAlignment(AI->getAlignment());
  203. }
  204. AI->eraseFromParent();
  205. MergedAwayAlloca = true;
  206. ++NumMergedAllocas;
  207. IFI.StaticAllocas[AllocaNo] = nullptr;
  208. break;
  209. }
  210. // If we already nuked the alloca, we're done with it.
  211. if (MergedAwayAlloca)
  212. continue;
  213. // If we were unable to merge away the alloca either because there are no
  214. // allocas of the right type available or because we reused them all
  215. // already, remember that this alloca came from an inlined function and mark
  216. // it used so we don't reuse it for other allocas from this inline
  217. // operation.
  218. AllocasForType.push_back(AI);
  219. UsedAllocas.insert(AI);
  220. }
  221. return true;
  222. }
  223. unsigned Inliner::getInlineThreshold(CallSite CS) const {
  224. int thres = InlineThreshold; // -inline-threshold or else selected by
  225. // overall opt level
  226. // If -inline-threshold is not given, listen to the optsize attribute when it
  227. // would decrease the threshold.
  228. Function *Caller = CS.getCaller();
  229. bool OptSize = Caller && !Caller->isDeclaration() &&
  230. Caller->hasFnAttribute(Attribute::OptimizeForSize);
  231. if (!(InlineLimit.getNumOccurrences() > 0) && OptSize &&
  232. OptSizeThreshold < thres)
  233. thres = OptSizeThreshold;
  234. // Listen to the inlinehint attribute when it would increase the threshold
  235. // and the caller does not need to minimize its size.
  236. Function *Callee = CS.getCalledFunction();
  237. bool InlineHint = Callee && !Callee->isDeclaration() &&
  238. Callee->hasFnAttribute(Attribute::InlineHint);
  239. if (InlineHint && HintThreshold > thres &&
  240. !Caller->hasFnAttribute(Attribute::MinSize))
  241. thres = HintThreshold;
  242. // Listen to the cold attribute when it would decrease the threshold.
  243. bool ColdCallee = Callee && !Callee->isDeclaration() &&
  244. Callee->hasFnAttribute(Attribute::Cold);
  245. // Command line argument for InlineLimit will override the default
  246. // ColdThreshold. If we have -inline-threshold but no -inlinecold-threshold,
  247. // do not use the default cold threshold even if it is smaller.
  248. if ((InlineLimit.getNumOccurrences() == 0 ||
  249. ColdThreshold.getNumOccurrences() > 0) && ColdCallee &&
  250. ColdThreshold < thres)
  251. thres = ColdThreshold;
  252. return thres;
  253. }
  254. static void emitAnalysis(CallSite CS, const Twine &Msg) {
  255. Function *Caller = CS.getCaller();
  256. LLVMContext &Ctx = Caller->getContext();
  257. DebugLoc DLoc = CS.getInstruction()->getDebugLoc();
  258. emitOptimizationRemarkAnalysis(Ctx, DEBUG_TYPE, *Caller, DLoc, Msg);
  259. }
  260. /// Return true if the inliner should attempt to inline at the given CallSite.
  261. bool Inliner::shouldInline(CallSite CS) {
  262. InlineCost IC = getInlineCost(CS);
  263. if (IC.isAlways()) {
  264. DEBUG(dbgs() << " Inlining: cost=always"
  265. << ", Call: " << *CS.getInstruction() << "\n");
  266. emitAnalysis(CS, Twine(CS.getCalledFunction()->getName()) +
  267. " should always be inlined (cost=always)");
  268. return true;
  269. }
  270. if (IC.isNever()) {
  271. DEBUG(dbgs() << " NOT Inlining: cost=never"
  272. << ", Call: " << *CS.getInstruction() << "\n");
  273. emitAnalysis(CS, Twine(CS.getCalledFunction()->getName() +
  274. " should never be inlined (cost=never)"));
  275. return false;
  276. }
  277. Function *Caller = CS.getCaller();
  278. if (!IC) {
  279. DEBUG(dbgs() << " NOT Inlining: cost=" << IC.getCost()
  280. << ", thres=" << (IC.getCostDelta() + IC.getCost())
  281. << ", Call: " << *CS.getInstruction() << "\n");
  282. emitAnalysis(CS, Twine(CS.getCalledFunction()->getName() +
  283. " too costly to inline (cost=") +
  284. Twine(IC.getCost()) + ", threshold=" +
  285. Twine(IC.getCostDelta() + IC.getCost()) + ")");
  286. return false;
  287. }
  288. // Try to detect the case where the current inlining candidate caller (call
  289. // it B) is a static or linkonce-ODR function and is an inlining candidate
  290. // elsewhere, and the current candidate callee (call it C) is large enough
  291. // that inlining it into B would make B too big to inline later. In these
  292. // circumstances it may be best not to inline C into B, but to inline B into
  293. // its callers.
  294. //
  295. // This only applies to static and linkonce-ODR functions because those are
  296. // expected to be available for inlining in the translation units where they
  297. // are used. Thus we will always have the opportunity to make local inlining
  298. // decisions. Importantly the linkonce-ODR linkage covers inline functions
  299. // and templates in C++.
  300. //
  301. // FIXME: All of this logic should be sunk into getInlineCost. It relies on
  302. // the internal implementation of the inline cost metrics rather than
  303. // treating them as truly abstract units etc.
  304. if (Caller->hasLocalLinkage() || Caller->hasLinkOnceODRLinkage()) {
  305. int TotalSecondaryCost = 0;
  306. // The candidate cost to be imposed upon the current function.
  307. int CandidateCost = IC.getCost() - (InlineConstants::CallPenalty + 1);
  308. // This bool tracks what happens if we do NOT inline C into B.
  309. bool callerWillBeRemoved = Caller->hasLocalLinkage();
  310. // This bool tracks what happens if we DO inline C into B.
  311. bool inliningPreventsSomeOuterInline = false;
  312. for (User *U : Caller->users()) {
  313. CallSite CS2(U);
  314. // If this isn't a call to Caller (it could be some other sort
  315. // of reference) skip it. Such references will prevent the caller
  316. // from being removed.
  317. if (!CS2 || CS2.getCalledFunction() != Caller) {
  318. callerWillBeRemoved = false;
  319. continue;
  320. }
  321. InlineCost IC2 = getInlineCost(CS2);
  322. ++NumCallerCallersAnalyzed;
  323. if (!IC2) {
  324. callerWillBeRemoved = false;
  325. continue;
  326. }
  327. if (IC2.isAlways())
  328. continue;
  329. // See if inlining or original callsite would erase the cost delta of
  330. // this callsite. We subtract off the penalty for the call instruction,
  331. // which we would be deleting.
  332. if (IC2.getCostDelta() <= CandidateCost) {
  333. inliningPreventsSomeOuterInline = true;
  334. TotalSecondaryCost += IC2.getCost();
  335. }
  336. }
  337. // If all outer calls to Caller would get inlined, the cost for the last
  338. // one is set very low by getInlineCost, in anticipation that Caller will
  339. // be removed entirely. We did not account for this above unless there
  340. // is only one caller of Caller.
  341. if (callerWillBeRemoved && !Caller->use_empty())
  342. TotalSecondaryCost += InlineConstants::LastCallToStaticBonus;
  343. if (inliningPreventsSomeOuterInline && TotalSecondaryCost < IC.getCost()) {
  344. DEBUG(dbgs() << " NOT Inlining: " << *CS.getInstruction() <<
  345. " Cost = " << IC.getCost() <<
  346. ", outer Cost = " << TotalSecondaryCost << '\n');
  347. emitAnalysis(
  348. CS, Twine("Not inlining. Cost of inlining " +
  349. CS.getCalledFunction()->getName() +
  350. " increases the cost of inlining " +
  351. CS.getCaller()->getName() + " in other contexts"));
  352. return false;
  353. }
  354. }
  355. DEBUG(dbgs() << " Inlining: cost=" << IC.getCost()
  356. << ", thres=" << (IC.getCostDelta() + IC.getCost())
  357. << ", Call: " << *CS.getInstruction() << '\n');
  358. emitAnalysis(
  359. CS, CS.getCalledFunction()->getName() + Twine(" can be inlined into ") +
  360. CS.getCaller()->getName() + " with cost=" + Twine(IC.getCost()) +
  361. " (threshold=" + Twine(IC.getCostDelta() + IC.getCost()) + ")");
  362. return true;
  363. }
  364. /// Return true if the specified inline history ID
  365. /// indicates an inline history that includes the specified function.
  366. static bool InlineHistoryIncludes(Function *F, int InlineHistoryID,
  367. const SmallVectorImpl<std::pair<Function*, int> > &InlineHistory) {
  368. while (InlineHistoryID != -1) {
  369. assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
  370. "Invalid inline history ID");
  371. if (InlineHistory[InlineHistoryID].first == F)
  372. return true;
  373. InlineHistoryID = InlineHistory[InlineHistoryID].second;
  374. }
  375. return false;
  376. }
  377. bool Inliner::runOnSCC(CallGraphSCC &SCC) {
  378. CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
  379. AssumptionCacheTracker *ACT = &getAnalysis<AssumptionCacheTracker>();
  380. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  381. const TargetLibraryInfo *TLI = TLIP ? &TLIP->getTLI() : nullptr;
  382. AliasAnalysis *AA = &getAnalysis<AliasAnalysis>();
  383. SmallPtrSet<Function*, 8> SCCFunctions;
  384. DEBUG(dbgs() << "Inliner visiting SCC:");
  385. for (CallGraphNode *Node : SCC) {
  386. Function *F = Node->getFunction();
  387. if (F) SCCFunctions.insert(F);
  388. DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
  389. }
  390. // Scan through and identify all call sites ahead of time so that we only
  391. // inline call sites in the original functions, not call sites that result
  392. // from inlining other functions.
  393. SmallVector<std::pair<CallSite, int>, 16> CallSites;
  394. // When inlining a callee produces new call sites, we want to keep track of
  395. // the fact that they were inlined from the callee. This allows us to avoid
  396. // infinite inlining in some obscure cases. To represent this, we use an
  397. // index into the InlineHistory vector.
  398. SmallVector<std::pair<Function*, int>, 8> InlineHistory;
  399. for (CallGraphNode *Node : SCC) {
  400. Function *F = Node->getFunction();
  401. if (!F) continue;
  402. for (BasicBlock &BB : *F)
  403. for (Instruction &I : BB) {
  404. CallSite CS(cast<Value>(&I));
  405. // If this isn't a call, or it is a call to an intrinsic, it can
  406. // never be inlined.
  407. if (!CS || isa<IntrinsicInst>(I))
  408. continue;
  409. // If this is a direct call to an external function, we can never inline
  410. // it. If it is an indirect call, inlining may resolve it to be a
  411. // direct call, so we keep it.
  412. if (CS.getCalledFunction() && CS.getCalledFunction()->isDeclaration())
  413. continue;
  414. CallSites.push_back(std::make_pair(CS, -1));
  415. }
  416. }
  417. DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
  418. // If there are no calls in this function, exit early.
  419. if (CallSites.empty())
  420. return false;
  421. // Now that we have all of the call sites, move the ones to functions in the
  422. // current SCC to the end of the list.
  423. unsigned FirstCallInSCC = CallSites.size();
  424. for (unsigned i = 0; i < FirstCallInSCC; ++i)
  425. if (Function *F = CallSites[i].first.getCalledFunction())
  426. if (SCCFunctions.count(F))
  427. std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
  428. InlinedArrayAllocasTy InlinedArrayAllocas;
  429. InlineFunctionInfo InlineInfo(&CG, AA, ACT);
  430. // Now that we have all of the call sites, loop over them and inline them if
  431. // it looks profitable to do so.
  432. bool Changed = false;
  433. bool LocalChange;
  434. do {
  435. LocalChange = false;
  436. // Iterate over the outer loop because inlining functions can cause indirect
  437. // calls to become direct calls.
  438. // CallSites may be modified inside so ranged for loop can not be used.
  439. for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
  440. CallSite CS = CallSites[CSi].first;
  441. Function *Caller = CS.getCaller();
  442. Function *Callee = CS.getCalledFunction();
  443. // If this call site is dead and it is to a readonly function, we should
  444. // just delete the call instead of trying to inline it, regardless of
  445. // size. This happens because IPSCCP propagates the result out of the
  446. // call and then we're left with the dead call.
  447. if (isInstructionTriviallyDead(CS.getInstruction(), TLI)) {
  448. DEBUG(dbgs() << " -> Deleting dead call: "
  449. << *CS.getInstruction() << "\n");
  450. // Update the call graph by deleting the edge from Callee to Caller.
  451. CG[Caller]->removeCallEdgeFor(CS);
  452. CS.getInstruction()->eraseFromParent();
  453. ++NumCallsDeleted;
  454. } else {
  455. // We can only inline direct calls to non-declarations.
  456. if (!Callee || Callee->isDeclaration()) continue;
  457. // If this call site was obtained by inlining another function, verify
  458. // that the include path for the function did not include the callee
  459. // itself. If so, we'd be recursively inlining the same function,
  460. // which would provide the same callsites, which would cause us to
  461. // infinitely inline.
  462. int InlineHistoryID = CallSites[CSi].second;
  463. if (InlineHistoryID != -1 &&
  464. InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory))
  465. continue;
  466. LLVMContext &CallerCtx = Caller->getContext();
  467. // Get DebugLoc to report. CS will be invalid after Inliner.
  468. DebugLoc DLoc = CS.getInstruction()->getDebugLoc();
  469. // If the policy determines that we should inline this function,
  470. // try to do so.
  471. if (!shouldInline(CS)) {
  472. emitOptimizationRemarkMissed(CallerCtx, DEBUG_TYPE, *Caller, DLoc,
  473. Twine(Callee->getName() +
  474. " will not be inlined into " +
  475. Caller->getName()));
  476. continue;
  477. }
  478. // Attempt to inline the function.
  479. if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas,
  480. InlineHistoryID, InsertLifetime)) {
  481. emitOptimizationRemarkMissed(CallerCtx, DEBUG_TYPE, *Caller, DLoc,
  482. Twine(Callee->getName() +
  483. " will not be inlined into " +
  484. Caller->getName()));
  485. continue;
  486. }
  487. ++NumInlined;
  488. // Report the inline decision.
  489. emitOptimizationRemark(
  490. CallerCtx, DEBUG_TYPE, *Caller, DLoc,
  491. Twine(Callee->getName() + " inlined into " + Caller->getName()));
  492. // If inlining this function gave us any new call sites, throw them
  493. // onto our worklist to process. They are useful inline candidates.
  494. if (!InlineInfo.InlinedCalls.empty()) {
  495. // Create a new inline history entry for this, so that we remember
  496. // that these new callsites came about due to inlining Callee.
  497. int NewHistoryID = InlineHistory.size();
  498. InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
  499. for (Value *Ptr : InlineInfo.InlinedCalls)
  500. CallSites.push_back(std::make_pair(CallSite(Ptr), NewHistoryID));
  501. }
  502. }
  503. // If we inlined or deleted the last possible call site to the function,
  504. // delete the function body now.
  505. if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
  506. // TODO: Can remove if in SCC now.
  507. !SCCFunctions.count(Callee) &&
  508. // The function may be apparently dead, but if there are indirect
  509. // callgraph references to the node, we cannot delete it yet, this
  510. // could invalidate the CGSCC iterator.
  511. CG[Callee]->getNumReferences() == 0) {
  512. DEBUG(dbgs() << " -> Deleting dead function: "
  513. << Callee->getName() << "\n");
  514. CallGraphNode *CalleeNode = CG[Callee];
  515. // Remove any call graph edges from the callee to its callees.
  516. CalleeNode->removeAllCalledFunctions();
  517. // Removing the node for callee from the call graph and delete it.
  518. delete CG.removeFunctionFromModule(CalleeNode);
  519. ++NumDeleted;
  520. }
  521. // Remove this call site from the list. If possible, use
  522. // swap/pop_back for efficiency, but do not use it if doing so would
  523. // move a call site to a function in this SCC before the
  524. // 'FirstCallInSCC' barrier.
  525. if (SCC.isSingular()) {
  526. CallSites[CSi] = CallSites.back();
  527. CallSites.pop_back();
  528. } else {
  529. CallSites.erase(CallSites.begin()+CSi);
  530. }
  531. --CSi;
  532. Changed = true;
  533. LocalChange = true;
  534. }
  535. } while (LocalChange);
  536. return Changed;
  537. }
  538. /// Remove now-dead linkonce functions at the end of
  539. /// processing to avoid breaking the SCC traversal.
  540. bool Inliner::doFinalization(CallGraph &CG) {
  541. return removeDeadFunctions(CG);
  542. }
  543. /// Remove dead functions that are not included in DNR (Do Not Remove) list.
  544. bool Inliner::removeDeadFunctions(CallGraph &CG, bool AlwaysInlineOnly) {
  545. SmallVector<CallGraphNode*, 16> FunctionsToRemove;
  546. SmallVector<CallGraphNode *, 16> DeadFunctionsInComdats;
  547. SmallDenseMap<const Comdat *, int, 16> ComdatEntriesAlive;
  548. auto RemoveCGN = [&](CallGraphNode *CGN) {
  549. // Remove any call graph edges from the function to its callees.
  550. CGN->removeAllCalledFunctions();
  551. // Remove any edges from the external node to the function's call graph
  552. // node. These edges might have been made irrelegant due to
  553. // optimization of the program.
  554. CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
  555. // Removing the node for callee from the call graph and delete it.
  556. FunctionsToRemove.push_back(CGN);
  557. };
  558. // Scan for all of the functions, looking for ones that should now be removed
  559. // from the program. Insert the dead ones in the FunctionsToRemove set.
  560. for (auto I : CG) {
  561. CallGraphNode *CGN = I.second;
  562. Function *F = CGN->getFunction();
  563. if (!F || F->isDeclaration())
  564. continue;
  565. // Handle the case when this function is called and we only want to care
  566. // about always-inline functions. This is a bit of a hack to share code
  567. // between here and the InlineAlways pass.
  568. if (AlwaysInlineOnly && !F->hasFnAttribute(Attribute::AlwaysInline))
  569. continue;
  570. // If the only remaining users of the function are dead constants, remove
  571. // them.
  572. F->removeDeadConstantUsers();
  573. if (!F->isDefTriviallyDead())
  574. continue;
  575. // It is unsafe to drop a function with discardable linkage from a COMDAT
  576. // without also dropping the other members of the COMDAT.
  577. // The inliner doesn't visit non-function entities which are in COMDAT
  578. // groups so it is unsafe to do so *unless* the linkage is local.
  579. if (!F->hasLocalLinkage()) {
  580. if (const Comdat *C = F->getComdat()) {
  581. --ComdatEntriesAlive[C];
  582. DeadFunctionsInComdats.push_back(CGN);
  583. continue;
  584. }
  585. }
  586. RemoveCGN(CGN);
  587. }
  588. if (!DeadFunctionsInComdats.empty()) {
  589. // Count up all the entities in COMDAT groups
  590. auto ComdatGroupReferenced = [&](const Comdat *C) {
  591. auto I = ComdatEntriesAlive.find(C);
  592. if (I != ComdatEntriesAlive.end())
  593. ++(I->getSecond());
  594. };
  595. for (const Function &F : CG.getModule())
  596. if (const Comdat *C = F.getComdat())
  597. ComdatGroupReferenced(C);
  598. for (const GlobalVariable &GV : CG.getModule().globals())
  599. if (const Comdat *C = GV.getComdat())
  600. ComdatGroupReferenced(C);
  601. for (const GlobalAlias &GA : CG.getModule().aliases())
  602. if (const Comdat *C = GA.getComdat())
  603. ComdatGroupReferenced(C);
  604. for (CallGraphNode *CGN : DeadFunctionsInComdats) {
  605. Function *F = CGN->getFunction();
  606. const Comdat *C = F->getComdat();
  607. int NumAlive = ComdatEntriesAlive[C];
  608. // We can remove functions in a COMDAT group if the entire group is dead.
  609. assert(NumAlive >= 0);
  610. if (NumAlive > 0)
  611. continue;
  612. RemoveCGN(CGN);
  613. }
  614. }
  615. if (FunctionsToRemove.empty())
  616. return false;
  617. // Now that we know which functions to delete, do so. We didn't want to do
  618. // this inline, because that would invalidate our CallGraph::iterator
  619. // objects. :(
  620. //
  621. // Note that it doesn't matter that we are iterating over a non-stable order
  622. // here to do this, it doesn't matter which order the functions are deleted
  623. // in.
  624. array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end());
  625. FunctionsToRemove.erase(std::unique(FunctionsToRemove.begin(),
  626. FunctionsToRemove.end()),
  627. FunctionsToRemove.end());
  628. for (CallGraphNode *CGN : FunctionsToRemove) {
  629. delete CG.removeFunctionFromModule(CGN);
  630. ++NumDeleted;
  631. }
  632. return true;
  633. }