Inliner.cpp 31 KB

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