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