Inliner.cpp 31 KB

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