1//===- InlineFunction.cpp - Code to perform function inlining -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements inlining of a function into a call site, resolving
10// parameters and the return value as appropriate.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SetVector.h"
17#include "llvm/ADT/SmallPtrSet.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/iterator_range.h"
21#include "llvm/Analysis/AliasAnalysis.h"
22#include "llvm/Analysis/AssumptionCache.h"
23#include "llvm/Analysis/BlockFrequencyInfo.h"
24#include "llvm/Analysis/CallGraph.h"
25#include "llvm/Analysis/CaptureTracking.h"
26#include "llvm/Analysis/CtxProfAnalysis.h"
27#include "llvm/Analysis/IndirectCallVisitor.h"
28#include "llvm/Analysis/InstructionSimplify.h"
29#include "llvm/Analysis/MemoryProfileInfo.h"
30#include "llvm/Analysis/ObjCARCAnalysisUtils.h"
31#include "llvm/Analysis/ObjCARCUtil.h"
32#include "llvm/Analysis/ProfileSummaryInfo.h"
33#include "llvm/Analysis/ValueTracking.h"
34#include "llvm/Analysis/VectorUtils.h"
35#include "llvm/IR/Argument.h"
36#include "llvm/IR/AttributeMask.h"
37#include "llvm/IR/Attributes.h"
38#include "llvm/IR/BasicBlock.h"
39#include "llvm/IR/CFG.h"
40#include "llvm/IR/Constant.h"
41#include "llvm/IR/ConstantRange.h"
42#include "llvm/IR/Constants.h"
43#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/DebugInfo.h"
45#include "llvm/IR/DebugInfoMetadata.h"
46#include "llvm/IR/DebugLoc.h"
47#include "llvm/IR/DerivedTypes.h"
48#include "llvm/IR/Dominators.h"
49#include "llvm/IR/EHPersonalities.h"
50#include "llvm/IR/Function.h"
51#include "llvm/IR/GlobalVariable.h"
52#include "llvm/IR/IRBuilder.h"
53#include "llvm/IR/InlineAsm.h"
54#include "llvm/IR/InstrTypes.h"
55#include "llvm/IR/Instruction.h"
56#include "llvm/IR/Instructions.h"
57#include "llvm/IR/IntrinsicInst.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/LLVMContext.h"
60#include "llvm/IR/MDBuilder.h"
61#include "llvm/IR/Metadata.h"
62#include "llvm/IR/Module.h"
63#include "llvm/IR/PatternMatch.h"
64#include "llvm/IR/ProfDataUtils.h"
65#include "llvm/IR/Type.h"
66#include "llvm/IR/User.h"
67#include "llvm/IR/Value.h"
68#include "llvm/Support/Casting.h"
69#include "llvm/Support/CommandLine.h"
70#include "llvm/Support/ErrorHandling.h"
71#include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
72#include "llvm/Transforms/Utils/Cloning.h"
73#include "llvm/Transforms/Utils/Local.h"
74#include "llvm/Transforms/Utils/ValueMapper.h"
75#include <algorithm>
76#include <cassert>
77#include <cstdint>
78#include <deque>
79#include <iterator>
80#include <optional>
81#include <string>
82#include <utility>
83#include <vector>
84
85#define DEBUG_TYPE "inline-function"
86
87using namespace llvm;
88using namespace llvm::memprof;
89
90static cl::opt<bool>
91EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(Val: true),
92 cl::Hidden,
93 cl::desc("Convert noalias attributes to metadata during inlining."));
94
95static cl::opt<bool>
96 UseNoAliasIntrinsic("use-noalias-intrinsic-during-inlining", cl::Hidden,
97 cl::init(Val: true),
98 cl::desc("Use the llvm.experimental.noalias.scope.decl "
99 "intrinsic during inlining."));
100
101// Disabled by default, because the added alignment assumptions may increase
102// compile-time and block optimizations. This option is not suitable for use
103// with frontends that emit comprehensive parameter alignment annotations.
104static cl::opt<bool>
105PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
106 cl::init(Val: false), cl::Hidden,
107 cl::desc("Convert align attributes to assumptions during inlining."));
108
109static cl::opt<unsigned> InlinerAttributeWindow(
110 "max-inst-checked-for-throw-during-inlining", cl::Hidden,
111 cl::desc("the maximum number of instructions analyzed for may throw during "
112 "attribute inference in inlined body"),
113 cl::init(Val: 4));
114
115namespace {
116
117 /// A class for recording information about inlining a landing pad.
118 class LandingPadInliningInfo {
119 /// Destination of the invoke's unwind.
120 BasicBlock *OuterResumeDest;
121
122 /// Destination for the callee's resume.
123 BasicBlock *InnerResumeDest = nullptr;
124
125 /// LandingPadInst associated with the invoke.
126 LandingPadInst *CallerLPad = nullptr;
127
128 /// PHI for EH values from landingpad insts.
129 PHINode *InnerEHValuesPHI = nullptr;
130
131 SmallVector<Value*, 8> UnwindDestPHIValues;
132
133 public:
134 LandingPadInliningInfo(InvokeInst *II)
135 : OuterResumeDest(II->getUnwindDest()) {
136 // If there are PHI nodes in the unwind destination block, we need to keep
137 // track of which values came into them from the invoke before removing
138 // the edge from this block.
139 BasicBlock *InvokeBB = II->getParent();
140 BasicBlock::iterator I = OuterResumeDest->begin();
141 for (; isa<PHINode>(Val: I); ++I) {
142 // Save the value to use for this edge.
143 PHINode *PHI = cast<PHINode>(Val&: I);
144 UnwindDestPHIValues.push_back(Elt: PHI->getIncomingValueForBlock(BB: InvokeBB));
145 }
146
147 CallerLPad = cast<LandingPadInst>(Val&: I);
148 }
149
150 /// The outer unwind destination is the target of
151 /// unwind edges introduced for calls within the inlined function.
152 BasicBlock *getOuterResumeDest() const {
153 return OuterResumeDest;
154 }
155
156 BasicBlock *getInnerResumeDest();
157
158 LandingPadInst *getLandingPadInst() const { return CallerLPad; }
159
160 /// Forward the 'resume' instruction to the caller's landing pad block.
161 /// When the landing pad block has only one predecessor, this is
162 /// a simple branch. When there is more than one predecessor, we need to
163 /// split the landing pad block after the landingpad instruction and jump
164 /// to there.
165 void forwardResume(ResumeInst *RI);
166
167 /// Add incoming-PHI values to the unwind destination block for the given
168 /// basic block, using the values for the original invoke's source block.
169 void addIncomingPHIValuesFor(BasicBlock *BB) const {
170 addIncomingPHIValuesForInto(src: BB, dest: OuterResumeDest);
171 }
172
173 void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
174 BasicBlock::iterator I = dest->begin();
175 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
176 PHINode *phi = cast<PHINode>(Val&: I);
177 phi->addIncoming(V: UnwindDestPHIValues[i], BB: src);
178 }
179 }
180 };
181} // end anonymous namespace
182
183static IntrinsicInst *getConvergenceEntry(BasicBlock &BB) {
184 BasicBlock::iterator It = BB.getFirstNonPHIIt();
185 while (It != BB.end()) {
186 if (auto *IntrinsicCall = dyn_cast<ConvergenceControlInst>(Val&: It)) {
187 if (IntrinsicCall->isEntry()) {
188 return IntrinsicCall;
189 }
190 }
191 It = std::next(x: It);
192 }
193 return nullptr;
194}
195
196/// Get or create a target for the branch from ResumeInsts.
197BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
198 if (InnerResumeDest) return InnerResumeDest;
199
200 // Split the landing pad.
201 BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
202 InnerResumeDest =
203 OuterResumeDest->splitBasicBlock(I: SplitPoint,
204 BBName: OuterResumeDest->getName() + ".body");
205
206 // The number of incoming edges we expect to the inner landing pad.
207 const unsigned PHICapacity = 2;
208
209 // Create corresponding new PHIs for all the PHIs in the outer landing pad.
210 BasicBlock::iterator InsertPoint = InnerResumeDest->begin();
211 BasicBlock::iterator I = OuterResumeDest->begin();
212 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
213 PHINode *OuterPHI = cast<PHINode>(Val&: I);
214 PHINode *InnerPHI = PHINode::Create(Ty: OuterPHI->getType(), NumReservedValues: PHICapacity,
215 NameStr: OuterPHI->getName() + ".lpad-body");
216 InnerPHI->insertBefore(InsertPos: InsertPoint);
217 OuterPHI->replaceAllUsesWith(V: InnerPHI);
218 InnerPHI->addIncoming(V: OuterPHI, BB: OuterResumeDest);
219 }
220
221 // Create a PHI for the exception values.
222 InnerEHValuesPHI =
223 PHINode::Create(Ty: CallerLPad->getType(), NumReservedValues: PHICapacity, NameStr: "eh.lpad-body");
224 InnerEHValuesPHI->insertBefore(InsertPos: InsertPoint);
225 CallerLPad->replaceAllUsesWith(V: InnerEHValuesPHI);
226 InnerEHValuesPHI->addIncoming(V: CallerLPad, BB: OuterResumeDest);
227
228 // All done.
229 return InnerResumeDest;
230}
231
232/// Forward the 'resume' instruction to the caller's landing pad block.
233/// When the landing pad block has only one predecessor, this is a simple
234/// branch. When there is more than one predecessor, we need to split the
235/// landing pad block after the landingpad instruction and jump to there.
236void LandingPadInliningInfo::forwardResume(ResumeInst *RI) {
237 BasicBlock *Dest = getInnerResumeDest();
238 BasicBlock *Src = RI->getParent();
239
240 auto *BI = UncondBrInst::Create(Target: Dest, InsertBefore: Src);
241 BI->setDebugLoc(RI->getDebugLoc());
242
243 // Update the PHIs in the destination. They were inserted in an order which
244 // makes this work.
245 addIncomingPHIValuesForInto(src: Src, dest: Dest);
246
247 InnerEHValuesPHI->addIncoming(V: RI->getOperand(i_nocapture: 0), BB: Src);
248 RI->eraseFromParent();
249}
250
251/// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
252static Value *getParentPad(Value *EHPad) {
253 if (auto *FPI = dyn_cast<FuncletPadInst>(Val: EHPad))
254 return FPI->getParentPad();
255 return cast<CatchSwitchInst>(Val: EHPad)->getParentPad();
256}
257
258using UnwindDestMemoTy = DenseMap<Instruction *, Value *>;
259
260/// Helper for getUnwindDestToken that does the descendant-ward part of
261/// the search.
262static Value *getUnwindDestTokenHelper(Instruction *EHPad,
263 UnwindDestMemoTy &MemoMap) {
264 SmallVector<Instruction *, 8> Worklist(1, EHPad);
265
266 while (!Worklist.empty()) {
267 Instruction *CurrentPad = Worklist.pop_back_val();
268 // We only put pads on the worklist that aren't in the MemoMap. When
269 // we find an unwind dest for a pad we may update its ancestors, but
270 // the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
271 // so they should never get updated while queued on the worklist.
272 assert(!MemoMap.count(CurrentPad));
273 Value *UnwindDestToken = nullptr;
274 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Val: CurrentPad)) {
275 if (CatchSwitch->hasUnwindDest()) {
276 UnwindDestToken = &*CatchSwitch->getUnwindDest()->getFirstNonPHIIt();
277 } else {
278 // Catchswitch doesn't have a 'nounwind' variant, and one might be
279 // annotated as "unwinds to caller" when really it's nounwind (see
280 // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
281 // parent's unwind dest from this. We can check its catchpads'
282 // descendants, since they might include a cleanuppad with an
283 // "unwinds to caller" cleanupret, which can be trusted.
284 for (auto HI = CatchSwitch->handler_begin(),
285 HE = CatchSwitch->handler_end();
286 HI != HE && !UnwindDestToken; ++HI) {
287 BasicBlock *HandlerBlock = *HI;
288 auto *CatchPad =
289 cast<CatchPadInst>(Val: &*HandlerBlock->getFirstNonPHIIt());
290 for (User *Child : CatchPad->users()) {
291 // Intentionally ignore invokes here -- since the catchswitch is
292 // marked "unwind to caller", it would be a verifier error if it
293 // contained an invoke which unwinds out of it, so any invoke we'd
294 // encounter must unwind to some child of the catch.
295 if (!isa<CleanupPadInst>(Val: Child) && !isa<CatchSwitchInst>(Val: Child))
296 continue;
297
298 Instruction *ChildPad = cast<Instruction>(Val: Child);
299 auto Memo = MemoMap.find(Val: ChildPad);
300 if (Memo == MemoMap.end()) {
301 // Haven't figured out this child pad yet; queue it.
302 Worklist.push_back(Elt: ChildPad);
303 continue;
304 }
305 // We've already checked this child, but might have found that
306 // it offers no proof either way.
307 Value *ChildUnwindDestToken = Memo->second;
308 if (!ChildUnwindDestToken)
309 continue;
310 // We already know the child's unwind dest, which can either
311 // be ConstantTokenNone to indicate unwind to caller, or can
312 // be another child of the catchpad. Only the former indicates
313 // the unwind dest of the catchswitch.
314 if (isa<ConstantTokenNone>(Val: ChildUnwindDestToken)) {
315 UnwindDestToken = ChildUnwindDestToken;
316 break;
317 }
318 assert(getParentPad(ChildUnwindDestToken) == CatchPad);
319 }
320 }
321 }
322 } else {
323 auto *CleanupPad = cast<CleanupPadInst>(Val: CurrentPad);
324 for (User *U : CleanupPad->users()) {
325 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(Val: U)) {
326 if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
327 UnwindDestToken = &*RetUnwindDest->getFirstNonPHIIt();
328 else
329 UnwindDestToken = ConstantTokenNone::get(Context&: CleanupPad->getContext());
330 break;
331 }
332 Value *ChildUnwindDestToken;
333 if (auto *Invoke = dyn_cast<InvokeInst>(Val: U)) {
334 ChildUnwindDestToken = &*Invoke->getUnwindDest()->getFirstNonPHIIt();
335 } else if (isa<CleanupPadInst>(Val: U) || isa<CatchSwitchInst>(Val: U)) {
336 Instruction *ChildPad = cast<Instruction>(Val: U);
337 auto Memo = MemoMap.find(Val: ChildPad);
338 if (Memo == MemoMap.end()) {
339 // Haven't resolved this child yet; queue it and keep searching.
340 Worklist.push_back(Elt: ChildPad);
341 continue;
342 }
343 // We've checked this child, but still need to ignore it if it
344 // had no proof either way.
345 ChildUnwindDestToken = Memo->second;
346 if (!ChildUnwindDestToken)
347 continue;
348 } else {
349 // Not a relevant user of the cleanuppad
350 continue;
351 }
352 // In a well-formed program, the child/invoke must either unwind to
353 // an(other) child of the cleanup, or exit the cleanup. In the
354 // first case, continue searching.
355 if (isa<Instruction>(Val: ChildUnwindDestToken) &&
356 getParentPad(EHPad: ChildUnwindDestToken) == CleanupPad)
357 continue;
358 UnwindDestToken = ChildUnwindDestToken;
359 break;
360 }
361 }
362 // If we haven't found an unwind dest for CurrentPad, we may have queued its
363 // children, so move on to the next in the worklist.
364 if (!UnwindDestToken)
365 continue;
366
367 // Now we know that CurrentPad unwinds to UnwindDestToken. It also exits
368 // any ancestors of CurrentPad up to but not including UnwindDestToken's
369 // parent pad. Record this in the memo map, and check to see if the
370 // original EHPad being queried is one of the ones exited.
371 Value *UnwindParent;
372 if (auto *UnwindPad = dyn_cast<Instruction>(Val: UnwindDestToken))
373 UnwindParent = getParentPad(EHPad: UnwindPad);
374 else
375 UnwindParent = nullptr;
376 bool ExitedOriginalPad = false;
377 for (Instruction *ExitedPad = CurrentPad;
378 ExitedPad && ExitedPad != UnwindParent;
379 ExitedPad = dyn_cast<Instruction>(Val: getParentPad(EHPad: ExitedPad))) {
380 // Skip over catchpads since they just follow their catchswitches.
381 if (isa<CatchPadInst>(Val: ExitedPad))
382 continue;
383 MemoMap[ExitedPad] = UnwindDestToken;
384 ExitedOriginalPad |= (ExitedPad == EHPad);
385 }
386
387 if (ExitedOriginalPad)
388 return UnwindDestToken;
389
390 // Continue the search.
391 }
392
393 // No definitive information is contained within this funclet.
394 return nullptr;
395}
396
397/// Given an EH pad, find where it unwinds. If it unwinds to an EH pad,
398/// return that pad instruction. If it unwinds to caller, return
399/// ConstantTokenNone. If it does not have a definitive unwind destination,
400/// return nullptr.
401///
402/// This routine gets invoked for calls in funclets in inlinees when inlining
403/// an invoke. Since many funclets don't have calls inside them, it's queried
404/// on-demand rather than building a map of pads to unwind dests up front.
405/// Determining a funclet's unwind dest may require recursively searching its
406/// descendants, and also ancestors and cousins if the descendants don't provide
407/// an answer. Since most funclets will have their unwind dest immediately
408/// available as the unwind dest of a catchswitch or cleanupret, this routine
409/// searches top-down from the given pad and then up. To avoid worst-case
410/// quadratic run-time given that approach, it uses a memo map to avoid
411/// re-processing funclet trees. The callers that rewrite the IR as they go
412/// take advantage of this, for correctness, by checking/forcing rewritten
413/// pads' entries to match the original callee view.
414static Value *getUnwindDestToken(Instruction *EHPad,
415 UnwindDestMemoTy &MemoMap) {
416 // Catchpads unwind to the same place as their catchswitch;
417 // redirct any queries on catchpads so the code below can
418 // deal with just catchswitches and cleanuppads.
419 if (auto *CPI = dyn_cast<CatchPadInst>(Val: EHPad))
420 EHPad = CPI->getCatchSwitch();
421
422 // Check if we've already determined the unwind dest for this pad.
423 auto Memo = MemoMap.find(Val: EHPad);
424 if (Memo != MemoMap.end())
425 return Memo->second;
426
427 // Search EHPad and, if necessary, its descendants.
428 Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
429 assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
430 if (UnwindDestToken)
431 return UnwindDestToken;
432
433 // No information is available for this EHPad from itself or any of its
434 // descendants. An unwind all the way out to a pad in the caller would
435 // need also to agree with the unwind dest of the parent funclet, so
436 // search up the chain to try to find a funclet with information. Put
437 // null entries in the memo map to avoid re-processing as we go up.
438 MemoMap[EHPad] = nullptr;
439#ifndef NDEBUG
440 SmallPtrSet<Instruction *, 4> TempMemos;
441 TempMemos.insert(EHPad);
442#endif
443 Instruction *LastUselessPad = EHPad;
444 Value *AncestorToken;
445 for (AncestorToken = getParentPad(EHPad);
446 auto *AncestorPad = dyn_cast<Instruction>(Val: AncestorToken);
447 AncestorToken = getParentPad(EHPad: AncestorToken)) {
448 // Skip over catchpads since they just follow their catchswitches.
449 if (isa<CatchPadInst>(Val: AncestorPad))
450 continue;
451 // If the MemoMap had an entry mapping AncestorPad to nullptr, since we
452 // haven't yet called getUnwindDestTokenHelper for AncestorPad in this
453 // call to getUnwindDestToken, that would mean that AncestorPad had no
454 // information in itself, its descendants, or its ancestors. If that
455 // were the case, then we should also have recorded the lack of information
456 // for the descendant that we're coming from. So assert that we don't
457 // find a null entry in the MemoMap for AncestorPad.
458 assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
459 auto AncestorMemo = MemoMap.find(Val: AncestorPad);
460 if (AncestorMemo == MemoMap.end()) {
461 UnwindDestToken = getUnwindDestTokenHelper(EHPad: AncestorPad, MemoMap);
462 } else {
463 UnwindDestToken = AncestorMemo->second;
464 }
465 if (UnwindDestToken)
466 break;
467 LastUselessPad = AncestorPad;
468 MemoMap[LastUselessPad] = nullptr;
469#ifndef NDEBUG
470 TempMemos.insert(LastUselessPad);
471#endif
472 }
473
474 // We know that getUnwindDestTokenHelper was called on LastUselessPad and
475 // returned nullptr (and likewise for EHPad and any of its ancestors up to
476 // LastUselessPad), so LastUselessPad has no information from below. Since
477 // getUnwindDestTokenHelper must investigate all downward paths through
478 // no-information nodes to prove that a node has no information like this,
479 // and since any time it finds information it records it in the MemoMap for
480 // not just the immediately-containing funclet but also any ancestors also
481 // exited, it must be the case that, walking downward from LastUselessPad,
482 // visiting just those nodes which have not been mapped to an unwind dest
483 // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
484 // they are just used to keep getUnwindDestTokenHelper from repeating work),
485 // any node visited must have been exhaustively searched with no information
486 // for it found.
487 SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
488 while (!Worklist.empty()) {
489 Instruction *UselessPad = Worklist.pop_back_val();
490 auto Memo = MemoMap.find(Val: UselessPad);
491 if (Memo != MemoMap.end() && Memo->second) {
492 // Here the name 'UselessPad' is a bit of a misnomer, because we've found
493 // that it is a funclet that does have information about unwinding to
494 // a particular destination; its parent was a useless pad.
495 // Since its parent has no information, the unwind edge must not escape
496 // the parent, and must target a sibling of this pad. This local unwind
497 // gives us no information about EHPad. Leave it and the subtree rooted
498 // at it alone.
499 assert(getParentPad(Memo->second) == getParentPad(UselessPad));
500 continue;
501 }
502 // We know we don't have information for UselesPad. If it has an entry in
503 // the MemoMap (mapping it to nullptr), it must be one of the TempMemos
504 // added on this invocation of getUnwindDestToken; if a previous invocation
505 // recorded nullptr, it would have had to prove that the ancestors of
506 // UselessPad, which include LastUselessPad, had no information, and that
507 // in turn would have required proving that the descendants of
508 // LastUselesPad, which include EHPad, have no information about
509 // LastUselessPad, which would imply that EHPad was mapped to nullptr in
510 // the MemoMap on that invocation, which isn't the case if we got here.
511 assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
512 // Assert as we enumerate users that 'UselessPad' doesn't have any unwind
513 // information that we'd be contradicting by making a map entry for it
514 // (which is something that getUnwindDestTokenHelper must have proved for
515 // us to get here). Just assert on is direct users here; the checks in
516 // this downward walk at its descendants will verify that they don't have
517 // any unwind edges that exit 'UselessPad' either (i.e. they either have no
518 // unwind edges or unwind to a sibling).
519 MemoMap[UselessPad] = UnwindDestToken;
520 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Val: UselessPad)) {
521 assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
522 for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
523 auto *CatchPad = &*HandlerBlock->getFirstNonPHIIt();
524 for (User *U : CatchPad->users()) {
525 assert((!isa<InvokeInst>(U) ||
526 (getParentPad(&*cast<InvokeInst>(U)
527 ->getUnwindDest()
528 ->getFirstNonPHIIt()) == CatchPad)) &&
529 "Expected useless pad");
530 if (isa<CatchSwitchInst>(Val: U) || isa<CleanupPadInst>(Val: U))
531 Worklist.push_back(Elt: cast<Instruction>(Val: U));
532 }
533 }
534 } else {
535 assert(isa<CleanupPadInst>(UselessPad));
536 for (User *U : UselessPad->users()) {
537 assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
538 assert(
539 (!isa<InvokeInst>(U) ||
540 (getParentPad(
541 &*cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHIIt()) ==
542 UselessPad)) &&
543 "Expected useless pad");
544 if (isa<CatchSwitchInst>(Val: U) || isa<CleanupPadInst>(Val: U))
545 Worklist.push_back(Elt: cast<Instruction>(Val: U));
546 }
547 }
548 }
549
550 return UnwindDestToken;
551}
552
553/// When we inline a basic block into an invoke,
554/// we have to turn all of the calls that can throw into invokes.
555/// This function analyze BB to see if there are any calls, and if so,
556/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
557/// nodes in that block with the values specified in InvokeDestPHIValues.
558static BasicBlock *HandleCallsInBlockInlinedThroughInvoke(
559 BasicBlock *BB, BasicBlock *UnwindEdge,
560 SmallSetVector<const Value *, 4> &OriginallyIndirectCalls,
561 UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
562 for (Instruction &I : llvm::make_early_inc_range(Range&: *BB)) {
563 // We only need to check for function calls: inlined invoke
564 // instructions require no special handling.
565 CallInst *CI = dyn_cast<CallInst>(Val: &I);
566
567 if (!CI || CI->doesNotThrow())
568 continue;
569
570 // We do not need to (and in fact, cannot) convert possibly throwing calls
571 // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
572 // invokes. The caller's "segment" of the deoptimization continuation
573 // attached to the newly inlined @llvm.experimental_deoptimize
574 // (resp. @llvm.experimental.guard) call should contain the exception
575 // handling logic, if any.
576 if (auto *F = CI->getCalledFunction())
577 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
578 F->getIntrinsicID() == Intrinsic::experimental_guard)
579 continue;
580
581 if (auto FuncletBundle = CI->getOperandBundle(ID: LLVMContext::OB_funclet)) {
582 // This call is nested inside a funclet. If that funclet has an unwind
583 // destination within the inlinee, then unwinding out of this call would
584 // be UB. Rewriting this call to an invoke which targets the inlined
585 // invoke's unwind dest would give the call's parent funclet multiple
586 // unwind destinations, which is something that subsequent EH table
587 // generation can't handle and that the veirifer rejects. So when we
588 // see such a call, leave it as a call.
589 auto *FuncletPad = cast<Instruction>(Val: FuncletBundle->Inputs[0]);
590 Value *UnwindDestToken =
591 getUnwindDestToken(EHPad: FuncletPad, MemoMap&: *FuncletUnwindMap);
592 if (UnwindDestToken && !isa<ConstantTokenNone>(Val: UnwindDestToken))
593 continue;
594#ifndef NDEBUG
595 Instruction *MemoKey;
596 if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
597 MemoKey = CatchPad->getCatchSwitch();
598 else
599 MemoKey = FuncletPad;
600 assert(FuncletUnwindMap->count(MemoKey) &&
601 (*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
602 "must get memoized to avoid confusing later searches");
603#endif // NDEBUG
604 }
605
606 bool WasIndirect = OriginallyIndirectCalls.remove(X: CI);
607 changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
608 if (WasIndirect)
609 OriginallyIndirectCalls.insert(X: BB->getTerminator());
610 return BB;
611 }
612 return nullptr;
613}
614
615/// If we inlined an invoke site, we need to convert calls
616/// in the body of the inlined function into invokes.
617///
618/// II is the invoke instruction being inlined. FirstNewBlock is the first
619/// block of the inlined code (the last block is the end of the function),
620/// and InlineCodeInfo is information about the code that got inlined.
621static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
622 ClonedCodeInfo &InlinedCodeInfo) {
623 BasicBlock *InvokeDest = II->getUnwindDest();
624
625 Function *Caller = FirstNewBlock->getParent();
626
627 // The inlined code is currently at the end of the function, scan from the
628 // start of the inlined code to its end, checking for stuff we need to
629 // rewrite.
630 LandingPadInliningInfo Invoke(II);
631
632 // Get all of the inlined landing pad instructions. Keep them in block order
633 // so the clauses appended below get a deterministic use-list order.
634 SmallSetVector<LandingPadInst *, 16> InlinedLPads;
635 for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
636 I != E; ++I)
637 if (InvokeInst *II = dyn_cast<InvokeInst>(Val: I->getTerminator()))
638 InlinedLPads.insert(X: II->getLandingPadInst());
639
640 // Append the clauses from the outer landing pad instruction into the inlined
641 // landing pad instructions.
642 LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
643 for (LandingPadInst *InlinedLPad : InlinedLPads) {
644 unsigned OuterNum = OuterLPad->getNumClauses();
645 InlinedLPad->reserveClauses(Size: OuterNum);
646 for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
647 InlinedLPad->addClause(ClauseVal: OuterLPad->getClause(Idx: OuterIdx));
648 if (OuterLPad->isCleanup())
649 InlinedLPad->setCleanup(true);
650 }
651
652 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
653 BB != E; ++BB) {
654 if (InlinedCodeInfo.ContainsCalls)
655 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
656 BB: &*BB, UnwindEdge: Invoke.getOuterResumeDest(),
657 OriginallyIndirectCalls&: InlinedCodeInfo.OriginallyIndirectCalls))
658 // Update any PHI nodes in the exceptional block to indicate that there
659 // is now a new entry in them.
660 Invoke.addIncomingPHIValuesFor(BB: NewBB);
661
662 // Forward any resumes that are remaining here.
663 if (ResumeInst *RI = dyn_cast<ResumeInst>(Val: BB->getTerminator()))
664 Invoke.forwardResume(RI);
665 }
666
667 // Now that everything is happy, we have one final detail. The PHI nodes in
668 // the exception destination block still have entries due to the original
669 // invoke instruction. Eliminate these entries (which might even delete the
670 // PHI node) now.
671 InvokeDest->removePredecessor(Pred: II->getParent());
672}
673
674/// If we inlined an invoke site, we need to convert calls
675/// in the body of the inlined function into invokes.
676///
677/// II is the invoke instruction being inlined. FirstNewBlock is the first
678/// block of the inlined code (the last block is the end of the function),
679/// and InlineCodeInfo is information about the code that got inlined.
680static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
681 ClonedCodeInfo &InlinedCodeInfo) {
682 BasicBlock *UnwindDest = II->getUnwindDest();
683 Function *Caller = FirstNewBlock->getParent();
684
685 assert(UnwindDest->getFirstNonPHIIt()->isEHPad() && "unexpected BasicBlock!");
686
687 // If there are PHI nodes in the unwind destination block, we need to keep
688 // track of which values came into them from the invoke before removing the
689 // edge from this block.
690 SmallVector<Value *, 8> UnwindDestPHIValues;
691 BasicBlock *InvokeBB = II->getParent();
692 for (PHINode &PHI : UnwindDest->phis()) {
693 // Save the value to use for this edge.
694 UnwindDestPHIValues.push_back(Elt: PHI.getIncomingValueForBlock(BB: InvokeBB));
695 }
696
697 // Add incoming-PHI values to the unwind destination block for the given basic
698 // block, using the values for the original invoke's source block.
699 auto UpdatePHINodes = [&](BasicBlock *Src) {
700 BasicBlock::iterator I = UnwindDest->begin();
701 for (Value *V : UnwindDestPHIValues) {
702 PHINode *PHI = cast<PHINode>(Val&: I);
703 PHI->addIncoming(V, BB: Src);
704 ++I;
705 }
706 };
707
708 // This connects all the instructions which 'unwind to caller' to the invoke
709 // destination.
710 UnwindDestMemoTy FuncletUnwindMap;
711 for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
712 BB != E; ++BB) {
713 if (auto *CRI = dyn_cast<CleanupReturnInst>(Val: BB->getTerminator())) {
714 if (CRI->unwindsToCaller()) {
715 auto *CleanupPad = CRI->getCleanupPad();
716 CleanupReturnInst::Create(CleanupPad, UnwindBB: UnwindDest, InsertBefore: CRI->getIterator());
717 CRI->eraseFromParent();
718 UpdatePHINodes(&*BB);
719 // Finding a cleanupret with an unwind destination would confuse
720 // subsequent calls to getUnwindDestToken, so map the cleanuppad
721 // to short-circuit any such calls and recognize this as an "unwind
722 // to caller" cleanup.
723 assert(!FuncletUnwindMap.count(CleanupPad) ||
724 isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
725 FuncletUnwindMap[CleanupPad] =
726 ConstantTokenNone::get(Context&: Caller->getContext());
727 }
728 }
729
730 BasicBlock::iterator I = BB->getFirstNonPHIIt();
731 if (!I->isEHPad())
732 continue;
733
734 Instruction *Replacement = nullptr;
735 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Val&: I)) {
736 if (CatchSwitch->unwindsToCaller()) {
737 Value *UnwindDestToken;
738 if (auto *ParentPad =
739 dyn_cast<Instruction>(Val: CatchSwitch->getParentPad())) {
740 // This catchswitch is nested inside another funclet. If that
741 // funclet has an unwind destination within the inlinee, then
742 // unwinding out of this catchswitch would be UB. Rewriting this
743 // catchswitch to unwind to the inlined invoke's unwind dest would
744 // give the parent funclet multiple unwind destinations, which is
745 // something that subsequent EH table generation can't handle and
746 // that the veirifer rejects. So when we see such a call, leave it
747 // as "unwind to caller".
748 UnwindDestToken = getUnwindDestToken(EHPad: ParentPad, MemoMap&: FuncletUnwindMap);
749 if (UnwindDestToken && !isa<ConstantTokenNone>(Val: UnwindDestToken))
750 continue;
751 } else {
752 // This catchswitch has no parent to inherit constraints from, and
753 // none of its descendants can have an unwind edge that exits it and
754 // targets another funclet in the inlinee. It may or may not have a
755 // descendant that definitively has an unwind to caller. In either
756 // case, we'll have to assume that any unwinds out of it may need to
757 // be routed to the caller, so treat it as though it has a definitive
758 // unwind to caller.
759 UnwindDestToken = ConstantTokenNone::get(Context&: Caller->getContext());
760 }
761 auto *NewCatchSwitch = CatchSwitchInst::Create(
762 ParentPad: CatchSwitch->getParentPad(), UnwindDest,
763 NumHandlers: CatchSwitch->getNumHandlers(), NameStr: CatchSwitch->getName(),
764 InsertBefore: CatchSwitch->getIterator());
765 for (BasicBlock *PadBB : CatchSwitch->handlers())
766 NewCatchSwitch->addHandler(Dest: PadBB);
767 // Propagate info for the old catchswitch over to the new one in
768 // the unwind map. This also serves to short-circuit any subsequent
769 // checks for the unwind dest of this catchswitch, which would get
770 // confused if they found the outer handler in the callee.
771 FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
772 Replacement = NewCatchSwitch;
773 }
774 } else if (!isa<FuncletPadInst>(Val: I)) {
775 llvm_unreachable("unexpected EHPad!");
776 }
777
778 if (Replacement) {
779 Replacement->takeName(V: &*I);
780 I->replaceAllUsesWith(V: Replacement);
781 I->eraseFromParent();
782 UpdatePHINodes(&*BB);
783 }
784 }
785
786 if (InlinedCodeInfo.ContainsCalls)
787 for (Function::iterator BB = FirstNewBlock->getIterator(),
788 E = Caller->end();
789 BB != E; ++BB)
790 if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
791 BB: &*BB, UnwindEdge: UnwindDest, OriginallyIndirectCalls&: InlinedCodeInfo.OriginallyIndirectCalls,
792 FuncletUnwindMap: &FuncletUnwindMap))
793 // Update any PHI nodes in the exceptional block to indicate that there
794 // is now a new entry in them.
795 UpdatePHINodes(NewBB);
796
797 // Now that everything is happy, we have one final detail. The PHI nodes in
798 // the exception destination block still have entries due to the original
799 // invoke instruction. Eliminate these entries (which might even delete the
800 // PHI node) now.
801 UnwindDest->removePredecessor(Pred: InvokeBB);
802}
803
804static bool haveCommonPrefix(MDNode *MIBStackContext,
805 MDNode *CallsiteStackContext) {
806 assert(MIBStackContext->getNumOperands() > 0 &&
807 CallsiteStackContext->getNumOperands() > 0);
808 // Because of the context trimming performed during matching, the callsite
809 // context could have more stack ids than the MIB. We match up to the end of
810 // the shortest stack context.
811 for (auto MIBStackIter = MIBStackContext->op_begin(),
812 CallsiteStackIter = CallsiteStackContext->op_begin();
813 MIBStackIter != MIBStackContext->op_end() &&
814 CallsiteStackIter != CallsiteStackContext->op_end();
815 MIBStackIter++, CallsiteStackIter++) {
816 auto *Val1 = mdconst::dyn_extract<ConstantInt>(MD: *MIBStackIter);
817 auto *Val2 = mdconst::dyn_extract<ConstantInt>(MD: *CallsiteStackIter);
818 assert(Val1 && Val2);
819 if (Val1->getZExtValue() != Val2->getZExtValue())
820 return false;
821 }
822 return true;
823}
824
825static void removeMemProfMetadata(CallBase *Call) {
826 Call->setMetadata(KindID: LLVMContext::MD_memprof, Node: nullptr);
827}
828
829static void removeCallsiteMetadata(CallBase *Call) {
830 Call->setMetadata(KindID: LLVMContext::MD_callsite, Node: nullptr);
831}
832
833static void updateMemprofMetadata(CallBase *CI,
834 const std::vector<Metadata *> &MIBList,
835 OptimizationRemarkEmitter *ORE) {
836 assert(!MIBList.empty());
837 // Remove existing memprof, which will either be replaced or may not be needed
838 // if we are able to use a single allocation type function attribute.
839 removeMemProfMetadata(Call: CI);
840 CallStackTrie CallStack(ORE);
841 for (Metadata *MIB : MIBList)
842 CallStack.addCallStack(MIB: cast<MDNode>(Val: MIB));
843 bool MemprofMDAttached = CallStack.buildAndAttachMIBMetadata(CI);
844 assert(MemprofMDAttached == CI->hasMetadata(LLVMContext::MD_memprof));
845 if (!MemprofMDAttached)
846 // If we used a function attribute remove the callsite metadata as well.
847 removeCallsiteMetadata(Call: CI);
848}
849
850// Update the metadata on the inlined copy ClonedCall of a call OrigCall in the
851// inlined callee body, based on the callsite metadata InlinedCallsiteMD from
852// the call that was inlined.
853static void propagateMemProfHelper(const CallBase *OrigCall,
854 CallBase *ClonedCall,
855 MDNode *InlinedCallsiteMD,
856 OptimizationRemarkEmitter *ORE) {
857 MDNode *OrigCallsiteMD = ClonedCall->getMetadata(KindID: LLVMContext::MD_callsite);
858 MDNode *ClonedCallsiteMD = nullptr;
859 // Check if the call originally had callsite metadata, and update it for the
860 // new call in the inlined body.
861 if (OrigCallsiteMD) {
862 // The cloned call's context is now the concatenation of the original call's
863 // callsite metadata and the callsite metadata on the call where it was
864 // inlined.
865 ClonedCallsiteMD = MDNode::concatenate(A: OrigCallsiteMD, B: InlinedCallsiteMD);
866 ClonedCall->setMetadata(KindID: LLVMContext::MD_callsite, Node: ClonedCallsiteMD);
867 }
868
869 // Update any memprof metadata on the cloned call.
870 MDNode *OrigMemProfMD = ClonedCall->getMetadata(KindID: LLVMContext::MD_memprof);
871 if (!OrigMemProfMD)
872 return;
873 // We currently expect that allocations with memprof metadata also have
874 // callsite metadata for the allocation's part of the context.
875 assert(OrigCallsiteMD);
876
877 // New call's MIB list.
878 std::vector<Metadata *> NewMIBList;
879
880 // For each MIB metadata, check if its call stack context starts with the
881 // new clone's callsite metadata. If so, that MIB goes onto the cloned call in
882 // the inlined body. If not, it stays on the out-of-line original call.
883 for (auto &MIBOp : OrigMemProfMD->operands()) {
884 MDNode *MIB = dyn_cast<MDNode>(Val: MIBOp);
885 // Stack is first operand of MIB.
886 MDNode *StackMD = getMIBStackNode(MIB);
887 assert(StackMD);
888 // See if the new cloned callsite context matches this profiled context.
889 if (haveCommonPrefix(MIBStackContext: StackMD, CallsiteStackContext: ClonedCallsiteMD))
890 // Add it to the cloned call's MIB list.
891 NewMIBList.push_back(x: MIB);
892 }
893 if (NewMIBList.empty()) {
894 removeMemProfMetadata(Call: ClonedCall);
895 removeCallsiteMetadata(Call: ClonedCall);
896 return;
897 }
898 if (NewMIBList.size() < OrigMemProfMD->getNumOperands())
899 updateMemprofMetadata(CI: ClonedCall, MIBList: NewMIBList, ORE);
900}
901
902// Update memprof related metadata (!memprof and !callsite) based on the
903// inlining of Callee into the callsite at CB. The updates include merging the
904// inlined callee's callsite metadata with that of the inlined call,
905// and moving the subset of any memprof contexts to the inlined callee
906// allocations if they match the new inlined call stack.
907static void
908propagateMemProfMetadata(Function *Callee, CallBase &CB,
909 bool ContainsMemProfMetadata,
910 const ValueMap<const Value *, WeakTrackingVH> &VMap,
911 OptimizationRemarkEmitter *ORE) {
912 MDNode *CallsiteMD = CB.getMetadata(KindID: LLVMContext::MD_callsite);
913 // Only need to update if the inlined callsite had callsite metadata, or if
914 // there was any memprof metadata inlined.
915 if (!CallsiteMD && !ContainsMemProfMetadata)
916 return;
917
918 // Propagate metadata onto the cloned calls in the inlined callee.
919 for (const auto &Entry : VMap) {
920 // See if this is a call that has been inlined and remapped, and not
921 // simplified away in the process.
922 auto *OrigCall = dyn_cast_or_null<CallBase>(Val: Entry.first);
923 auto *ClonedCall = dyn_cast_or_null<CallBase>(Val: Entry.second);
924 if (!OrigCall || !ClonedCall)
925 continue;
926 // If the inlined callsite did not have any callsite metadata, then it isn't
927 // involved in any profiled call contexts, and we can remove any memprof
928 // metadata on the cloned call.
929 if (!CallsiteMD) {
930 removeMemProfMetadata(Call: ClonedCall);
931 removeCallsiteMetadata(Call: ClonedCall);
932 continue;
933 }
934 propagateMemProfHelper(OrigCall, ClonedCall, InlinedCallsiteMD: CallsiteMD, ORE);
935 }
936}
937
938/// Collect all calls that produce RetVal, following only pointer-preserving
939/// instructions (cast, phi, select).
940static void collectPointerReturningCalls(Value *RetVal,
941 SmallVectorImpl<CallBase *> &Out) {
942 SmallVector<Value *, 8> Worklist{RetVal};
943 SmallPtrSet<Value *, 8> Visited;
944 while (!Worklist.empty()) {
945 Value *V = Worklist.pop_back_val();
946 if (!V->getType()->isPointerTy() || !Visited.insert(Ptr: V).second)
947 continue;
948 if (auto *CB = dyn_cast<CallBase>(Val: V))
949 Out.push_back(Elt: CB);
950 else if (isa<BitCastInst, AddrSpaceCastInst>(Val: V))
951 Worklist.push_back(Elt: cast<CastInst>(Val: V)->getOperand(i_nocapture: 0));
952 else if (auto *PN = dyn_cast<PHINode>(Val: V))
953 append_range(C&: Worklist, R: PN->incoming_values());
954 else if (auto *SI = dyn_cast<SelectInst>(Val: V)) {
955 Worklist.push_back(Elt: SI->getTrueValue());
956 Worklist.push_back(Elt: SI->getFalseValue());
957 }
958 }
959}
960
961/// When inlining a call that carries !alloc_token metadata, propagate that
962/// metadata onto calls exposed by inlining the wrapper body. Propagation is
963/// restricted to return-value producing calls, which avoids instrumenting
964/// unrelated calls in the wrapper body.
965static void
966propagateAllocTokenMetadata(Function *CalledFunc, CallBase &CB,
967 const ValueMap<const Value *, WeakTrackingVH> &VMap,
968 ClonedCodeInfo &InlinedFunctionInfo) {
969 MDNode *AllocTokenMD = CB.getMetadata(KindID: LLVMContext::MD_alloc_token);
970 if (!AllocTokenMD)
971 return;
972
973 SmallVector<CallBase *, 2> AllocCalls;
974 for (BasicBlock &BB : *CalledFunc)
975 if (auto *RI = dyn_cast<ReturnInst>(Val: BB.getTerminator()))
976 if (Value *RV = RI->getReturnValue())
977 collectPointerReturningCalls(RetVal: RV, Out&: AllocCalls);
978
979 for (CallBase *OrigCall : AllocCalls) {
980 auto *ClonedCall = dyn_cast_or_null<CallBase>(Val: VMap.lookup(Val: OrigCall));
981 if (!ClonedCall)
982 continue;
983 // Skip calls simplified during inlining; propagation may be incorrect.
984 if (InlinedFunctionInfo.isSimplified(From: OrigCall, To: ClonedCall))
985 continue;
986 // Fill missing only: never overwrite a more specific token the wrapper
987 // already set on an internal allocation. An unknown type (empty type name
988 // with function name) is not more specific.
989 if (MDNode *MD = ClonedCall->getMetadata(KindID: LLVMContext::MD_alloc_token)) {
990 if (MD->getNumOperands() != 3 ||
991 !cast<MDString>(Val: MD->getOperand(I: 0))->getString().empty())
992 continue;
993 }
994 ClonedCall->setMetadata(KindID: LLVMContext::MD_alloc_token, Node: AllocTokenMD);
995 }
996}
997
998/// When inlining a call site that has !llvm.mem.parallel_loop_access,
999/// !llvm.access.group, !alias.scope or !noalias metadata, that metadata should
1000/// be propagated to all memory-accessing cloned instructions.
1001static void PropagateCallSiteMetadata(CallBase &CB, Function::iterator FStart,
1002 Function::iterator FEnd) {
1003 MDNode *MemParallelLoopAccess =
1004 CB.getMetadata(KindID: LLVMContext::MD_mem_parallel_loop_access);
1005 MDNode *AccessGroup = CB.getMetadata(KindID: LLVMContext::MD_access_group);
1006 MDNode *AliasScope = CB.getMetadata(KindID: LLVMContext::MD_alias_scope);
1007 MDNode *NoAlias = CB.getMetadata(KindID: LLVMContext::MD_noalias);
1008 if (!MemParallelLoopAccess && !AccessGroup && !AliasScope && !NoAlias)
1009 return;
1010
1011 for (BasicBlock &BB : make_range(x: FStart, y: FEnd)) {
1012 for (Instruction &I : BB) {
1013 // This metadata is only relevant for instructions that access memory.
1014 if (!I.mayReadOrWriteMemory())
1015 continue;
1016
1017 if (MemParallelLoopAccess) {
1018 // TODO: This probably should not overwrite MemParalleLoopAccess.
1019 MemParallelLoopAccess = MDNode::concatenate(
1020 A: I.getMetadata(KindID: LLVMContext::MD_mem_parallel_loop_access),
1021 B: MemParallelLoopAccess);
1022 I.setMetadata(KindID: LLVMContext::MD_mem_parallel_loop_access,
1023 Node: MemParallelLoopAccess);
1024 }
1025
1026 if (AccessGroup)
1027 I.setMetadata(KindID: LLVMContext::MD_access_group, Node: uniteAccessGroups(
1028 AccGroups1: I.getMetadata(KindID: LLVMContext::MD_access_group), AccGroups2: AccessGroup));
1029
1030 if (AliasScope)
1031 I.setMetadata(KindID: LLVMContext::MD_alias_scope, Node: MDNode::concatenate(
1032 A: I.getMetadata(KindID: LLVMContext::MD_alias_scope), B: AliasScope));
1033
1034 if (NoAlias)
1035 I.setMetadata(KindID: LLVMContext::MD_noalias, Node: MDNode::concatenate(
1036 A: I.getMetadata(KindID: LLVMContext::MD_noalias), B: NoAlias));
1037 }
1038 }
1039}
1040
1041/// Track inlining chain via inlined.from metadata for dontcall diagnostics.
1042static void PropagateInlinedFromMetadata(CallBase &CB, StringRef CalledFuncName,
1043 StringRef CallerFuncName,
1044 Function::iterator FStart,
1045 Function::iterator FEnd) {
1046 LLVMContext &Ctx = CB.getContext();
1047 uint64_t InlineSiteLoc = 0;
1048 if (auto *MD = CB.getMetadata(Kind: "srcloc"))
1049 if (auto *CI = mdconst::dyn_extract<ConstantInt>(MD: MD->getOperand(I: 0)))
1050 InlineSiteLoc = CI->getZExtValue();
1051
1052 auto *I64Ty = Type::getInt64Ty(C&: Ctx);
1053 auto MakeMDInt = [&](uint64_t V) {
1054 return ConstantAsMetadata::get(C: ConstantInt::get(Ty: I64Ty, V));
1055 };
1056
1057 for (BasicBlock &BB : make_range(x: FStart, y: FEnd)) {
1058 for (Instruction &I : BB) {
1059 auto *CI = dyn_cast<CallInst>(Val: &I);
1060 if (!CI || !CI->getMetadata(Kind: "srcloc"))
1061 continue;
1062 auto *Callee = CI->getCalledFunction();
1063 if (!Callee || (!Callee->hasFnAttribute(Kind: "dontcall-error") &&
1064 !Callee->hasFnAttribute(Kind: "dontcall-warn")))
1065 continue;
1066
1067 SmallVector<Metadata *, 8> Ops;
1068 if (MDNode *Existing = CI->getMetadata(Kind: "inlined.from"))
1069 append_range(C&: Ops, R: Existing->operands());
1070 else {
1071 Ops.push_back(Elt: MDString::get(Context&: Ctx, Str: CalledFuncName));
1072 Ops.push_back(Elt: MakeMDInt(0));
1073 }
1074 Ops.push_back(Elt: MDString::get(Context&: Ctx, Str: CallerFuncName));
1075 Ops.push_back(Elt: MakeMDInt(InlineSiteLoc));
1076 CI->setMetadata(Kind: "inlined.from", Node: MDNode::get(Context&: Ctx, MDs: Ops));
1077 }
1078 }
1079}
1080
1081/// Bundle operands of the inlined function must be added to inlined call sites.
1082static void PropagateOperandBundles(Function::iterator InlinedBB,
1083 Instruction *CallSiteEHPad) {
1084 for (Instruction &II : llvm::make_early_inc_range(Range&: *InlinedBB)) {
1085 CallBase *I = dyn_cast<CallBase>(Val: &II);
1086 if (!I)
1087 continue;
1088 // Skip call sites which already have a "funclet" bundle.
1089 if (I->getOperandBundle(ID: LLVMContext::OB_funclet))
1090 continue;
1091 // Skip call sites which are nounwind intrinsics (as long as they don't
1092 // lower into regular function calls in the course of IR transformations).
1093 auto *CalledFn =
1094 dyn_cast<Function>(Val: I->getCalledOperand()->stripPointerCasts());
1095 if (CalledFn && CalledFn->isIntrinsic() && I->doesNotThrow() &&
1096 !IntrinsicInst::mayLowerToFunctionCall(IID: CalledFn->getIntrinsicID()))
1097 continue;
1098
1099 SmallVector<OperandBundleDef, 1> OpBundles;
1100 I->getOperandBundlesAsDefs(Defs&: OpBundles);
1101 OpBundles.emplace_back(Args: "funclet", Args&: CallSiteEHPad);
1102
1103 Instruction *NewInst = CallBase::Create(CB: I, Bundles: OpBundles, InsertPt: I->getIterator());
1104 NewInst->takeName(V: I);
1105 I->replaceAllUsesWith(V: NewInst);
1106 I->eraseFromParent();
1107 }
1108}
1109
1110namespace {
1111/// Utility for cloning !noalias and !alias.scope metadata. When a code region
1112/// using scoped alias metadata is inlined, the aliasing relationships may not
1113/// hold between the two version. It is necessary to create a deep clone of the
1114/// metadata, putting the two versions in separate scope domains.
1115class ScopedAliasMetadataDeepCloner {
1116 using MetadataMap = DenseMap<const MDNode *, TrackingMDNodeRef>;
1117 SetVector<const MDNode *> MD;
1118 MetadataMap MDMap;
1119 void addRecursiveMetadataUses();
1120
1121public:
1122 ScopedAliasMetadataDeepCloner(const Function *F);
1123
1124 /// Create a new clone of the scoped alias metadata, which will be used by
1125 /// subsequent remap() calls.
1126 void clone();
1127
1128 /// Remap instructions in the given range from the original to the cloned
1129 /// metadata.
1130 void remap(Function::iterator FStart, Function::iterator FEnd);
1131};
1132} // namespace
1133
1134ScopedAliasMetadataDeepCloner::ScopedAliasMetadataDeepCloner(
1135 const Function *F) {
1136 for (const BasicBlock &BB : *F) {
1137 for (const Instruction &I : BB) {
1138 if (const MDNode *M = I.getMetadata(KindID: LLVMContext::MD_alias_scope))
1139 MD.insert(X: M);
1140 if (const MDNode *M = I.getMetadata(KindID: LLVMContext::MD_noalias))
1141 MD.insert(X: M);
1142
1143 // We also need to clone the metadata in noalias intrinsics.
1144 if (const auto *Decl = dyn_cast<NoAliasScopeDeclInst>(Val: &I))
1145 MD.insert(X: Decl->getScopeList());
1146 }
1147 }
1148 addRecursiveMetadataUses();
1149}
1150
1151void ScopedAliasMetadataDeepCloner::addRecursiveMetadataUses() {
1152 SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
1153 while (!Queue.empty()) {
1154 const MDNode *M = cast<MDNode>(Val: Queue.pop_back_val());
1155 for (const Metadata *Op : M->operands())
1156 if (const MDNode *OpMD = dyn_cast<MDNode>(Val: Op))
1157 if (MD.insert(X: OpMD))
1158 Queue.push_back(Elt: OpMD);
1159 }
1160}
1161
1162void ScopedAliasMetadataDeepCloner::clone() {
1163 assert(MDMap.empty() && "clone() already called ?");
1164
1165 SmallVector<TempMDTuple, 16> DummyNodes;
1166 for (const MDNode *I : MD) {
1167 DummyNodes.push_back(Elt: MDTuple::getTemporary(Context&: I->getContext(), MDs: {}));
1168 MDMap[I].reset(MD: DummyNodes.back().get());
1169 }
1170
1171 // Create new metadata nodes to replace the dummy nodes, replacing old
1172 // metadata references with either a dummy node or an already-created new
1173 // node.
1174 SmallVector<Metadata *, 4> NewOps;
1175 for (const MDNode *I : MD) {
1176 for (const Metadata *Op : I->operands()) {
1177 if (const MDNode *M = dyn_cast<MDNode>(Val: Op))
1178 NewOps.push_back(Elt: MDMap[M]);
1179 else
1180 NewOps.push_back(Elt: const_cast<Metadata *>(Op));
1181 }
1182
1183 MDNode *NewM = MDNode::get(Context&: I->getContext(), MDs: NewOps);
1184 MDTuple *TempM = cast<MDTuple>(Val&: MDMap[I]);
1185 assert(TempM->isTemporary() && "Expected temporary node");
1186
1187 TempM->replaceAllUsesWith(MD: NewM);
1188 NewOps.clear();
1189 }
1190}
1191
1192void ScopedAliasMetadataDeepCloner::remap(Function::iterator FStart,
1193 Function::iterator FEnd) {
1194 if (MDMap.empty())
1195 return; // Nothing to do.
1196
1197 for (BasicBlock &BB : make_range(x: FStart, y: FEnd)) {
1198 for (Instruction &I : BB) {
1199 // TODO: The null checks for the MDMap.lookup() results should no longer
1200 // be necessary.
1201 if (MDNode *M = I.getMetadata(KindID: LLVMContext::MD_alias_scope))
1202 if (MDNode *MNew = MDMap.lookup(Val: M))
1203 I.setMetadata(KindID: LLVMContext::MD_alias_scope, Node: MNew);
1204
1205 if (MDNode *M = I.getMetadata(KindID: LLVMContext::MD_noalias))
1206 if (MDNode *MNew = MDMap.lookup(Val: M))
1207 I.setMetadata(KindID: LLVMContext::MD_noalias, Node: MNew);
1208
1209 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(Val: &I))
1210 if (MDNode *MNew = MDMap.lookup(Val: Decl->getScopeList()))
1211 Decl->setScopeList(MNew);
1212 }
1213 }
1214}
1215
1216/// If the inlined function has noalias arguments,
1217/// then add new alias scopes for each noalias argument, tag the mapped noalias
1218/// parameters with noalias metadata specifying the new scope, and tag all
1219/// non-derived loads, stores and memory intrinsics with the new alias scopes.
1220static void AddAliasScopeMetadata(CallBase &CB, ValueToValueMapTy &VMap,
1221 const DataLayout &DL, AAResults *CalleeAAR,
1222 ClonedCodeInfo &InlinedFunctionInfo) {
1223 if (!EnableNoAliasConversion)
1224 return;
1225
1226 const Function *CalledFunc = CB.getCalledFunction();
1227 SmallVector<const Argument *, 4> NoAliasArgs;
1228
1229 for (const Argument &Arg : CalledFunc->args())
1230 if (CB.paramHasAttr(ArgNo: Arg.getArgNo(), Kind: Attribute::NoAlias) && !Arg.use_empty())
1231 NoAliasArgs.push_back(Elt: &Arg);
1232
1233 if (NoAliasArgs.empty())
1234 return;
1235
1236 // To do a good job, if a noalias variable is captured, we need to know if
1237 // the capture point dominates the particular use we're considering.
1238 DominatorTree DT;
1239 DT.recalculate(Func&: const_cast<Function&>(*CalledFunc));
1240
1241 // noalias indicates that pointer values based on the argument do not alias
1242 // pointer values which are not based on it. So we add a new "scope" for each
1243 // noalias function argument. Accesses using pointers based on that argument
1244 // become part of that alias scope, accesses using pointers not based on that
1245 // argument are tagged as noalias with that scope.
1246
1247 DenseMap<const Argument *, MDNode *> NewScopes;
1248 MDBuilder MDB(CalledFunc->getContext());
1249
1250 // Create a new scope domain for this function. Its scopes are disjoint,
1251 // since accesses based on one noalias argument don't alias accesses based on
1252 // another one.
1253 MDNode *NewDomain = MDB.createAnonymousAliasScopeDomain(
1254 Description: CalledFunc->getName(), /*DisjointScopes=*/true);
1255 for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
1256 const Argument *A = NoAliasArgs[i];
1257
1258 std::string Name = std::string(CalledFunc->getName());
1259 if (A->hasName()) {
1260 Name += ": %";
1261 Name += A->getName();
1262 } else {
1263 Name += ": argument ";
1264 Name += utostr(X: i);
1265 }
1266
1267 // Note: We always create a new anonymous root here. This is true regardless
1268 // of the linkage of the callee because the aliasing "scope" is not just a
1269 // property of the callee, but also all control dependencies in the caller.
1270 MDNode *NewScope = MDB.createAnonymousAliasScope(Domain: NewDomain, Name);
1271 NewScopes.insert(KV: std::make_pair(x&: A, y&: NewScope));
1272
1273 if (UseNoAliasIntrinsic) {
1274 // Introduce a llvm.experimental.noalias.scope.decl for the noalias
1275 // argument.
1276 MDNode *AScopeList = MDNode::get(Context&: CalledFunc->getContext(), MDs: NewScope);
1277 auto *NoAliasDecl =
1278 IRBuilder<>(&CB).CreateNoAliasScopeDeclaration(ScopeTag: AScopeList);
1279 // Ignore the result for now. The result will be used when the
1280 // llvm.noalias intrinsic is introduced.
1281 (void)NoAliasDecl;
1282 }
1283 }
1284
1285 // Iterate over all new instructions in the map; for all memory-access
1286 // instructions, add the alias scope metadata.
1287 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
1288 VMI != VMIE; ++VMI) {
1289 if (const Instruction *I = dyn_cast<Instruction>(Val: VMI->first)) {
1290 if (!VMI->second)
1291 continue;
1292
1293 Instruction *NI = dyn_cast<Instruction>(Val&: VMI->second);
1294 if (!NI || InlinedFunctionInfo.isSimplified(From: I, To: NI))
1295 continue;
1296
1297 bool IsArgMemOnlyCall = false, IsFuncCall = false;
1298 SmallVector<const Value *, 2> PtrArgs;
1299
1300 if (const LoadInst *LI = dyn_cast<LoadInst>(Val: I))
1301 PtrArgs.push_back(Elt: LI->getPointerOperand());
1302 else if (const StoreInst *SI = dyn_cast<StoreInst>(Val: I))
1303 PtrArgs.push_back(Elt: SI->getPointerOperand());
1304 else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(Val: I))
1305 PtrArgs.push_back(Elt: VAAI->getPointerOperand());
1306 else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(Val: I))
1307 PtrArgs.push_back(Elt: CXI->getPointerOperand());
1308 else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(Val: I))
1309 PtrArgs.push_back(Elt: RMWI->getPointerOperand());
1310 else if (const auto *Call = dyn_cast<CallBase>(Val: I)) {
1311 // If we know that the call does not access memory, then we'll still
1312 // know that about the inlined clone of this call site, and we don't
1313 // need to add metadata.
1314 if (Call->doesNotAccessMemory())
1315 continue;
1316
1317 IsFuncCall = true;
1318 if (CalleeAAR) {
1319 MemoryEffects ME = CalleeAAR->getMemoryEffects(Call);
1320
1321 // We'll retain this knowledge without additional metadata.
1322 if (ME.onlyAccessesInaccessibleMem())
1323 continue;
1324
1325 if (ME.onlyAccessesArgPointees())
1326 IsArgMemOnlyCall = true;
1327 }
1328
1329 for (Value *Arg : Call->args()) {
1330 // Only care about pointer arguments. If a noalias argument is
1331 // accessed through a non-pointer argument, it must be captured
1332 // first (e.g. via ptrtoint), and we protect against captures below.
1333 if (!Arg->getType()->isPointerTy())
1334 continue;
1335
1336 PtrArgs.push_back(Elt: Arg);
1337 }
1338 }
1339
1340 // If we found no pointers, then this instruction is not suitable for
1341 // pairing with an instruction to receive aliasing metadata.
1342 // However, if this is a call, this we might just alias with none of the
1343 // noalias arguments.
1344 if (PtrArgs.empty() && !IsFuncCall)
1345 continue;
1346
1347 // It is possible that there is only one underlying object, but you
1348 // need to go through several PHIs to see it, and thus could be
1349 // repeated in the Objects list.
1350 SmallPtrSet<const Value *, 4> ObjSet;
1351 SmallVector<Metadata *, 4> Scopes, NoAliases;
1352
1353 for (const Value *V : PtrArgs) {
1354 SmallVector<const Value *, 4> Objects;
1355 getUnderlyingObjects(V, Objects, /* LI = */ nullptr);
1356
1357 ObjSet.insert_range(R&: Objects);
1358 }
1359
1360 // Figure out if we're derived from anything that is not a noalias
1361 // argument.
1362 bool RequiresNoCaptureBefore = false, UsesAliasingPtr = false,
1363 UsesUnknownObject = false;
1364 for (const Value *V : ObjSet) {
1365 // Is this value a constant that cannot be derived from any pointer
1366 // value (we need to exclude constant expressions, for example, that
1367 // are formed from arithmetic on global symbols).
1368 bool IsNonPtrConst = isa<ConstantInt>(Val: V) || isa<ConstantFP>(Val: V) ||
1369 isa<ConstantPointerNull>(Val: V) ||
1370 isa<ConstantDataVector>(Val: V) || isa<UndefValue>(Val: V);
1371 if (IsNonPtrConst)
1372 continue;
1373
1374 // If this is anything other than a noalias argument, then we cannot
1375 // completely describe the aliasing properties using alias.scope
1376 // metadata (and, thus, won't add any).
1377 if (const Argument *A = dyn_cast<Argument>(Val: V)) {
1378 if (!CB.paramHasAttr(ArgNo: A->getArgNo(), Kind: Attribute::NoAlias))
1379 UsesAliasingPtr = true;
1380 } else {
1381 UsesAliasingPtr = true;
1382 }
1383
1384 if (isEscapeSource(V)) {
1385 // An escape source can only alias with a noalias argument if it has
1386 // been captured beforehand.
1387 RequiresNoCaptureBefore = true;
1388 } else if (!isa<Argument>(Val: V) && !isIdentifiedObject(V)) {
1389 // If this is neither an escape source, nor some identified object
1390 // (which cannot directly alias a noalias argument), nor some other
1391 // argument (which, by definition, also cannot alias a noalias
1392 // argument), conservatively do not make any assumptions.
1393 UsesUnknownObject = true;
1394 }
1395 }
1396
1397 // Nothing we can do if the used underlying object cannot be reliably
1398 // determined.
1399 if (UsesUnknownObject)
1400 continue;
1401
1402 // A function call can always get captured noalias pointers (via other
1403 // parameters, globals, etc.).
1404 if (IsFuncCall && !IsArgMemOnlyCall)
1405 RequiresNoCaptureBefore = true;
1406
1407 // First, we want to figure out all of the sets to which we might belong.
1408 // We might belong to a set if the noalias argument is in the set of
1409 // underlying objects. If there is some non-noalias argument in our list
1410 // of underlying objects, then we cannot add a scope because the fact
1411 // that some access does not alias with any set of our noalias arguments
1412 // cannot itself guarantee that it does not alias with this access
1413 // (because there is some pointer of unknown origin involved and the
1414 // other access might also depend on this pointer). We also cannot add
1415 // scopes to arbitrary functions unless we know they don't access any
1416 // non-parameter pointer-values.
1417 bool CanAddScopes = !UsesAliasingPtr && (!IsFuncCall || IsArgMemOnlyCall);
1418 if (CanAddScopes) {
1419 for (const Argument *A : NoAliasArgs) {
1420 if (ObjSet.count(Ptr: A))
1421 Scopes.push_back(Elt: NewScopes[A]);
1422 }
1423 }
1424
1425 if (!Scopes.empty()) {
1426 NI->setMetadata(
1427 KindID: LLVMContext::MD_alias_scope,
1428 Node: MDNode::concatenate(A: NI->getMetadata(KindID: LLVMContext::MD_alias_scope),
1429 B: MDNode::get(Context&: CalledFunc->getContext(), MDs: Scopes)));
1430 // Being in these scopes already means being noalias with the rest.
1431 continue;
1432 }
1433
1434 // Next, we want to figure out all of the sets with which we definitely
1435 // don't alias. Iterate over all noalias set, and add those for which:
1436 // 1. The noalias argument is not in the set of objects from which we
1437 // definitely derive.
1438 // 2. The noalias argument has not yet been captured.
1439 // An arbitrary function that might load pointers could see captured
1440 // noalias arguments via other noalias arguments or globals, and so we
1441 // must always check for prior capture.
1442 for (const Argument *A : NoAliasArgs) {
1443 if (ObjSet.contains(Ptr: A))
1444 continue; // May be based on a noalias argument.
1445
1446 // It might be tempting to skip the PointerMayBeCapturedBefore check if
1447 // A->hasNoCaptureAttr() is true, but this is incorrect because
1448 // nocapture only guarantees that no copies outlive the function, not
1449 // that the value cannot be locally captured.
1450 if (!RequiresNoCaptureBefore ||
1451 !capturesAnything(CC: PointerMayBeCapturedBefore(
1452 V: A, /*ReturnCaptures=*/false, I, DT: &DT, /*IncludeI=*/false,
1453 Mask: CaptureComponents::Provenance)))
1454 NoAliases.push_back(Elt: NewScopes[A]);
1455 }
1456
1457 if (!NoAliases.empty())
1458 NI->setMetadata(KindID: LLVMContext::MD_noalias,
1459 Node: MDNode::concatenate(
1460 A: NI->getMetadata(KindID: LLVMContext::MD_noalias),
1461 B: MDNode::get(Context&: CalledFunc->getContext(), MDs: NoAliases)));
1462 }
1463 }
1464}
1465
1466static bool MayContainThrowingOrExitingCallAfterCB(CallBase *Begin,
1467 ReturnInst *End) {
1468
1469 assert(Begin->getParent() == End->getParent() &&
1470 "Expected to be in same basic block!");
1471 auto BeginIt = Begin->getIterator();
1472 assert(BeginIt != End->getIterator() && "Non-empty BB has empty iterator");
1473 return !llvm::isGuaranteedToTransferExecutionToSuccessor(
1474 Begin: ++BeginIt, End: End->getIterator(), ScanLimit: InlinerAttributeWindow + 1);
1475}
1476
1477// Add attributes from CB params and Fn attributes that can always be propagated
1478// to the corresponding argument / inner callbases.
1479static void AddParamAndFnBasicAttributes(const CallBase &CB,
1480 ValueToValueMapTy &VMap,
1481 ClonedCodeInfo &InlinedFunctionInfo) {
1482 auto *CalledFunction = CB.getCalledFunction();
1483 auto &Context = CalledFunction->getContext();
1484
1485 // Collect valid attributes for all params.
1486 SmallVector<AttrBuilder> ValidObjParamAttrs, ValidExactParamAttrs;
1487 bool HasAttrToPropagate = false;
1488
1489 // Attributes we can only propagate if the exact parameter is forwarded.
1490 // We can propagate both poison generating and UB generating attributes
1491 // without any extra checks. The only attribute that is tricky to propagate
1492 // is `noundef` (skipped for now) as that can create new UB where previous
1493 // behavior was just using a poison value.
1494 static const Attribute::AttrKind ExactAttrsToPropagate[] = {
1495 Attribute::Dereferenceable, Attribute::DereferenceableOrNull,
1496 Attribute::NonNull, Attribute::NoFPClass,
1497 Attribute::Alignment, Attribute::Range};
1498
1499 for (unsigned I = 0, E = CB.arg_size(); I < E; ++I) {
1500 ValidObjParamAttrs.emplace_back(Args: AttrBuilder{CB.getContext()});
1501 ValidExactParamAttrs.emplace_back(Args: AttrBuilder{CB.getContext()});
1502 // Access attributes can be propagated to any param with the same underlying
1503 // object as the argument.
1504 if (CB.paramHasAttr(ArgNo: I, Kind: Attribute::ReadNone))
1505 ValidObjParamAttrs.back().addAttribute(Val: Attribute::ReadNone);
1506 if (CB.paramHasAttr(ArgNo: I, Kind: Attribute::ReadOnly))
1507 ValidObjParamAttrs.back().addAttribute(Val: Attribute::ReadOnly);
1508
1509 for (Attribute::AttrKind AK : ExactAttrsToPropagate) {
1510 Attribute Attr = CB.getParamAttr(ArgNo: I, Kind: AK);
1511 if (Attr.isValid())
1512 ValidExactParamAttrs.back().addAttribute(A: Attr);
1513 }
1514
1515 HasAttrToPropagate |= ValidObjParamAttrs.back().hasAttributes();
1516 HasAttrToPropagate |= ValidExactParamAttrs.back().hasAttributes();
1517 }
1518
1519 // Won't be able to propagate anything.
1520 if (!HasAttrToPropagate)
1521 return;
1522
1523 for (BasicBlock &BB : *CalledFunction) {
1524 for (Instruction &Ins : BB) {
1525 const auto *InnerCB = dyn_cast<CallBase>(Val: &Ins);
1526 if (!InnerCB)
1527 continue;
1528 auto *NewInnerCB = dyn_cast_or_null<CallBase>(Val: VMap.lookup(Val: InnerCB));
1529 if (!NewInnerCB)
1530 continue;
1531 // The InnerCB might have be simplified during the inlining
1532 // process which can make propagation incorrect.
1533 if (InlinedFunctionInfo.isSimplified(From: InnerCB, To: NewInnerCB))
1534 continue;
1535
1536 AttributeList AL = NewInnerCB->getAttributes();
1537 for (unsigned I = 0, E = InnerCB->arg_size(); I < E; ++I) {
1538 // It's unsound or requires special handling to propagate
1539 // attributes to byval arguments. Even if CalledFunction
1540 // doesn't e.g. write to the argument (readonly), the call to
1541 // NewInnerCB may write to its by-value copy.
1542 if (NewInnerCB->isByValArgument(ArgNo: I))
1543 continue;
1544
1545 // Don't bother propagating attrs to constants.
1546 if (match(V: NewInnerCB->getArgOperand(i: I),
1547 P: llvm::PatternMatch::m_ImmConstant()))
1548 continue;
1549
1550 // Check if the underlying value for the parameter is an argument.
1551 const Argument *Arg = dyn_cast<Argument>(Val: InnerCB->getArgOperand(i: I));
1552 unsigned ArgNo;
1553 if (Arg) {
1554 ArgNo = Arg->getArgNo();
1555 // For dereferenceable, dereferenceable_or_null, align, etc...
1556 // we don't want to propagate if the existing param has the same
1557 // attribute with "better" constraints. So remove from the
1558 // new AL if the region of the existing param is larger than
1559 // what we can propagate.
1560 AttrBuilder NewAB{
1561 Context, AttributeSet::get(C&: Context, B: ValidExactParamAttrs[ArgNo])};
1562 if (AL.getParamDereferenceableBytes(Index: I) >
1563 NewAB.getDereferenceableBytes())
1564 NewAB.removeAttribute(Val: Attribute::Dereferenceable);
1565 if (AL.getParamDereferenceableOrNullBytes(ArgNo: I) >
1566 NewAB.getDereferenceableOrNullBytes())
1567 NewAB.removeAttribute(Val: Attribute::DereferenceableOrNull);
1568 if (AL.getParamAlignment(ArgNo: I).valueOrOne() >
1569 NewAB.getAlignment().valueOrOne())
1570 NewAB.removeAttribute(Val: Attribute::Alignment);
1571 if (auto ExistingRange = AL.getParamRange(ArgNo: I)) {
1572 if (auto NewRange = NewAB.getRange()) {
1573 ConstantRange CombinedRange =
1574 ExistingRange->intersectWith(CR: *NewRange);
1575 NewAB.removeAttribute(Val: Attribute::Range);
1576 NewAB.addRangeAttr(CR: CombinedRange);
1577 }
1578 }
1579
1580 if (FPClassTest ExistingNoFP = AL.getParamNoFPClass(ArgNo: I))
1581 NewAB.addNoFPClassAttr(NoFPClassMask: ExistingNoFP | NewAB.getNoFPClass());
1582
1583 AL = AL.addParamAttributes(C&: Context, ArgNo: I, B: NewAB);
1584 } else if (NewInnerCB->getArgOperand(i: I)->getType()->isPointerTy()) {
1585 // Check if the underlying value for the parameter is an argument.
1586 const Value *UnderlyingV =
1587 getUnderlyingObject(V: InnerCB->getArgOperand(i: I));
1588 Arg = dyn_cast<Argument>(Val: UnderlyingV);
1589 if (!Arg)
1590 continue;
1591 ArgNo = Arg->getArgNo();
1592 } else {
1593 continue;
1594 }
1595
1596 // If so, propagate its access attributes.
1597 AL = AL.addParamAttributes(C&: Context, ArgNo: I, B: ValidObjParamAttrs[ArgNo]);
1598
1599 // We can have conflicting attributes from the inner callsite and
1600 // to-be-inlined callsite. In that case, choose the most
1601 // restrictive.
1602
1603 // readonly + writeonly means we can never deref so make readnone.
1604 if (AL.hasParamAttr(ArgNo: I, Kind: Attribute::ReadOnly) &&
1605 AL.hasParamAttr(ArgNo: I, Kind: Attribute::WriteOnly))
1606 AL = AL.addParamAttribute(C&: Context, ArgNo: I, Kind: Attribute::ReadNone);
1607
1608 // If have readnone, need to clear readonly/writeonly
1609 if (AL.hasParamAttr(ArgNo: I, Kind: Attribute::ReadNone)) {
1610 AL = AL.removeParamAttribute(C&: Context, ArgNo: I, Kind: Attribute::ReadOnly);
1611 AL = AL.removeParamAttribute(C&: Context, ArgNo: I, Kind: Attribute::WriteOnly);
1612 }
1613
1614 // Writable cannot exist in conjunction w/ readonly/readnone
1615 if (AL.hasParamAttr(ArgNo: I, Kind: Attribute::ReadOnly) ||
1616 AL.hasParamAttr(ArgNo: I, Kind: Attribute::ReadNone))
1617 AL = AL.removeParamAttribute(C&: Context, ArgNo: I, Kind: Attribute::Writable);
1618 }
1619 NewInnerCB->setAttributes(AL);
1620 }
1621 }
1622}
1623
1624// Only allow these white listed attributes to be propagated back to the
1625// callee. This is because other attributes may only be valid on the call
1626// itself, i.e. attributes such as signext and zeroext.
1627
1628// Attributes that are always okay to propagate as if they are violated its
1629// immediate UB.
1630static AttrBuilder IdentifyValidUBGeneratingAttributes(CallBase &CB) {
1631 AttrBuilder Valid(CB.getContext());
1632 if (auto DerefBytes = CB.getRetDereferenceableBytes())
1633 Valid.addDereferenceableAttr(Bytes: DerefBytes);
1634 if (auto DerefOrNullBytes = CB.getRetDereferenceableOrNullBytes())
1635 Valid.addDereferenceableOrNullAttr(Bytes: DerefOrNullBytes);
1636 if (CB.hasRetAttr(Kind: Attribute::NoAlias))
1637 Valid.addAttribute(Val: Attribute::NoAlias);
1638 if (CB.hasRetAttr(Kind: Attribute::NoUndef))
1639 Valid.addAttribute(Val: Attribute::NoUndef);
1640 return Valid;
1641}
1642
1643// Attributes that need additional checks as propagating them may change
1644// behavior or cause new UB.
1645static AttrBuilder IdentifyValidPoisonGeneratingAttributes(CallBase &CB) {
1646 AttrBuilder Valid(CB.getContext());
1647 if (CB.hasRetAttr(Kind: Attribute::NonNull))
1648 Valid.addAttribute(Val: Attribute::NonNull);
1649 if (CB.hasRetAttr(Kind: Attribute::Alignment))
1650 Valid.addAlignmentAttr(Align: CB.getRetAlign());
1651 if (std::optional<ConstantRange> Range = CB.getRange())
1652 Valid.addRangeAttr(CR: *Range);
1653 if (CB.hasRetAttr(Kind: Attribute::NoFPClass))
1654 Valid.addNoFPClassAttr(NoFPClassMask: CB.getRetNoFPClass());
1655 return Valid;
1656}
1657
1658static void AddReturnAttributes(CallBase &CB, ValueToValueMapTy &VMap,
1659 ClonedCodeInfo &InlinedFunctionInfo) {
1660 AttrBuilder CallSiteValidUB = IdentifyValidUBGeneratingAttributes(CB);
1661 AttrBuilder CallSiteValidPG = IdentifyValidPoisonGeneratingAttributes(CB);
1662 if (!CallSiteValidUB.hasAttributes() && !CallSiteValidPG.hasAttributes())
1663 return;
1664 auto *CalledFunction = CB.getCalledFunction();
1665 auto &Context = CalledFunction->getContext();
1666
1667 for (auto &BB : *CalledFunction) {
1668 auto *RI = dyn_cast<ReturnInst>(Val: BB.getTerminator());
1669 if (!RI || !isa<CallBase>(Val: RI->getOperand(i_nocapture: 0)))
1670 continue;
1671 auto *RetVal = cast<CallBase>(Val: RI->getOperand(i_nocapture: 0));
1672 // Check that the cloned RetVal exists and is a call, otherwise we cannot
1673 // add the attributes on the cloned RetVal. Simplification during inlining
1674 // could have transformed the cloned instruction.
1675 auto *NewRetVal = dyn_cast_or_null<CallBase>(Val: VMap.lookup(Val: RetVal));
1676 if (!NewRetVal)
1677 continue;
1678
1679 // The RetVal might have be simplified during the inlining
1680 // process which can make propagation incorrect.
1681 if (InlinedFunctionInfo.isSimplified(From: RetVal, To: NewRetVal))
1682 continue;
1683 // Backward propagation of attributes to the returned value may be incorrect
1684 // if it is control flow dependent.
1685 // Consider:
1686 // @callee {
1687 // %rv = call @foo()
1688 // %rv2 = call @bar()
1689 // if (%rv2 != null)
1690 // return %rv2
1691 // if (%rv == null)
1692 // exit()
1693 // return %rv
1694 // }
1695 // caller() {
1696 // %val = call nonnull @callee()
1697 // }
1698 // Here we cannot add the nonnull attribute on either foo or bar. So, we
1699 // limit the check to both RetVal and RI are in the same basic block and
1700 // there are no throwing/exiting instructions between these instructions.
1701 if (RI->getParent() != RetVal->getParent() ||
1702 MayContainThrowingOrExitingCallAfterCB(Begin: RetVal, End: RI))
1703 continue;
1704 // Add to the existing attributes of NewRetVal, i.e. the cloned call
1705 // instruction.
1706 // NB! When we have the same attribute already existing on NewRetVal, but
1707 // with a differing value, the AttributeList's merge API honours the already
1708 // existing attribute value (i.e. attributes such as dereferenceable,
1709 // dereferenceable_or_null etc). See AttrBuilder::merge for more details.
1710 AttrBuilder ValidUB = IdentifyValidUBGeneratingAttributes(CB);
1711 AttrBuilder ValidPG = IdentifyValidPoisonGeneratingAttributes(CB);
1712 AttributeList AL = NewRetVal->getAttributes();
1713 if (ValidUB.getDereferenceableBytes() < AL.getRetDereferenceableBytes())
1714 ValidUB.removeAttribute(Val: Attribute::Dereferenceable);
1715 if (ValidUB.getDereferenceableOrNullBytes() <
1716 AL.getRetDereferenceableOrNullBytes())
1717 ValidUB.removeAttribute(Val: Attribute::DereferenceableOrNull);
1718 AttributeList NewAL = AL.addRetAttributes(C&: Context, B: ValidUB);
1719 // Attributes that may generate poison returns are a bit tricky. If we
1720 // propagate them, other uses of the callsite might have their behavior
1721 // change or cause UB (if they have noundef) b.c of the new potential
1722 // poison.
1723 // Take the following three cases:
1724 //
1725 // 1)
1726 // define nonnull ptr @foo() {
1727 // %p = call ptr @bar()
1728 // call void @use(ptr %p) willreturn nounwind
1729 // ret ptr %p
1730 // }
1731 //
1732 // 2)
1733 // define noundef nonnull ptr @foo() {
1734 // %p = call ptr @bar()
1735 // call void @use(ptr %p) willreturn nounwind
1736 // ret ptr %p
1737 // }
1738 //
1739 // 3)
1740 // define nonnull ptr @foo() {
1741 // %p = call noundef ptr @bar()
1742 // ret ptr %p
1743 // }
1744 //
1745 // In case 1, we can't propagate nonnull because poison value in @use may
1746 // change behavior or trigger UB.
1747 // In case 2, we don't need to be concerned about propagating nonnull, as
1748 // any new poison at @use will trigger UB anyways.
1749 // In case 3, we can never propagate nonnull because it may create UB due to
1750 // the noundef on @bar.
1751 if (ValidPG.getAlignment().valueOrOne() < AL.getRetAlignment().valueOrOne())
1752 ValidPG.removeAttribute(Val: Attribute::Alignment);
1753 if (ValidPG.hasAttributes()) {
1754 Attribute CBRange = ValidPG.getAttribute(Kind: Attribute::Range);
1755 if (CBRange.isValid()) {
1756 Attribute NewRange = AL.getRetAttr(Kind: Attribute::Range);
1757 if (NewRange.isValid()) {
1758 ValidPG.addRangeAttr(
1759 CR: CBRange.getRange().intersectWith(CR: NewRange.getRange()));
1760 }
1761 }
1762
1763 Attribute CBNoFPClass = ValidPG.getAttribute(Kind: Attribute::NoFPClass);
1764 if (CBNoFPClass.isValid() && AL.hasRetAttr(Kind: Attribute::NoFPClass)) {
1765 ValidPG.addNoFPClassAttr(
1766 NoFPClassMask: CBNoFPClass.getNoFPClass() |
1767 AL.getRetAttr(Kind: Attribute::NoFPClass).getNoFPClass());
1768 }
1769
1770 // Three checks.
1771 // If the callsite has `noundef`, then a poison due to violating the
1772 // return attribute will create UB anyways so we can always propagate.
1773 // Otherwise, if the return value (callee to be inlined) has `noundef`, we
1774 // can't propagate as a new poison return will cause UB.
1775 // Finally, check if the return value has no uses whose behavior may
1776 // change/may cause UB if we potentially return poison. At the moment this
1777 // is implemented overly conservatively with a single-use check.
1778 // TODO: Update the single-use check to iterate through uses and only bail
1779 // if we have a potentially dangerous use.
1780
1781 if (CB.hasRetAttr(Kind: Attribute::NoUndef) ||
1782 (RetVal->hasOneUse() && !RetVal->hasRetAttr(Kind: Attribute::NoUndef)))
1783 NewAL = NewAL.addRetAttributes(C&: Context, B: ValidPG);
1784 }
1785 NewRetVal->setAttributes(NewAL);
1786 }
1787}
1788
1789/// If the inlined function has non-byval align arguments, then
1790/// add @llvm.assume-based alignment assumptions to preserve this information.
1791static void AddAlignmentAssumptions(CallBase &CB, InlineFunctionInfo &IFI) {
1792 if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache)
1793 return;
1794
1795 AssumptionCache *AC = &IFI.GetAssumptionCache(*CB.getCaller());
1796 auto &DL = CB.getDataLayout();
1797
1798 // To avoid inserting redundant assumptions, we should check for assumptions
1799 // already in the caller. To do this, we might need a DT of the caller.
1800 DominatorTree DT;
1801 bool DTCalculated = false;
1802
1803 Function *CalledFunc = CB.getCalledFunction();
1804 for (Argument &Arg : CalledFunc->args()) {
1805 if (!Arg.getType()->isPointerTy() || Arg.hasPassPointeeByValueCopyAttr() ||
1806 Arg.use_empty())
1807 continue;
1808 MaybeAlign Alignment = Arg.getParamAlign();
1809 if (!Alignment)
1810 continue;
1811
1812 if (!DTCalculated) {
1813 DT.recalculate(Func&: *CB.getCaller());
1814 DTCalculated = true;
1815 }
1816 // If we can already prove the asserted alignment in the context of the
1817 // caller, then don't bother inserting the assumption.
1818 Value *ArgVal = CB.getArgOperand(i: Arg.getArgNo());
1819 if (getKnownAlignment(V: ArgVal, DL, CtxI: &CB, AC, DT: &DT) >= *Alignment)
1820 continue;
1821
1822 CallInst *NewAsmp = IRBuilder<>(&CB).CreateAlignmentAssumption(
1823 DL, PtrValue: ArgVal, Alignment: Alignment->value());
1824 AC->registerAssumption(CI: cast<AssumeInst>(Val: NewAsmp));
1825 }
1826}
1827
1828static void HandleByValArgumentInit(Type *ByValType, Value *Dst, Value *Src,
1829 MaybeAlign SrcAlign, Module *M,
1830 BasicBlock *InsertBlock,
1831 InlineFunctionInfo &IFI,
1832 Function *CalledFunc) {
1833 IRBuilder<> Builder(InsertBlock->begin());
1834
1835 Value *Size =
1836 Builder.getInt64(C: M->getDataLayout().getTypeAllocSize(Ty: ByValType));
1837
1838 Align DstAlign = Dst->getPointerAlignment(DL: M->getDataLayout());
1839
1840 // Generate a memcpy with the correct alignments.
1841 CallInst *CI = Builder.CreateMemCpy(Dst, DstAlign, Src, SrcAlign, Size);
1842
1843 // The verifier requires that all calls of debug-info-bearing functions
1844 // from debug-info-bearing functions have a debug location (for inlining
1845 // purposes). Assign a dummy location to satisfy the constraint.
1846 if (!CI->getDebugLoc() && InsertBlock->getParent()->getSubprogram())
1847 if (DISubprogram *SP = CalledFunc->getSubprogram())
1848 CI->setDebugLoc(DILocation::get(Context&: SP->getContext(), Line: 0, Column: 0, Scope: SP));
1849}
1850
1851/// When inlining a call site that has a byval argument,
1852/// we have to make the implicit memcpy explicit by adding it.
1853static Value *HandleByValArgument(Type *ByValType, Value *Arg,
1854 Instruction *TheCall,
1855 const Function *CalledFunc,
1856 InlineFunctionInfo &IFI,
1857 MaybeAlign ByValAlignment) {
1858 Function *Caller = TheCall->getFunction();
1859 const DataLayout &DL = Caller->getDataLayout();
1860
1861 // If the called function is readonly, then it could not mutate the caller's
1862 // copy of the byval'd memory. In this case, it is safe to elide the copy and
1863 // temporary.
1864 if (CalledFunc->onlyReadsMemory()) {
1865 // If the byval argument has a specified alignment that is greater than the
1866 // passed in pointer, then we either have to round up the input pointer or
1867 // give up on this transformation.
1868 if (ByValAlignment.valueOrOne() == 1)
1869 return Arg;
1870
1871 AssumptionCache *AC =
1872 IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr;
1873
1874 // If the pointer is already known to be sufficiently aligned, or if we can
1875 // round it up to a larger alignment, then we don't need a temporary.
1876 if (getOrEnforceKnownAlignment(V: Arg, PrefAlign: *ByValAlignment, DL, CtxI: TheCall, AC) >=
1877 *ByValAlignment)
1878 return Arg;
1879
1880 // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
1881 // for code quality, but rarely happens and is required for correctness.
1882 }
1883
1884 // Create the alloca. If we have DataLayout, use nice alignment.
1885 Align Alignment = DL.getPrefTypeAlign(Ty: ByValType);
1886
1887 // If the byval had an alignment specified, we *must* use at least that
1888 // alignment, as it is required by the byval argument (and uses of the
1889 // pointer inside the callee).
1890 if (ByValAlignment)
1891 Alignment = std::max(a: Alignment, b: *ByValAlignment);
1892
1893 AllocaInst *NewAlloca =
1894 new AllocaInst(ByValType, Arg->getType()->getPointerAddressSpace(),
1895 nullptr, Alignment, Arg->getName());
1896 NewAlloca->setDebugLoc(DebugLoc::getCompilerGenerated());
1897 NewAlloca->insertBefore(InsertPos: Caller->begin()->begin());
1898 IFI.StaticAllocas.push_back(Elt: NewAlloca);
1899
1900 // Uses of the argument in the function should use our new alloca
1901 // instead.
1902 return NewAlloca;
1903}
1904
1905/// Return the result of AI->isStaticAlloca() if AI were moved to the entry
1906/// block. Allocas used in inalloca calls and allocas of dynamic array size
1907/// cannot be static.
1908static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) {
1909 return isa<Constant>(Val: AI->getArraySize()) && !AI->isUsedWithInAlloca();
1910}
1911
1912/// Returns a DebugLoc for a new DILocation which is a clone of \p OrigDL
1913/// inlined at \p InlinedAt. \p IANodes is an inlined-at cache.
1914static DebugLoc inlineDebugLoc(
1915 DebugLoc OrigDL, DILocation *InlinedAt, LLVMContext &Ctx,
1916 DenseMap<const MDNode *, MDNode *> &IANodes,
1917 SmallDenseMap<const DILocation *, DILocation *, 16> &InlineLocs) {
1918 if (DILocation *Cached = InlineLocs.lookup(Val: OrigDL.get()))
1919 return DebugLoc(Cached);
1920 DILocation *IA =
1921 OrigDL->getInlinedAt()
1922 ? DebugLoc::appendInlinedAt(DL: OrigDL, InlinedAt, Ctx, Cache&: IANodes).get()
1923 : InlinedAt;
1924 DILocation *Result = DILocation::getDistinct(
1925 Context&: Ctx, Line: OrigDL.getLine(), Column: OrigDL.getCol(), Scope: OrigDL.getScope(), InlinedAt: IA,
1926 ImplicitCode: OrigDL.isImplicitCode(), AtomGroup: OrigDL->getAtomGroup(), AtomRank: OrigDL->getAtomRank(),
1927 IRLayers: OrigDL.getRawIRLayers());
1928 InlineLocs[OrigDL.get()] = Result;
1929 return DebugLoc(Result);
1930}
1931
1932/// Update inlined instructions' line numbers to
1933/// to encode location where these instructions are inlined.
1934static void fixupLineNumbers(Function *Fn, Function::iterator FI,
1935 Instruction *TheCall, bool CalleeHasDebugInfo) {
1936 if (!TheCall->getDebugLoc())
1937 return;
1938
1939 // Don't propagate the source location atom from the call to inlined nodebug
1940 // instructions, and avoid putting it in the InlinedAt field of inlined
1941 // not-nodebug instructions. FIXME: Possibly worth transferring/generating
1942 // an atom for the returned value, otherwise we miss stepping on inlined
1943 // nodebug functions (which is different to existing behaviour).
1944 DebugLoc TheCallDL = TheCall->getDebugLoc()->getWithoutAtom();
1945
1946 // A call receiving the outer callsite's fallback location has no usable
1947 // callsite probe of its own. Do not let it inherit the outer call's probe
1948 // discriminator, but preserve any packed DWARF base discriminator.
1949 DebugLoc TheCallDLForInlinedCall = TheCallDL;
1950 uint32_t Discriminator = TheCallDLForInlinedCall->getDiscriminator();
1951 if (DILocation::isPseudoProbeDiscriminator(Discriminator)) {
1952 std::optional<uint32_t> DwarfDiscriminator =
1953 PseudoProbeDwarfDiscriminator::extractDwarfBaseDiscriminator(
1954 Value: Discriminator);
1955 TheCallDLForInlinedCall = TheCallDLForInlinedCall->cloneWithDiscriminator(
1956 Discriminator: DwarfDiscriminator.value_or(u: 0));
1957 }
1958
1959 auto &Ctx = Fn->getContext();
1960 DILocation *InlinedAtNode = TheCallDL;
1961
1962 // Create a unique call site, not to be confused with any other call from the
1963 // same location.
1964 // Keep the call site's irlayers: this node ends the inlinedAt chain of
1965 // every location inlined here.
1966 InlinedAtNode = DILocation::getDistinct(
1967 Context&: Ctx, Line: InlinedAtNode->getLine(), Column: InlinedAtNode->getColumn(),
1968 Scope: InlinedAtNode->getScope(), InlinedAt: InlinedAtNode->getInlinedAt(),
1969 /*ImplicitCode=*/false, /*AtomGroup=*/0, /*AtomRank=*/0,
1970 IRLayers: InlinedAtNode->getRawIRLayers());
1971
1972 // Cache the inlined-at nodes as they're built so they are reused, without
1973 // this every instruction's inlined-at chain would become distinct from each
1974 // other.
1975 DenseMap<const MDNode *, MDNode *> IANodes;
1976 SmallDenseMap<const DILocation *, DILocation *, 16> InlineLocs;
1977
1978 // Check if we are not generating inline line tables and want to use
1979 // the call site location instead.
1980 bool NoInlineLineTables = Fn->hasFnAttribute(Kind: "no-inline-line-tables");
1981
1982 // Helper-util for updating the metadata attached to an instruction.
1983 auto UpdateInst = [&](Instruction &I) {
1984 // Loop metadata needs to be updated so that the start and end locs
1985 // reference inlined-at locations.
1986 auto updateLoopInfoLoc = [&Ctx, &InlinedAtNode, &IANodes,
1987 &InlineLocs](Metadata *MD) -> Metadata * {
1988 if (auto *Loc = dyn_cast_or_null<DILocation>(Val: MD))
1989 return inlineDebugLoc(OrigDL: Loc, InlinedAt: InlinedAtNode, Ctx, IANodes, InlineLocs)
1990 .get();
1991 return MD;
1992 };
1993 updateLoopMetadataDebugLocations(I, Updater: updateLoopInfoLoc);
1994
1995 if (!NoInlineLineTables)
1996 if (DebugLoc DL = I.getDebugLoc()) {
1997 DebugLoc IDL = inlineDebugLoc(OrigDL: DL, InlinedAt: InlinedAtNode, Ctx&: I.getContext(),
1998 IANodes, InlineLocs);
1999 I.setDebugLoc(IDL);
2000 return;
2001 }
2002
2003 if (CalleeHasDebugInfo && !NoInlineLineTables)
2004 return;
2005
2006 // If the inlined instruction has no line number, or if inline info
2007 // is not being generated, make it look as if it originates from the call
2008 // location. This is important for ((__always_inline, __nodebug__))
2009 // functions which must use caller location for all instructions in their
2010 // function body.
2011
2012 // Don't update static allocas, as they may get moved later.
2013 if (auto *AI = dyn_cast<AllocaInst>(Val: &I))
2014 if (allocaWouldBeStaticInEntry(AI))
2015 return;
2016
2017 // Do not force a debug loc for pseudo probes, since they do not need to
2018 // be debuggable, and also they are expected to have a zero/null dwarf
2019 // discriminator at this point which could be violated otherwise.
2020 if (isa<PseudoProbeInst>(Val: I))
2021 return;
2022
2023 I.setDebugLoc(isa<CallBase>(Val: I) ? TheCallDLForInlinedCall : TheCallDL);
2024 };
2025
2026 // Helper-util for updating debug-info records attached to instructions.
2027 auto UpdateDVR = [&](DbgRecord *DVR) {
2028 assert(DVR->getDebugLoc() && "Debug Value must have debug loc");
2029 if (NoInlineLineTables) {
2030 DVR->setDebugLoc(TheCallDL);
2031 return;
2032 }
2033 DebugLoc DL = DVR->getDebugLoc();
2034 DebugLoc IDL = inlineDebugLoc(OrigDL: DL, InlinedAt: InlinedAtNode,
2035 Ctx&: DVR->getMarker()->getParent()->getContext(),
2036 IANodes, InlineLocs);
2037 DVR->setDebugLoc(IDL);
2038 };
2039
2040 // Iterate over all instructions, updating metadata and debug-info records.
2041 for (; FI != Fn->end(); ++FI) {
2042 for (Instruction &I : *FI) {
2043 UpdateInst(I);
2044 for (DbgRecord &DVR : I.getDbgRecordRange()) {
2045 UpdateDVR(&DVR);
2046 }
2047 }
2048
2049 // Remove debug info records if we're not keeping inline info.
2050 if (NoInlineLineTables) {
2051 BasicBlock::iterator BI = FI->begin();
2052 while (BI != FI->end()) {
2053 BI->dropDbgRecords();
2054 ++BI;
2055 }
2056 }
2057 }
2058}
2059
2060#undef DEBUG_TYPE
2061#define DEBUG_TYPE "assignment-tracking"
2062/// Find Alloca and linked DbgAssignIntrinsic for locals escaped by \p CB.
2063static at::StorageToVarsMap collectEscapedLocals(const DataLayout &DL,
2064 const CallBase &CB) {
2065 at::StorageToVarsMap EscapedLocals;
2066 SmallPtrSet<const Value *, 4> SeenBases;
2067
2068 LLVM_DEBUG(
2069 errs() << "# Finding caller local variables escaped by callee\n");
2070 for (const Value *Arg : CB.args()) {
2071 LLVM_DEBUG(errs() << "INSPECT: " << *Arg << "\n");
2072 if (!Arg->getType()->isPointerTy()) {
2073 LLVM_DEBUG(errs() << " | SKIP: Not a pointer\n");
2074 continue;
2075 }
2076
2077 const Instruction *I = dyn_cast<Instruction>(Val: Arg);
2078 if (!I) {
2079 LLVM_DEBUG(errs() << " | SKIP: Not result of instruction\n");
2080 continue;
2081 }
2082
2083 // Walk back to the base storage.
2084 assert(Arg->getType()->isPtrOrPtrVectorTy());
2085 APInt TmpOffset(DL.getIndexTypeSizeInBits(Ty: Arg->getType()), 0, false);
2086 const AllocaInst *Base = dyn_cast<AllocaInst>(
2087 Val: Arg->stripAndAccumulateConstantOffsets(DL, Offset&: TmpOffset, AllowNonInbounds: true));
2088 if (!Base) {
2089 LLVM_DEBUG(errs() << " | SKIP: Couldn't walk back to base storage\n");
2090 continue;
2091 }
2092
2093 assert(Base);
2094 LLVM_DEBUG(errs() << " | BASE: " << *Base << "\n");
2095 // We only need to process each base address once - skip any duplicates.
2096 if (!SeenBases.insert(Ptr: Base).second)
2097 continue;
2098
2099 // Find all local variables associated with the backing storage.
2100 auto CollectAssignsForStorage = [&](DbgVariableRecord *DbgAssign) {
2101 // Skip variables from inlined functions - they are not local variables.
2102 if (DbgAssign->getDebugLoc().getInlinedAt())
2103 return;
2104 LLVM_DEBUG(errs() << " > DEF : " << *DbgAssign << "\n");
2105 EscapedLocals[Base].insert(X: at::VarRecord(DbgAssign));
2106 };
2107 for_each(Range: at::getDVRAssignmentMarkers(Inst: Base), F: CollectAssignsForStorage);
2108 }
2109 return EscapedLocals;
2110}
2111
2112static void trackInlinedStores(Function::iterator Start, Function::iterator End,
2113 const CallBase &CB) {
2114 LLVM_DEBUG(errs() << "trackInlinedStores into "
2115 << Start->getParent()->getName() << " from "
2116 << CB.getCalledFunction()->getName() << "\n");
2117 const DataLayout &DL = CB.getDataLayout();
2118 at::trackAssignments(Start, End, Vars: collectEscapedLocals(DL, CB), DL);
2119}
2120
2121/// Update inlined instructions' DIAssignID metadata. We need to do this
2122/// otherwise a function inlined more than once into the same function
2123/// will cause DIAssignID to be shared by many instructions.
2124static void fixupAssignments(Function::iterator Start, Function::iterator End) {
2125 DenseMap<DIAssignID *, DIAssignID *> Map;
2126 // Loop over all the inlined instructions. If we find a DIAssignID
2127 // attachment or use, replace it with a new version.
2128 for (auto BBI = Start; BBI != End; ++BBI) {
2129 for (Instruction &I : *BBI)
2130 at::remapAssignID(Map, I);
2131 }
2132}
2133#undef DEBUG_TYPE
2134#define DEBUG_TYPE "inline-function"
2135
2136/// Update the block frequencies of the caller after a callee has been inlined.
2137///
2138/// Each block cloned into the caller has its block frequency scaled by the
2139/// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of
2140/// callee's entry block gets the same frequency as the callsite block and the
2141/// relative frequencies of all cloned blocks remain the same after cloning.
2142static void updateCallerBFI(BasicBlock *CallSiteBlock,
2143 const ValueToValueMapTy &VMap,
2144 BlockFrequencyInfo *CallerBFI,
2145 BlockFrequencyInfo *CalleeBFI,
2146 const BasicBlock &CalleeEntryBlock) {
2147 SmallPtrSet<BasicBlock *, 16> ClonedBBs;
2148 for (auto Entry : VMap) {
2149 if (!isa<BasicBlock>(Val: Entry.first) || !Entry.second)
2150 continue;
2151 auto *OrigBB = cast<BasicBlock>(Val: Entry.first);
2152 auto *ClonedBB = cast<BasicBlock>(Val: Entry.second);
2153 BlockFrequency Freq = CalleeBFI->getBlockFreq(BB: OrigBB);
2154 if (!ClonedBBs.insert(Ptr: ClonedBB).second) {
2155 // Multiple blocks in the callee might get mapped to one cloned block in
2156 // the caller since we prune the callee as we clone it. When that happens,
2157 // we want to use the maximum among the original blocks' frequencies.
2158 BlockFrequency NewFreq = CallerBFI->getBlockFreq(BB: ClonedBB);
2159 if (NewFreq > Freq)
2160 Freq = NewFreq;
2161 }
2162 CallerBFI->setBlockFreq(BB: ClonedBB, Freq);
2163 }
2164 BasicBlock *EntryClone = cast<BasicBlock>(Val: VMap.lookup(Val: &CalleeEntryBlock));
2165 CallerBFI->setBlockFreqAndScale(
2166 ReferenceBB: EntryClone, Freq: CallerBFI->getBlockFreq(BB: CallSiteBlock), BlocksToScale&: ClonedBBs);
2167}
2168
2169/// Update the branch metadata for cloned call instructions.
2170static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap,
2171 const uint64_t &CalleeEntryCount,
2172 const CallBase &TheCall, ProfileSummaryInfo *PSI,
2173 BlockFrequencyInfo *CallerBFI) {
2174 if (CalleeEntryCount < 1)
2175 return;
2176 auto CallSiteCount =
2177 PSI ? PSI->getProfileCount(CallInst: TheCall, BFI: CallerBFI) : std::nullopt;
2178 int64_t CallCount = std::min(a: CallSiteCount.value_or(u: 0), b: CalleeEntryCount);
2179 updateProfileCallee(Callee, EntryDelta: -CallCount, VMap: &VMap);
2180}
2181
2182void llvm::updateProfileCallee(
2183 Function *Callee, int64_t EntryDelta,
2184 const ValueMap<const Value *, WeakTrackingVH> *VMap) {
2185 auto CalleeCount = Callee->getEntryCount();
2186 if (!CalleeCount)
2187 return;
2188
2189 // Since CallSiteCount is an estimate, it could exceed the original callee
2190 // count and has to be set to 0 so guard against underflow.
2191 const uint64_t NewEntryCount =
2192 (EntryDelta < 0 && static_cast<uint64_t>(-EntryDelta) > *CalleeCount)
2193 ? 0
2194 : *CalleeCount + EntryDelta;
2195
2196 auto updateVTableProfWeight = [](CallBase *CB, const uint64_t NewEntryCount,
2197 const uint64_t PriorEntryCount) {
2198 Instruction *VPtr = PGOIndirectCallVisitor::tryGetVTableInstruction(CB);
2199 if (VPtr)
2200 scaleProfData(I&: *VPtr, S: NewEntryCount, T: PriorEntryCount);
2201 };
2202
2203 // During inlining ?
2204 if (VMap) {
2205 uint64_t CloneEntryCount = *CalleeCount - NewEntryCount;
2206 for (auto Entry : *VMap) {
2207 if (isa<CallInst>(Val: Entry.first))
2208 if (auto *CI = dyn_cast_or_null<CallInst>(Val: Entry.second)) {
2209 CI->updateProfWeight(S: CloneEntryCount, T: *CalleeCount);
2210 updateVTableProfWeight(CI, CloneEntryCount, *CalleeCount);
2211 }
2212
2213 if (isa<InvokeInst>(Val: Entry.first))
2214 if (auto *II = dyn_cast_or_null<InvokeInst>(Val: Entry.second)) {
2215 II->updateProfWeight(S: CloneEntryCount, T: *CalleeCount);
2216 updateVTableProfWeight(II, CloneEntryCount, *CalleeCount);
2217 }
2218 }
2219 }
2220
2221 if (EntryDelta) {
2222 Callee->setEntryCount(Count: NewEntryCount);
2223
2224 for (BasicBlock &BB : *Callee)
2225 // No need to update the callsite if it is pruned during inlining.
2226 if (!VMap || VMap->count(Val: &BB))
2227 for (Instruction &I : BB) {
2228 if (CallInst *CI = dyn_cast<CallInst>(Val: &I)) {
2229 CI->updateProfWeight(S: NewEntryCount, T: *CalleeCount);
2230 updateVTableProfWeight(CI, NewEntryCount, *CalleeCount);
2231 }
2232 if (InvokeInst *II = dyn_cast<InvokeInst>(Val: &I)) {
2233 II->updateProfWeight(S: NewEntryCount, T: *CalleeCount);
2234 updateVTableProfWeight(II, NewEntryCount, *CalleeCount);
2235 }
2236 }
2237 }
2238}
2239
2240/// An operand bundle "clang.arc.attachedcall" on a call indicates the call
2241/// result is implicitly consumed by a call to retainRV/claimRV/unsafeClaimRV
2242/// immediately after the call. This function inlines those consuming calls.
2243///
2244/// There are three cases to consider:
2245///
2246/// 1. If there is a call to autoreleaseRV that takes a pointer to the returned
2247/// object in the callee return block, the autoreleaseRV call and the
2248/// retainRV/claimRV/unsafeClaimRV call in the caller cancel out. If the call
2249/// in the caller is an unsafeClaimRV call, a call to objc_release is
2250/// emitted.
2251///
2252/// 2. If there is a call in the callee return block that doesn't have operand
2253/// bundle "clang.arc.attachedcall", the operand bundle on the original call
2254/// is transferred to the call in the callee.
2255///
2256/// 3. Otherwise, a call to objc_retain is inserted if the call in the caller is
2257/// not an unsafeClaimRV call.
2258static void
2259inlineRetainOrClaimRVCalls(CallBase &CB, objcarc::ARCInstKind RVCallKind,
2260 const SmallVectorImpl<ReturnInst *> &Returns) {
2261 assert(objcarc::isRetainOrClaimRV(RVCallKind) && "unexpected ARC function");
2262 bool IsUnsafeClaimRV = RVCallKind == objcarc::ARCInstKind::UnsafeClaimRV;
2263
2264 for (auto *RI : Returns) {
2265 Value *RetOpnd = objcarc::GetRCIdentityRoot(V: RI->getOperand(i_nocapture: 0));
2266 bool InsertRetainCall = !IsUnsafeClaimRV;
2267 IRBuilder<> Builder(*RI->getModule());
2268
2269 // Walk backwards through the basic block looking for either a matching
2270 // autoreleaseRV call or an unannotated call.
2271 auto InstRange = llvm::make_range(x: ++(RI->getIterator().getReverse()),
2272 y: RI->getParent()->rend());
2273 for (Instruction &I : llvm::make_early_inc_range(Range&: InstRange)) {
2274 // Ignore casts.
2275 if (isa<CastInst>(Val: I))
2276 continue;
2277
2278 if (auto *II = dyn_cast<IntrinsicInst>(Val: &I)) {
2279 if (II->getIntrinsicID() != Intrinsic::objc_autoreleaseReturnValue ||
2280 !II->use_empty() ||
2281 objcarc::GetRCIdentityRoot(V: II->getOperand(i_nocapture: 0)) != RetOpnd)
2282 break;
2283
2284 // If we've found a matching authoreleaseRV call:
2285 // - If unsafeClaimRV is attached to the call, insert a call to
2286 // objc_release and erase the autoreleaseRV call.
2287 // - If retainRV/claimRV is attached to the call, just erase the
2288 // autoreleaseRV call.
2289 if (IsUnsafeClaimRV) {
2290 Builder.SetInsertPoint(II);
2291 Builder.CreateIntrinsic(ID: Intrinsic::objc_release, Args: RetOpnd);
2292 }
2293 II->eraseFromParent();
2294 InsertRetainCall = false;
2295 break;
2296 }
2297
2298 auto *CI = dyn_cast<CallInst>(Val: &I);
2299
2300 if (!CI)
2301 break;
2302
2303 if (objcarc::GetRCIdentityRoot(V: CI) != RetOpnd ||
2304 objcarc::hasAttachedCallOpBundle(CB: CI))
2305 break;
2306
2307 // If we've found an unannotated call that defines RetOpnd, add a
2308 // "clang.arc.attachedcall" operand bundle.
2309 Value *BundleArgs[] = {*objcarc::getAttachedARCFunction(CB: &CB)};
2310 OperandBundleDef OB("clang.arc.attachedcall", BundleArgs);
2311 auto *NewCall = CallBase::addOperandBundle(
2312 CB: CI, ID: LLVMContext::OB_clang_arc_attachedcall, OB, InsertPt: CI->getIterator());
2313 NewCall->copyMetadata(SrcInst: *CI);
2314 CI->replaceAllUsesWith(V: NewCall);
2315 CI->eraseFromParent();
2316 InsertRetainCall = false;
2317 break;
2318 }
2319
2320 if (InsertRetainCall) {
2321 // The retainRV is attached to the call and we've failed to find a
2322 // matching autoreleaseRV or an annotated call in the callee. Emit a call
2323 // to objc_retain.
2324 Builder.SetInsertPoint(RI);
2325 Builder.CreateIntrinsic(ID: Intrinsic::objc_retain, Args: RetOpnd);
2326 }
2327 }
2328}
2329
2330// In contextual profiling, when an inline succeeds, we want to remap the
2331// indices of the callee into the index space of the caller. We can't just leave
2332// them as-is because the same callee may appear in other places in this caller
2333// (other callsites), and its (callee's) counters and sub-contextual profile
2334// tree would be potentially different.
2335// Not all BBs of the callee may survive the opportunistic DCE InlineFunction
2336// does (same goes for callsites in the callee).
2337// We will return a pair of vectors, one for basic block IDs and one for
2338// callsites. For such a vector V, V[Idx] will be -1 if the callee
2339// instrumentation with index Idx did not survive inlining, and a new value
2340// otherwise.
2341// This function will update the caller's instrumentation intrinsics
2342// accordingly, mapping indices as described above. We also replace the "name"
2343// operand because we use it to distinguish between "own" instrumentation and
2344// "from callee" instrumentation when performing the traversal of the CFG of the
2345// caller. We traverse depth-first from the callsite's BB and up to the point we
2346// hit BBs owned by the caller.
2347// The return values will be then used to update the contextual
2348// profile. Note: we only update the "name" and "index" operands in the
2349// instrumentation intrinsics, we leave the hash and total nr of indices as-is,
2350// it's not worth updating those.
2351static std::pair<std::vector<int64_t>, std::vector<int64_t>>
2352remapIndices(Function &Caller, BasicBlock *StartBB,
2353 PGOContextualProfile &CtxProf, uint32_t CalleeCounters,
2354 uint32_t CalleeCallsites) {
2355 // We'll allocate a new ID to imported callsite counters and callsites. We're
2356 // using -1 to indicate a counter we delete. Most likely the entry ID, for
2357 // example, will be deleted - we don't want 2 IDs in the same BB, and the
2358 // entry would have been cloned in the callsite's old BB.
2359 std::vector<int64_t> CalleeCounterMap;
2360 std::vector<int64_t> CalleeCallsiteMap;
2361 CalleeCounterMap.resize(new_size: CalleeCounters, x: -1);
2362 CalleeCallsiteMap.resize(new_size: CalleeCallsites, x: -1);
2363
2364 auto RewriteInstrIfNeeded = [&](InstrProfIncrementInst &Ins) -> bool {
2365 if (Ins.getNameValue() == &Caller)
2366 return false;
2367 const auto OldID = static_cast<uint32_t>(Ins.getIndex()->getZExtValue());
2368 if (CalleeCounterMap[OldID] == -1)
2369 CalleeCounterMap[OldID] = CtxProf.allocateNextCounterIndex(F: Caller);
2370 const auto NewID = static_cast<uint32_t>(CalleeCounterMap[OldID]);
2371
2372 Ins.setNameValue(&Caller);
2373 Ins.setIndex(NewID);
2374 return true;
2375 };
2376
2377 auto RewriteCallsiteInsIfNeeded = [&](InstrProfCallsite &Ins) -> bool {
2378 if (Ins.getNameValue() == &Caller)
2379 return false;
2380 const auto OldID = static_cast<uint32_t>(Ins.getIndex()->getZExtValue());
2381 if (CalleeCallsiteMap[OldID] == -1)
2382 CalleeCallsiteMap[OldID] = CtxProf.allocateNextCallsiteIndex(F: Caller);
2383 const auto NewID = static_cast<uint32_t>(CalleeCallsiteMap[OldID]);
2384
2385 Ins.setNameValue(&Caller);
2386 Ins.setIndex(NewID);
2387 return true;
2388 };
2389
2390 std::deque<BasicBlock *> Worklist;
2391 DenseSet<const BasicBlock *> Seen;
2392 // We will traverse the BBs starting from the callsite BB. The callsite BB
2393 // will have at least a BB ID - maybe its own, and in any case the one coming
2394 // from the cloned function's entry BB. The other BBs we'll start seeing from
2395 // there on may or may not have BB IDs. BBs with IDs belonging to our caller
2396 // are definitely not coming from the imported function and form a boundary
2397 // past which we don't need to traverse anymore. BBs may have no
2398 // instrumentation (because we originally inserted instrumentation as per
2399 // MST), in which case we'll traverse past them. An invariant we'll keep is
2400 // that a BB will have at most 1 BB ID. For example, in the callsite BB, we
2401 // will delete the callee BB's instrumentation. This doesn't result in
2402 // information loss: the entry BB of the callee will have the same count as
2403 // the callsite's BB. At the end of this traversal, all the callee's
2404 // instrumentation would be mapped into the caller's instrumentation index
2405 // space. Some of the callee's counters may be deleted (as mentioned, this
2406 // should result in no loss of information).
2407 Worklist.push_back(x: StartBB);
2408 while (!Worklist.empty()) {
2409 auto *BB = Worklist.front();
2410 Worklist.pop_front();
2411 bool Changed = false;
2412 auto *BBID = CtxProfAnalysis::getBBInstrumentation(BB&: *BB);
2413 if (BBID) {
2414 Changed |= RewriteInstrIfNeeded(*BBID);
2415 // this may be the entryblock from the inlined callee, coming into a BB
2416 // that didn't have instrumentation because of MST decisions. Let's make
2417 // sure it's placed accordingly. This is a noop elsewhere.
2418 BBID->moveBefore(InsertPos: BB->getFirstInsertionPt());
2419 }
2420 for (auto &I : llvm::make_early_inc_range(Range&: *BB)) {
2421 if (auto *Inc = dyn_cast<InstrProfIncrementInst>(Val: &I)) {
2422 if (isa<InstrProfIncrementInstStep>(Val: Inc)) {
2423 // Step instrumentation is used for select instructions. Inlining may
2424 // have propagated a constant resulting in the condition of the select
2425 // being resolved, case in which function cloning resolves the value
2426 // of the select, and elides the select instruction. If that is the
2427 // case, the step parameter of the instrumentation will reflect that.
2428 // We can delete the instrumentation in that case.
2429 if (isa<Constant>(Val: Inc->getStep())) {
2430 assert(!Inc->getNextNode() || !isa<SelectInst>(Inc->getNextNode()));
2431 Inc->eraseFromParent();
2432 } else {
2433 assert(isa_and_nonnull<SelectInst>(Inc->getNextNode()));
2434 RewriteInstrIfNeeded(*Inc);
2435 }
2436 } else if (Inc != BBID) {
2437 // If we're here it means that the BB had more than 1 IDs, presumably
2438 // some coming from the callee. We "made up our mind" to keep the
2439 // first one (which may or may not have been originally the caller's).
2440 // All the others are superfluous and we delete them.
2441 Inc->eraseFromParent();
2442 Changed = true;
2443 }
2444 } else if (auto *CS = dyn_cast<InstrProfCallsite>(Val: &I)) {
2445 Changed |= RewriteCallsiteInsIfNeeded(*CS);
2446 }
2447 }
2448 if (!BBID || Changed)
2449 for (auto *Succ : successors(BB))
2450 if (Seen.insert(V: Succ).second)
2451 Worklist.push_back(x: Succ);
2452 }
2453
2454 assert(!llvm::is_contained(CalleeCounterMap, 0) &&
2455 "Counter index mapping should be either to -1 or to non-zero index, "
2456 "because the 0 "
2457 "index corresponds to the entry BB of the caller");
2458 assert(!llvm::is_contained(CalleeCallsiteMap, 0) &&
2459 "Callsite index mapping should be either to -1 or to non-zero index, "
2460 "because there should have been at least a callsite - the inlined one "
2461 "- which would have had a 0 index.");
2462
2463 return {std::move(CalleeCounterMap), std::move(CalleeCallsiteMap)};
2464}
2465
2466// Inline. If successful, update the contextual profile (if a valid one is
2467// given).
2468// The contextual profile data is organized in trees, as follows:
2469// - each node corresponds to a function
2470// - the root of each tree corresponds to an "entrypoint" - e.g.
2471// RPC handler for server side
2472// - the path from the root to a node is a particular call path
2473// - the counters stored in a node are counter values observed in that
2474// particular call path ("context")
2475// - the edges between nodes are annotated with callsite IDs.
2476//
2477// Updating the contextual profile after an inlining means, at a high level,
2478// copying over the data of the callee, **intentionally without any value
2479// scaling**, and copying over the callees of the inlined callee.
2480llvm::InlineResult
2481llvm::InlineFunction(CallBase &CB, InlineFunctionInfo &IFI,
2482 PGOContextualProfile &CtxProf, bool MergeAttributes,
2483 AAResults *CalleeAAR, bool InsertLifetime,
2484 bool TrackInlineHistory, Function *ForwardVarArgsTo,
2485 OptimizationRemarkEmitter *ORE) {
2486 if (!CtxProf.isInSpecializedModule())
2487 return InlineFunction(CB, IFI, MergeAttributes, CalleeAAR, InsertLifetime,
2488 TrackInlineHistory, ForwardVarArgsTo, ORE);
2489
2490 auto &Caller = *CB.getCaller();
2491 auto &Callee = *CB.getCalledFunction();
2492 auto *StartBB = CB.getParent();
2493
2494 // Get some preliminary data about the callsite before it might get inlined.
2495 // Inlining shouldn't delete the callee, but it's cleaner (and low-cost) to
2496 // get this data upfront and rely less on InlineFunction's behavior.
2497 const auto CalleeGUID = Callee.getGUID();
2498 auto *CallsiteIDIns = CtxProfAnalysis::getCallsiteInstrumentation(CB);
2499 const auto CallsiteID =
2500 static_cast<uint32_t>(CallsiteIDIns->getIndex()->getZExtValue());
2501
2502 const auto NumCalleeCounters = CtxProf.getNumCounters(F: Callee);
2503 const auto NumCalleeCallsites = CtxProf.getNumCallsites(F: Callee);
2504
2505 auto Ret = InlineFunction(CB, IFI, MergeAttributes, CalleeAAR, InsertLifetime,
2506 TrackInlineHistory, ForwardVarArgsTo, ORE);
2507 if (!Ret.isSuccess())
2508 return Ret;
2509
2510 // Inlining succeeded, we don't need the instrumentation of the inlined
2511 // callsite.
2512 CallsiteIDIns->eraseFromParent();
2513
2514 // Assinging Maps and then capturing references into it in the lambda because
2515 // captured structured bindings are a C++20 extension. We do also need a
2516 // capture here, though.
2517 const auto IndicesMaps = remapIndices(Caller, StartBB, CtxProf,
2518 CalleeCounters: NumCalleeCounters, CalleeCallsites: NumCalleeCallsites);
2519 const uint32_t NewCountersSize = CtxProf.getNumCounters(F: Caller);
2520
2521 auto Updater = [&](PGOCtxProfContext &Ctx) {
2522 assert(Ctx.guid() == Caller.getGUID());
2523 const auto &[CalleeCounterMap, CalleeCallsiteMap] = IndicesMaps;
2524 assert(
2525 (Ctx.counters().size() +
2526 llvm::count_if(CalleeCounterMap, [](auto V) { return V != -1; }) ==
2527 NewCountersSize) &&
2528 "The caller's counters size should have grown by the number of new "
2529 "distinct counters inherited from the inlined callee.");
2530 Ctx.resizeCounters(Size: NewCountersSize);
2531 // If the callsite wasn't exercised in this context, the value of the
2532 // counters coming from it is 0 - which it is right now, after resizing them
2533 // - and so we're done.
2534 auto CSIt = Ctx.callsites().find(x: CallsiteID);
2535 if (CSIt == Ctx.callsites().end())
2536 return;
2537 auto CalleeCtxIt = CSIt->second.find(x: CalleeGUID);
2538 // The callsite was exercised, but not with this callee (so presumably this
2539 // is an indirect callsite). Again, we're done here.
2540 if (CalleeCtxIt == CSIt->second.end())
2541 return;
2542
2543 // Let's pull in the counter values and the subcontexts coming from the
2544 // inlined callee.
2545 auto &CalleeCtx = CalleeCtxIt->second;
2546 assert(CalleeCtx.guid() == CalleeGUID);
2547
2548 for (auto I = 0U; I < CalleeCtx.counters().size(); ++I) {
2549 const int64_t NewIndex = CalleeCounterMap[I];
2550 if (NewIndex >= 0) {
2551 assert(NewIndex != 0 && "counter index mapping shouldn't happen to a 0 "
2552 "index, that's the caller's entry BB");
2553 Ctx.counters()[NewIndex] = CalleeCtx.counters()[I];
2554 }
2555 }
2556 for (auto &[I, OtherSet] : CalleeCtx.callsites()) {
2557 const int64_t NewCSIdx = CalleeCallsiteMap[I];
2558 if (NewCSIdx >= 0) {
2559 assert(NewCSIdx != 0 &&
2560 "callsite index mapping shouldn't happen to a 0 index, the "
2561 "caller must've had at least one callsite (with such an index)");
2562 Ctx.ingestAllContexts(CSId: NewCSIdx, Other: std::move(OtherSet));
2563 }
2564 }
2565 // We know the traversal is preorder, so it wouldn't have yet looked at the
2566 // sub-contexts of this context that it's currently visiting. Meaning, the
2567 // erase below invalidates no iterators.
2568 auto Deleted = Ctx.callsites().erase(x: CallsiteID);
2569 assert(Deleted);
2570 (void)Deleted;
2571 };
2572 CtxProf.update(Updater, F: Caller);
2573 return Ret;
2574}
2575
2576llvm::InlineResult llvm::CanInlineCallSite(const CallBase &CB,
2577 InlineFunctionInfo &IFI) {
2578 assert(CB.getParent() && CB.getFunction() && "Instruction not in function!");
2579
2580 // FIXME: we don't inline callbr yet.
2581 if (isa<CallBrInst>(Val: CB))
2582 return InlineResult::failure(Reason: "We don't inline callbr yet.");
2583
2584 // If IFI has any state in it, zap it before we fill it in.
2585 IFI.reset();
2586
2587 Function *CalledFunc = CB.getCalledFunction();
2588 if (!CalledFunc || // Can't inline external function or indirect
2589 CalledFunc->isDeclaration()) // call!
2590 return InlineResult::failure(Reason: "external or indirect");
2591
2592 // Don't inline if we've already inlined this callee through this call site
2593 // before to prevent infinite inlining through mutually recursive functions.
2594 if (MDNode *InlineHistory = CB.getMetadata(KindID: LLVMContext::MD_inline_history)) {
2595 for (const auto &Op : InlineHistory->operands()) {
2596 if (auto *MD = dyn_cast_or_null<ValueAsMetadata>(Val: Op)) {
2597 if (MD->getValue() == CalledFunc) {
2598 return InlineResult::failure(Reason: "inline history");
2599 }
2600 }
2601 }
2602 }
2603
2604 // The inliner does not know how to inline through calls with operand bundles
2605 // in general ...
2606 if (CB.hasOperandBundles()) {
2607 for (int i = 0, e = CB.getNumOperandBundles(); i != e; ++i) {
2608 auto OBUse = CB.getOperandBundleAt(Index: i);
2609 uint32_t Tag = OBUse.getTagID();
2610 // ... but it knows how to inline through "deopt" operand bundles ...
2611 if (Tag == LLVMContext::OB_deopt)
2612 continue;
2613 // ... and "funclet" operand bundles.
2614 if (Tag == LLVMContext::OB_funclet)
2615 continue;
2616 if (Tag == LLVMContext::OB_clang_arc_attachedcall)
2617 continue;
2618 if (Tag == LLVMContext::OB_kcfi)
2619 continue;
2620 if (Tag == LLVMContext::OB_convergencectrl) {
2621 IFI.ConvergenceControlToken = OBUse.Inputs[0].get();
2622 continue;
2623 }
2624
2625 return InlineResult::failure(Reason: "unsupported operand bundle");
2626 }
2627 }
2628
2629 // FIXME: The check below is redundant and incomplete. According to spec, if a
2630 // convergent call is missing a token, then the caller is using uncontrolled
2631 // convergence. If the callee has an entry intrinsic, then the callee is using
2632 // controlled convergence, and the call cannot be inlined. A proper
2633 // implemenation of this check requires a whole new analysis that identifies
2634 // convergence in every function. For now, we skip that and just do this one
2635 // cursory check. The underlying assumption is that in a compiler flow that
2636 // fully implements convergence control tokens, there is no mixing of
2637 // controlled and uncontrolled convergent operations in the whole program.
2638 if (CB.isConvergent()) {
2639 if (!IFI.ConvergenceControlToken &&
2640 getConvergenceEntry(BB&: CalledFunc->getEntryBlock())) {
2641 return InlineResult::failure(
2642 Reason: "convergent call needs convergencectrl operand");
2643 }
2644 }
2645
2646 const BasicBlock *OrigBB = CB.getParent();
2647 const Function *Caller = OrigBB->getParent();
2648
2649 // GC poses two hazards to inlining, which only occur when the callee has GC:
2650 // 1. If the caller has no GC, then the callee's GC must be propagated to the
2651 // caller.
2652 // 2. If the caller has a differing GC, it is invalid to inline.
2653 if (CalledFunc->hasGC()) {
2654 if (Caller->hasGC() && CalledFunc->getGC() != Caller->getGC())
2655 return InlineResult::failure(Reason: "incompatible GC");
2656 }
2657
2658 // Get the personality function from the callee if it contains a landing pad.
2659 Constant *CalledPersonality =
2660 CalledFunc->hasPersonalityFn()
2661 ? CalledFunc->getPersonalityFn()->stripPointerCasts()
2662 : nullptr;
2663
2664 // Find the personality function used by the landing pads of the caller. If it
2665 // exists, then check to see that it matches the personality function used in
2666 // the callee.
2667 Constant *CallerPersonality =
2668 Caller->hasPersonalityFn()
2669 ? Caller->getPersonalityFn()->stripPointerCasts()
2670 : nullptr;
2671 if (CalledPersonality) {
2672 // If the personality functions match, then we can perform the
2673 // inlining. Otherwise, we can't inline.
2674 // TODO: This isn't 100% true. Some personality functions are proper
2675 // supersets of others and can be used in place of the other.
2676 if (CallerPersonality && CalledPersonality != CallerPersonality)
2677 return InlineResult::failure(Reason: "incompatible personality");
2678 }
2679
2680 // We need to figure out which funclet the callsite was in so that we may
2681 // properly nest the callee.
2682 if (CallerPersonality) {
2683 EHPersonality Personality = classifyEHPersonality(Pers: CallerPersonality);
2684 if (isScopedEHPersonality(Pers: Personality)) {
2685 std::optional<OperandBundleUse> ParentFunclet =
2686 CB.getOperandBundle(ID: LLVMContext::OB_funclet);
2687 if (ParentFunclet)
2688 IFI.CallSiteEHPad = cast<FuncletPadInst>(Val: ParentFunclet->Inputs.front());
2689
2690 // OK, the inlining site is legal. What about the target function?
2691
2692 if (IFI.CallSiteEHPad) {
2693 if (Personality == EHPersonality::MSVC_CXX) {
2694 // The MSVC personality cannot tolerate catches getting inlined into
2695 // cleanup funclets.
2696 if (isa<CleanupPadInst>(Val: IFI.CallSiteEHPad)) {
2697 // Ok, the call site is within a cleanuppad. Let's check the callee
2698 // for catchpads.
2699 for (const BasicBlock &CalledBB : *CalledFunc) {
2700 if (isa<CatchSwitchInst>(Val: CalledBB.getFirstNonPHIIt()))
2701 return InlineResult::failure(Reason: "catch in cleanup funclet");
2702 }
2703 }
2704 } else if (isAsynchronousEHPersonality(Pers: Personality)) {
2705 // SEH is even less tolerant, there may not be any sort of exceptional
2706 // funclet in the callee.
2707 for (const BasicBlock &CalledBB : *CalledFunc) {
2708 if (CalledBB.isEHPad())
2709 return InlineResult::failure(Reason: "SEH in cleanup funclet");
2710 }
2711 }
2712 }
2713 }
2714 }
2715
2716 return InlineResult::success();
2717}
2718
2719/// This function inlines the called function into the basic block of the
2720/// caller. This returns false if it is not possible to inline this call.
2721/// The program is still in a well defined state if this occurs though.
2722///
2723/// Note that this only does one level of inlining. For example, if the
2724/// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
2725/// exists in the instruction stream. Similarly this will inline a recursive
2726/// function by one level.
2727void llvm::InlineFunctionImpl(CallBase &CB, InlineFunctionInfo &IFI,
2728 bool MergeAttributes, AAResults *CalleeAAR,
2729 bool InsertLifetime, bool TrackInlineHistory,
2730 Function *ForwardVarArgsTo,
2731 OptimizationRemarkEmitter *ORE) {
2732 BasicBlock *OrigBB = CB.getParent();
2733 Function *Caller = OrigBB->getParent();
2734 Function *CalledFunc = CB.getCalledFunction();
2735 assert(CalledFunc && !CalledFunc->isDeclaration() &&
2736 "CanInlineCallSite should have verified direct call to definition");
2737
2738 // Determine if we are dealing with a call in an EHPad which does not unwind
2739 // to caller.
2740 bool EHPadForCallUnwindsLocally = false;
2741 if (IFI.CallSiteEHPad && isa<CallInst>(Val: CB)) {
2742 UnwindDestMemoTy FuncletUnwindMap;
2743 Value *CallSiteUnwindDestToken =
2744 getUnwindDestToken(EHPad: IFI.CallSiteEHPad, MemoMap&: FuncletUnwindMap);
2745
2746 EHPadForCallUnwindsLocally =
2747 CallSiteUnwindDestToken &&
2748 !isa<ConstantTokenNone>(Val: CallSiteUnwindDestToken);
2749 }
2750
2751 // Get an iterator to the last basic block in the function, which will have
2752 // the new function inlined after it.
2753 Function::iterator LastBlock = --Caller->end();
2754
2755 // Make sure to capture all of the return instructions from the cloned
2756 // function.
2757 SmallVector<ReturnInst*, 8> Returns;
2758 ClonedCodeInfo InlinedFunctionInfo;
2759 Function::iterator FirstNewBlock;
2760
2761 // GC poses two hazards to inlining, which only occur when the callee has GC:
2762 // 1. If the caller has no GC, then the callee's GC must be propagated to the
2763 // caller.
2764 // 2. If the caller has a differing GC, it is invalid to inline.
2765 if (CalledFunc->hasGC()) {
2766 if (!Caller->hasGC())
2767 Caller->setGC(CalledFunc->getGC());
2768 else {
2769 assert(CalledFunc->getGC() == Caller->getGC() &&
2770 "CanInlineCallSite should have verified compatible GCs");
2771 }
2772 }
2773
2774 if (CalledFunc->hasPersonalityFn()) {
2775 Constant *CalledPersonality =
2776 CalledFunc->getPersonalityFn()->stripPointerCasts();
2777 if (!Caller->hasPersonalityFn()) {
2778 Caller->setPersonalityFn(CalledPersonality);
2779 } else
2780 assert(Caller->getPersonalityFn()->stripPointerCasts() ==
2781 CalledPersonality &&
2782 "CanInlineCallSite should have verified compatible personality");
2783 }
2784
2785 { // Scope to destroy VMap after cloning.
2786 ValueToValueMapTy VMap;
2787 struct ByValInit {
2788 Value *Dst;
2789 Value *Src;
2790 MaybeAlign SrcAlign;
2791 Type *Ty;
2792 };
2793 // Keep a list of tuples (dst, src, src_align) to emit byval
2794 // initializations. Src Alignment is only available though the callbase,
2795 // therefore has to be saved.
2796 SmallVector<ByValInit, 4> ByValInits;
2797
2798 // When inlining a function that contains noalias scope metadata,
2799 // this metadata needs to be cloned so that the inlined blocks
2800 // have different "unique scopes" at every call site.
2801 // Track the metadata that must be cloned. Do this before other changes to
2802 // the function, so that we do not get in trouble when inlining caller ==
2803 // callee.
2804 ScopedAliasMetadataDeepCloner SAMetadataCloner(CB.getCalledFunction());
2805
2806 auto &DL = Caller->getDataLayout();
2807
2808 // Calculate the vector of arguments to pass into the function cloner, which
2809 // matches up the formal to the actual argument values.
2810 auto AI = CB.arg_begin();
2811 unsigned ArgNo = 0;
2812 for (Function::arg_iterator I = CalledFunc->arg_begin(),
2813 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
2814 Value *ActualArg = *AI;
2815
2816 // When byval arguments actually inlined, we need to make the copy implied
2817 // by them explicit. However, we don't do this if the callee is readonly
2818 // or readnone, because the copy would be unneeded: the callee doesn't
2819 // modify the struct.
2820 if (CB.isByValArgument(ArgNo)) {
2821 ActualArg = HandleByValArgument(ByValType: CB.getParamByValType(ArgNo), Arg: ActualArg,
2822 TheCall: &CB, CalledFunc, IFI,
2823 ByValAlignment: CalledFunc->getParamAlign(ArgNo));
2824 if (ActualArg != *AI)
2825 ByValInits.push_back(Elt: {.Dst: ActualArg, .Src: (Value *)*AI,
2826 .SrcAlign: CB.getParamAlign(ArgNo),
2827 .Ty: CB.getParamByValType(ArgNo)});
2828 }
2829
2830 VMap[&*I] = ActualArg;
2831 }
2832
2833 // TODO: Remove this when users have been updated to the assume bundles.
2834 // Add alignment assumptions if necessary. We do this before the inlined
2835 // instructions are actually cloned into the caller so that we can easily
2836 // check what will be known at the start of the inlined code.
2837 AddAlignmentAssumptions(CB, IFI);
2838
2839 AssumptionCache *AC =
2840 IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr;
2841
2842 /// Preserve all attributes on of the call and its parameters.
2843 salvageKnowledge(I: &CB, AC);
2844
2845 // We want the inliner to prune the code as it copies. We would LOVE to
2846 // have no dead or constant instructions leftover after inlining occurs
2847 // (which can happen, e.g., because an argument was constant), but we'll be
2848 // happy with whatever the cloner can do.
2849 CloneAndPruneFunctionInto(NewFunc: Caller, OldFunc: CalledFunc, VMap,
2850 /*ModuleLevelChanges=*/false, Returns, NameSuffix: ".i",
2851 CodeInfo&: InlinedFunctionInfo);
2852 // Remember the first block that is newly cloned over.
2853 FirstNewBlock = LastBlock; ++FirstNewBlock;
2854
2855 // Insert retainRV/clainRV runtime calls.
2856 objcarc::ARCInstKind RVCallKind = objcarc::getAttachedARCFunctionKind(CB: &CB);
2857 if (RVCallKind != objcarc::ARCInstKind::None)
2858 inlineRetainOrClaimRVCalls(CB, RVCallKind, Returns);
2859
2860 // Updated caller/callee profiles only when requested. For sample loader
2861 // inlining, the context-sensitive inlinee profile doesn't need to be
2862 // subtracted from callee profile, and the inlined clone also doesn't need
2863 // to be scaled based on call site count.
2864 if (IFI.UpdateProfile) {
2865 if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr)
2866 // Update the BFI of blocks cloned into the caller.
2867 updateCallerBFI(CallSiteBlock: OrigBB, VMap, CallerBFI: IFI.CallerBFI, CalleeBFI: IFI.CalleeBFI,
2868 CalleeEntryBlock: CalledFunc->front());
2869
2870 if (auto Profile = CalledFunc->getEntryCount())
2871 updateCallProfile(Callee: CalledFunc, VMap, CalleeEntryCount: *Profile, TheCall: CB, PSI: IFI.PSI,
2872 CallerBFI: IFI.CallerBFI);
2873 }
2874
2875 // Inject byval arguments initialization.
2876 for (ByValInit &Init : ByValInits)
2877 HandleByValArgumentInit(ByValType: Init.Ty, Dst: Init.Dst, Src: Init.Src, SrcAlign: Init.SrcAlign,
2878 M: Caller->getParent(), InsertBlock: &*FirstNewBlock, IFI,
2879 CalledFunc);
2880
2881 std::optional<OperandBundleUse> ParentDeopt =
2882 CB.getOperandBundle(ID: LLVMContext::OB_deopt);
2883 if (ParentDeopt) {
2884 SmallVector<OperandBundleDef, 2> OpDefs;
2885
2886 for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
2887 CallBase *ICS = dyn_cast_or_null<CallBase>(Val&: VH);
2888 if (!ICS)
2889 continue; // instruction was DCE'd or RAUW'ed to undef
2890
2891 OpDefs.clear();
2892
2893 OpDefs.reserve(N: ICS->getNumOperandBundles());
2894
2895 for (unsigned COBi = 0, COBe = ICS->getNumOperandBundles(); COBi < COBe;
2896 ++COBi) {
2897 auto ChildOB = ICS->getOperandBundleAt(Index: COBi);
2898 if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
2899 // If the inlined call has other operand bundles, let them be
2900 OpDefs.emplace_back(Args&: ChildOB);
2901 continue;
2902 }
2903
2904 // It may be useful to separate this logic (of handling operand
2905 // bundles) out to a separate "policy" component if this gets crowded.
2906 // Prepend the parent's deoptimization continuation to the newly
2907 // inlined call's deoptimization continuation.
2908 std::vector<Value *> MergedDeoptArgs;
2909 MergedDeoptArgs.reserve(n: ParentDeopt->Inputs.size() +
2910 ChildOB.Inputs.size());
2911
2912 llvm::append_range(C&: MergedDeoptArgs, R&: ParentDeopt->Inputs);
2913 llvm::append_range(C&: MergedDeoptArgs, R&: ChildOB.Inputs);
2914
2915 OpDefs.emplace_back(Args: "deopt", Args: std::move(MergedDeoptArgs));
2916 }
2917
2918 Instruction *NewI = CallBase::Create(CB: ICS, Bundles: OpDefs, InsertPt: ICS->getIterator());
2919
2920 // Note: the RAUW does the appropriate fixup in VMap, so we need to do
2921 // this even if the call returns void.
2922 ICS->replaceAllUsesWith(V: NewI);
2923
2924 VH = nullptr;
2925 ICS->eraseFromParent();
2926 }
2927 }
2928
2929 // For 'nodebug' functions, the associated DISubprogram is always null.
2930 // Conservatively avoid propagating the callsite debug location to
2931 // instructions inlined from a function whose DISubprogram is not null.
2932 fixupLineNumbers(Fn: Caller, FI: FirstNewBlock, TheCall: &CB,
2933 CalleeHasDebugInfo: CalledFunc->getSubprogram() != nullptr);
2934
2935 if (isAssignmentTrackingEnabled(M: *Caller->getParent())) {
2936 // Interpret inlined stores to caller-local variables as assignments.
2937 trackInlinedStores(Start: FirstNewBlock, End: Caller->end(), CB);
2938
2939 // Update DIAssignID metadata attachments and uses so that they are
2940 // unique to this inlined instance.
2941 fixupAssignments(Start: FirstNewBlock, End: Caller->end());
2942 }
2943
2944 // Now clone the inlined noalias scope metadata.
2945 SAMetadataCloner.clone();
2946 SAMetadataCloner.remap(FStart: FirstNewBlock, FEnd: Caller->end());
2947
2948 // Add noalias metadata if necessary.
2949 AddAliasScopeMetadata(CB, VMap, DL, CalleeAAR, InlinedFunctionInfo);
2950
2951 // Clone return attributes on the callsite into the calls within the inlined
2952 // function which feed into its return value.
2953 AddReturnAttributes(CB, VMap, InlinedFunctionInfo);
2954
2955 // Clone attributes on the params of the callsite to calls within the
2956 // inlined function which use the same param.
2957 AddParamAndFnBasicAttributes(CB, VMap, InlinedFunctionInfo);
2958
2959 propagateMemProfMetadata(
2960 Callee: CalledFunc, CB, ContainsMemProfMetadata: InlinedFunctionInfo.ContainsMemProfMetadata, VMap, ORE);
2961
2962 // Propagate metadata on the callsite if necessary.
2963 PropagateCallSiteMetadata(CB, FStart: FirstNewBlock, FEnd: Caller->end());
2964
2965 // Propagate an allocation wrapper's !alloc_token if necessary.
2966 propagateAllocTokenMetadata(CalledFunc, CB, VMap, InlinedFunctionInfo);
2967
2968 // Propagate implicit ref metadata.
2969 if (CalledFunc->hasMetadata(KindID: LLVMContext::MD_implicit_ref)) {
2970 SmallVector<MDNode *> MDs;
2971 CalledFunc->getMetadata(KindID: LLVMContext::MD_implicit_ref, MDs);
2972 for (MDNode *MD : MDs) {
2973 Caller->addMetadata(KindID: LLVMContext::MD_implicit_ref, MD&: *MD);
2974 }
2975 }
2976
2977 // Propagate inlined.from metadata for dontcall diagnostics.
2978 PropagateInlinedFromMetadata(CB, CalledFuncName: CalledFunc->getName(), CallerFuncName: Caller->getName(),
2979 FStart: FirstNewBlock, FEnd: Caller->end());
2980
2981 // Register any cloned assumptions.
2982 if (IFI.GetAssumptionCache)
2983 for (BasicBlock &NewBlock :
2984 make_range(x: FirstNewBlock->getIterator(), y: Caller->end()))
2985 for (Instruction &I : NewBlock)
2986 if (auto *II = dyn_cast<AssumeInst>(Val: &I))
2987 IFI.GetAssumptionCache(*Caller).registerAssumption(CI: II);
2988 }
2989
2990 if (IFI.ConvergenceControlToken) {
2991 IntrinsicInst *IntrinsicCall = getConvergenceEntry(BB&: *FirstNewBlock);
2992 if (IntrinsicCall) {
2993 IntrinsicCall->replaceAllUsesWith(V: IFI.ConvergenceControlToken);
2994 IntrinsicCall->eraseFromParent();
2995 }
2996 }
2997
2998 // If there are any alloca instructions in the block that used to be the entry
2999 // block for the callee, move them to the entry block of the caller. First
3000 // calculate which instruction they should be inserted before. We insert the
3001 // instructions at the end of the current alloca list.
3002 {
3003 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
3004 for (BasicBlock::iterator I = FirstNewBlock->begin(),
3005 E = FirstNewBlock->end(); I != E; ) {
3006 AllocaInst *AI = dyn_cast<AllocaInst>(Val: I++);
3007 if (!AI) continue;
3008
3009 // If the alloca is now dead, remove it. This often occurs due to code
3010 // specialization.
3011 if (AI->use_empty()) {
3012 AI->eraseFromParent();
3013 continue;
3014 }
3015
3016 if (!allocaWouldBeStaticInEntry(AI))
3017 continue;
3018
3019 // Keep track of the static allocas that we inline into the caller.
3020 IFI.StaticAllocas.push_back(Elt: AI);
3021
3022 // Scan for the block of allocas that we can move over, and move them
3023 // all at once.
3024 while (isa<AllocaInst>(Val: I) &&
3025 !cast<AllocaInst>(Val&: I)->use_empty() &&
3026 allocaWouldBeStaticInEntry(AI: cast<AllocaInst>(Val&: I))) {
3027 IFI.StaticAllocas.push_back(Elt: cast<AllocaInst>(Val&: I));
3028 ++I;
3029 }
3030
3031 // Transfer all of the allocas over in a block. Using splice means
3032 // that the instructions aren't removed from the symbol table, then
3033 // reinserted.
3034 I.setTailBit(true);
3035 Caller->getEntryBlock().splice(ToIt: InsertPoint, FromBB: &*FirstNewBlock,
3036 FromBeginIt: AI->getIterator(), FromEndIt: I);
3037 }
3038 }
3039
3040 // If the call to the callee cannot throw, set the 'nounwind' flag on any
3041 // calls that we inline.
3042 bool MarkNoUnwind = CB.doesNotThrow();
3043
3044 SmallVector<Value*,4> VarArgsToForward;
3045 SmallVector<AttributeSet, 4> VarArgsAttrs;
3046 for (unsigned i = CalledFunc->getFunctionType()->getNumParams();
3047 i < CB.arg_size(); i++) {
3048 VarArgsToForward.push_back(Elt: CB.getArgOperand(i));
3049 VarArgsAttrs.push_back(Elt: CB.getAttributes().getParamAttrs(ArgNo: i));
3050 }
3051
3052 bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false;
3053 if (InlinedFunctionInfo.ContainsCalls) {
3054 CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
3055 if (CallInst *CI = dyn_cast<CallInst>(Val: &CB))
3056 CallSiteTailKind = CI->getTailCallKind();
3057
3058 // For inlining purposes, the "notail" marker is the same as no marker.
3059 if (CallSiteTailKind == CallInst::TCK_NoTail)
3060 CallSiteTailKind = CallInst::TCK_None;
3061
3062 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
3063 ++BB) {
3064 for (Instruction &I : llvm::make_early_inc_range(Range&: *BB)) {
3065 CallInst *CI = dyn_cast<CallInst>(Val: &I);
3066 if (!CI)
3067 continue;
3068
3069 // Forward varargs from inlined call site to calls to the
3070 // ForwardVarArgsTo function, if requested, and to musttail calls.
3071 if (!VarArgsToForward.empty() &&
3072 ((ForwardVarArgsTo &&
3073 CI->getCalledFunction() == ForwardVarArgsTo) ||
3074 CI->isMustTailCall())) {
3075 // Collect attributes for non-vararg parameters.
3076 AttributeList Attrs = CI->getAttributes();
3077 SmallVector<AttributeSet, 8> ArgAttrs;
3078 if (!Attrs.isEmpty() || !VarArgsAttrs.empty()) {
3079 for (unsigned ArgNo = 0;
3080 ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo)
3081 ArgAttrs.push_back(Elt: Attrs.getParamAttrs(ArgNo));
3082 }
3083
3084 // Add VarArg attributes.
3085 ArgAttrs.append(in_start: VarArgsAttrs.begin(), in_end: VarArgsAttrs.end());
3086 Attrs = AttributeList::get(C&: CI->getContext(), FnAttrs: Attrs.getFnAttrs(),
3087 RetAttrs: Attrs.getRetAttrs(), ArgAttrs);
3088 // Add VarArgs to existing parameters.
3089 SmallVector<Value *, 6> Params(CI->args());
3090 Params.append(in_start: VarArgsToForward.begin(), in_end: VarArgsToForward.end());
3091 CallInst *NewCI = CallInst::Create(
3092 Ty: CI->getFunctionType(), Func: CI->getCalledOperand(), Args: Params, NameStr: "", InsertBefore: CI->getIterator());
3093 NewCI->setDebugLoc(CI->getDebugLoc());
3094 NewCI->setAttributes(Attrs);
3095 NewCI->setCallingConv(CI->getCallingConv());
3096 CI->replaceAllUsesWith(V: NewCI);
3097 CI->eraseFromParent();
3098 CI = NewCI;
3099 }
3100
3101 if (Function *F = CI->getCalledFunction())
3102 InlinedDeoptimizeCalls |=
3103 F->getIntrinsicID() == Intrinsic::experimental_deoptimize;
3104
3105 // We need to reduce the strength of any inlined tail calls. For
3106 // musttail, we have to avoid introducing potential unbounded stack
3107 // growth. For example, if functions 'f' and 'g' are mutually recursive
3108 // with musttail, we can inline 'g' into 'f' so long as we preserve
3109 // musttail on the cloned call to 'f'. If either the inlined call site
3110 // or the cloned call site is *not* musttail, the program already has
3111 // one frame of stack growth, so it's safe to remove musttail. Here is
3112 // a table of example transformations:
3113 //
3114 // f -> musttail g -> musttail f ==> f -> musttail f
3115 // f -> musttail g -> tail f ==> f -> tail f
3116 // f -> g -> musttail f ==> f -> f
3117 // f -> g -> tail f ==> f -> f
3118 //
3119 // Inlined notail calls should remain notail calls.
3120 CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
3121 if (ChildTCK != CallInst::TCK_NoTail)
3122 ChildTCK = std::min(a: CallSiteTailKind, b: ChildTCK);
3123 CI->setTailCallKind(ChildTCK);
3124 InlinedMustTailCalls |= CI->isMustTailCall();
3125
3126 // Call sites inlined through a 'nounwind' call site should be
3127 // 'nounwind' as well. However, avoid marking call sites explicitly
3128 // where possible. This helps expose more opportunities for CSE after
3129 // inlining, commonly when the callee is an intrinsic.
3130 if (MarkNoUnwind && !CI->doesNotThrow())
3131 CI->setDoesNotThrow();
3132 }
3133 }
3134 }
3135
3136 // Leave lifetime markers for the static alloca's, scoping them to the
3137 // function we just inlined.
3138 // We need to insert lifetime intrinsics even at O0 to avoid invalid
3139 // access caused by multithreaded coroutines. The check
3140 // `Caller->isPresplitCoroutine()` would affect AlwaysInliner at O0 only.
3141 if ((InsertLifetime || Caller->isPresplitCoroutine()) &&
3142 !IFI.StaticAllocas.empty()) {
3143 IRBuilder<> builder(FirstNewBlock->begin());
3144 for (AllocaInst *AI : IFI.StaticAllocas) {
3145 // Don't mark swifterror allocas. They can't have bitcast uses.
3146 if (AI->isSwiftError())
3147 continue;
3148
3149 // If the alloca is already scoped to something smaller than the whole
3150 // function then there's no need to add redundant, less accurate markers.
3151 if (any_of(Range: AI->users(), P: IsaPred<LifetimeIntrinsic>))
3152 continue;
3153
3154 std::optional<TypeSize> Size = AI->getAllocationSize(DL: AI->getDataLayout());
3155 if (Size && Size->isZero())
3156 continue;
3157
3158 builder.CreateLifetimeStart(Ptr: AI);
3159 for (ReturnInst *RI : Returns) {
3160 // Don't insert llvm.lifetime.end calls between a musttail or deoptimize
3161 // call and a return. The return kills all local allocas.
3162 if (InlinedMustTailCalls &&
3163 RI->getParent()->getTerminatingMustTailCall())
3164 continue;
3165 if (InlinedDeoptimizeCalls &&
3166 RI->getParent()->getTerminatingDeoptimizeCall())
3167 continue;
3168 IRBuilder<>(RI).CreateLifetimeEnd(Ptr: AI);
3169 }
3170 }
3171 }
3172
3173 // If the inlined code contained dynamic alloca instructions, wrap the inlined
3174 // code with llvm.stacksave/llvm.stackrestore intrinsics.
3175 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
3176 // Insert the llvm.stacksave.
3177 CallInst *SavedPtr =
3178 IRBuilder<>(FirstNewBlock->begin()).CreateStackSave(Name: "savedstack");
3179
3180 // Insert a call to llvm.stackrestore before any return instructions in the
3181 // inlined function.
3182 for (ReturnInst *RI : Returns) {
3183 // Don't insert llvm.stackrestore calls between a musttail or deoptimize
3184 // call and a return. The return will restore the stack pointer.
3185 if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
3186 continue;
3187 if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall())
3188 continue;
3189 IRBuilder<>(RI).CreateStackRestore(Ptr: SavedPtr);
3190 }
3191 }
3192
3193 // If we are inlining for an invoke instruction, we must make sure to rewrite
3194 // any call instructions into invoke instructions. This is sensitive to which
3195 // funclet pads were top-level in the inlinee, so must be done before
3196 // rewriting the "parent pad" links.
3197 if (auto *II = dyn_cast<InvokeInst>(Val: &CB)) {
3198 BasicBlock *UnwindDest = II->getUnwindDest();
3199 BasicBlock::iterator FirstNonPHI = UnwindDest->getFirstNonPHIIt();
3200 if (isa<LandingPadInst>(Val: FirstNonPHI)) {
3201 HandleInlinedLandingPad(II, FirstNewBlock: &*FirstNewBlock, InlinedCodeInfo&: InlinedFunctionInfo);
3202 } else {
3203 HandleInlinedEHPad(II, FirstNewBlock: &*FirstNewBlock, InlinedCodeInfo&: InlinedFunctionInfo);
3204 }
3205 }
3206
3207 // Update the lexical scopes of the new funclets and callsites.
3208 // Anything that had 'none' as its parent is now nested inside the callsite's
3209 // EHPad.
3210 if (IFI.CallSiteEHPad) {
3211 for (Function::iterator BB = FirstNewBlock->getIterator(),
3212 E = Caller->end();
3213 BB != E; ++BB) {
3214 // Add bundle operands to inlined call sites.
3215 PropagateOperandBundles(InlinedBB: BB, CallSiteEHPad: IFI.CallSiteEHPad);
3216
3217 // It is problematic if the inlinee has a cleanupret which unwinds to
3218 // caller and we inline it into a call site which doesn't unwind but into
3219 // an EH pad that does. Such an edge must be dynamically unreachable.
3220 // As such, we replace the cleanupret with unreachable.
3221 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(Val: BB->getTerminator()))
3222 if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally)
3223 changeToUnreachable(I: CleanupRet);
3224
3225 BasicBlock::iterator I = BB->getFirstNonPHIIt();
3226 if (!I->isEHPad())
3227 continue;
3228
3229 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Val&: I)) {
3230 if (isa<ConstantTokenNone>(Val: CatchSwitch->getParentPad()))
3231 CatchSwitch->setParentPad(IFI.CallSiteEHPad);
3232 } else {
3233 auto *FPI = cast<FuncletPadInst>(Val&: I);
3234 if (isa<ConstantTokenNone>(Val: FPI->getParentPad()))
3235 FPI->setParentPad(IFI.CallSiteEHPad);
3236 }
3237 }
3238 }
3239
3240 if (InlinedDeoptimizeCalls) {
3241 // We need to at least remove the deoptimizing returns from the Return set,
3242 // so that the control flow from those returns does not get merged into the
3243 // caller (but terminate it instead). If the caller's return type does not
3244 // match the callee's return type, we also need to change the return type of
3245 // the intrinsic.
3246 if (Caller->getReturnType() == CB.getType()) {
3247 llvm::erase_if(C&: Returns, P: [](ReturnInst *RI) {
3248 return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr;
3249 });
3250 } else {
3251 SmallVector<ReturnInst *, 8> NormalReturns;
3252 Function *NewDeoptIntrinsic = Intrinsic::getOrInsertDeclaration(
3253 M: Caller->getParent(), id: Intrinsic::experimental_deoptimize,
3254 OverloadTys: {Caller->getReturnType()});
3255
3256 for (ReturnInst *RI : Returns) {
3257 CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall();
3258 if (!DeoptCall) {
3259 NormalReturns.push_back(Elt: RI);
3260 continue;
3261 }
3262
3263 // The calling convention on the deoptimize call itself may be bogus,
3264 // since the code we're inlining may have undefined behavior (and may
3265 // never actually execute at runtime); but all
3266 // @llvm.experimental.deoptimize declarations have to have the same
3267 // calling convention in a well-formed module.
3268 auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv();
3269 NewDeoptIntrinsic->setCallingConv(CallingConv);
3270 auto *CurBB = RI->getParent();
3271 RI->eraseFromParent();
3272
3273 SmallVector<Value *, 4> CallArgs(DeoptCall->args());
3274
3275 SmallVector<OperandBundleDef, 1> OpBundles;
3276 DeoptCall->getOperandBundlesAsDefs(Defs&: OpBundles);
3277 auto DeoptAttributes = DeoptCall->getAttributes();
3278 DeoptCall->eraseFromParent();
3279 assert(!OpBundles.empty() &&
3280 "Expected at least the deopt operand bundle");
3281
3282 IRBuilder<> Builder(CurBB);
3283 CallInst *NewDeoptCall =
3284 Builder.CreateCall(Callee: NewDeoptIntrinsic, Args: CallArgs, OpBundles);
3285 NewDeoptCall->setCallingConv(CallingConv);
3286 NewDeoptCall->setAttributes(DeoptAttributes);
3287 if (NewDeoptCall->getType()->isVoidTy())
3288 Builder.CreateRetVoid();
3289 else
3290 Builder.CreateRet(V: NewDeoptCall);
3291 // Since the ret type is changed, remove the incompatible attributes.
3292 NewDeoptCall->removeRetAttrs(AttrsToRemove: AttributeFuncs::typeIncompatible(
3293 Ty: NewDeoptCall->getType(), AS: NewDeoptCall->getRetAttributes()));
3294 }
3295
3296 // Leave behind the normal returns so we can merge control flow.
3297 std::swap(LHS&: Returns, RHS&: NormalReturns);
3298 }
3299 }
3300
3301 // Handle any inlined musttail call sites. In order for a new call site to be
3302 // musttail, the source of the clone and the inlined call site must have been
3303 // musttail. Therefore it's safe to return without merging control into the
3304 // phi below.
3305 if (InlinedMustTailCalls) {
3306 // Handle the returns preceded by musttail calls separately.
3307 SmallVector<ReturnInst *, 8> NormalReturns;
3308 for (ReturnInst *RI : Returns) {
3309 CallInst *ReturnedMustTail =
3310 RI->getParent()->getTerminatingMustTailCall();
3311 if (!ReturnedMustTail)
3312 NormalReturns.push_back(Elt: RI);
3313 }
3314
3315 // Leave behind the normal returns so we can merge control flow.
3316 std::swap(LHS&: Returns, RHS&: NormalReturns);
3317 }
3318
3319 // Now that all of the transforms on the inlined code have taken place but
3320 // before we splice the inlined code into the CFG and lose track of which
3321 // blocks were actually inlined, collect the call sites. We only do this if
3322 // call graph updates weren't requested, as those provide value handle based
3323 // tracking of inlined call sites instead. Calls to intrinsics are not
3324 // collected because they are not inlineable.
3325 if (InlinedFunctionInfo.ContainsCalls) {
3326 // Otherwise just collect the raw call sites that were inlined.
3327 for (BasicBlock &NewBB :
3328 make_range(x: FirstNewBlock->getIterator(), y: Caller->end()))
3329 for (Instruction &I : NewBB)
3330 if (auto *CB = dyn_cast<CallBase>(Val: &I))
3331 if (!(CB->getCalledFunction() &&
3332 CB->getCalledFunction()->isIntrinsic()))
3333 IFI.InlinedCallSites.push_back(Elt: CB);
3334 }
3335
3336 for (CallBase *ICB : IFI.InlinedCallSites) {
3337 // We only track inline history if requested, or if the inlined call site
3338 // was originally an indirect call (it may have become a direct call
3339 // during inlining).
3340 if (TrackInlineHistory ||
3341 InlinedFunctionInfo.OriginallyIndirectCalls.contains(key: ICB)) {
3342 // !inline_history is {Callee, CB.inline_history, ICB.inline_history}.
3343 // Metadata nodes may be null if the referenced function was erased from
3344 // the module.
3345 SmallVector<Metadata *, 4> History;
3346 History.push_back(Elt: ValueAsMetadata::get(V: CalledFunc));
3347 if (MDNode *CBHistory = CB.getMetadata(KindID: LLVMContext::MD_inline_history)) {
3348 for (const auto &Op : CBHistory->operands()) {
3349 if (Op)
3350 History.push_back(Elt: Op.get());
3351 }
3352 }
3353 if (MDNode *CBHistory =
3354 ICB->getMetadata(KindID: LLVMContext::MD_inline_history)) {
3355 for (const auto &Op : CBHistory->operands()) {
3356 if (Op)
3357 History.push_back(Elt: Op.get());
3358 }
3359 }
3360 MDNode *NewHistory = MDNode::get(Context&: Caller->getContext(), MDs: History);
3361 ICB->setMetadata(KindID: LLVMContext::MD_inline_history, Node: NewHistory);
3362 }
3363 }
3364
3365 // If we cloned in _exactly one_ basic block, and if that block ends in a
3366 // return instruction, we splice the body of the inlined callee directly into
3367 // the calling basic block.
3368 if (Returns.size() == 1 && std::distance(first: FirstNewBlock, last: Caller->end()) == 1) {
3369 // Move all of the instructions right before the call.
3370 OrigBB->splice(ToIt: CB.getIterator(), FromBB: &*FirstNewBlock, FromBeginIt: FirstNewBlock->begin(),
3371 FromEndIt: FirstNewBlock->end());
3372 // Remove the cloned basic block.
3373 Caller->back().eraseFromParent();
3374
3375 // If the call site was an invoke instruction, add a branch to the normal
3376 // destination.
3377 if (InvokeInst *II = dyn_cast<InvokeInst>(Val: &CB)) {
3378 UncondBrInst *NewBr =
3379 UncondBrInst::Create(Target: II->getNormalDest(), InsertBefore: CB.getIterator());
3380 NewBr->setDebugLoc(Returns[0]->getDebugLoc());
3381 }
3382
3383 // If the return instruction returned a value, replace uses of the call with
3384 // uses of the returned value.
3385 if (!CB.use_empty()) {
3386 ReturnInst *R = Returns[0];
3387 if (&CB == R->getReturnValue())
3388 CB.replaceAllUsesWith(V: PoisonValue::get(T: CB.getType()));
3389 else
3390 CB.replaceAllUsesWith(V: R->getReturnValue());
3391 }
3392 // Since we are now done with the Call/Invoke, we can delete it.
3393 CB.eraseFromParent();
3394
3395 // Since we are now done with the return instruction, delete it also.
3396 Returns[0]->eraseFromParent();
3397
3398 if (MergeAttributes)
3399 AttributeFuncs::mergeAttributesForInlining(Caller&: *Caller, Callee: *CalledFunc);
3400
3401 // We are now done with the inlining.
3402 return;
3403 }
3404
3405 // Otherwise, we have the normal case, of more than one block to inline or
3406 // multiple return sites.
3407
3408 // We want to clone the entire callee function into the hole between the
3409 // "starter" and "ender" blocks. How we accomplish this depends on whether
3410 // this is an invoke instruction or a call instruction.
3411 BasicBlock *AfterCallBB;
3412 UncondBrInst *CreatedBranchToNormalDest = nullptr;
3413 if (InvokeInst *II = dyn_cast<InvokeInst>(Val: &CB)) {
3414
3415 // Add an unconditional branch to make this look like the CallInst case...
3416 CreatedBranchToNormalDest =
3417 UncondBrInst::Create(Target: II->getNormalDest(), InsertBefore: CB.getIterator());
3418 // We intend to replace this DebugLoc with another later.
3419 CreatedBranchToNormalDest->setDebugLoc(DebugLoc::getTemporary());
3420
3421 // Split the basic block. This guarantees that no PHI nodes will have to be
3422 // updated due to new incoming edges, and make the invoke case more
3423 // symmetric to the call case.
3424 AfterCallBB =
3425 OrigBB->splitBasicBlock(I: CreatedBranchToNormalDest->getIterator(),
3426 BBName: CalledFunc->getName() + ".exit");
3427
3428 } else { // It's a call
3429 // If this is a call instruction, we need to split the basic block that
3430 // the call lives in.
3431 //
3432 AfterCallBB = OrigBB->splitBasicBlock(I: CB.getIterator(),
3433 BBName: CalledFunc->getName() + ".exit");
3434 }
3435
3436 if (IFI.CallerBFI) {
3437 // Copy original BB's block frequency to AfterCallBB
3438 IFI.CallerBFI->setBlockFreq(BB: AfterCallBB,
3439 Freq: IFI.CallerBFI->getBlockFreq(BB: OrigBB));
3440 }
3441
3442 // Change the branch that used to go to AfterCallBB to branch to the first
3443 // basic block of the inlined function.
3444 //
3445 UncondBrInst *Br = cast<UncondBrInst>(Val: OrigBB->getTerminator());
3446 Br->setSuccessor(&*FirstNewBlock);
3447
3448 // Now that the function is correct, make it a little bit nicer. In
3449 // particular, move the basic blocks inserted from the end of the function
3450 // into the space made by splitting the source basic block.
3451 Caller->splice(ToIt: AfterCallBB->getIterator(), FromF: Caller, FromBeginIt: FirstNewBlock,
3452 FromEndIt: Caller->end());
3453
3454 // Handle all of the return instructions that we just cloned in, and eliminate
3455 // any users of the original call/invoke instruction.
3456 Type *RTy = CalledFunc->getReturnType();
3457
3458 PHINode *PHI = nullptr;
3459 if (Returns.size() > 1) {
3460 // The PHI node should go at the front of the new basic block to merge all
3461 // possible incoming values.
3462 if (!CB.use_empty()) {
3463 PHI = PHINode::Create(Ty: RTy, NumReservedValues: Returns.size(), NameStr: CB.getName());
3464 PHI->insertBefore(InsertPos: AfterCallBB->begin());
3465 // Anything that used the result of the function call should now use the
3466 // PHI node as their operand.
3467 CB.replaceAllUsesWith(V: PHI);
3468 }
3469
3470 // Loop over all of the return instructions adding entries to the PHI node
3471 // as appropriate.
3472 if (PHI) {
3473 for (ReturnInst *RI : Returns) {
3474 assert(RI->getReturnValue()->getType() == PHI->getType() &&
3475 "Ret value not consistent in function!");
3476 PHI->addIncoming(V: RI->getReturnValue(), BB: RI->getParent());
3477 }
3478 }
3479
3480 // Add a branch to the merge points and remove return instructions.
3481 DebugLoc Loc;
3482 for (ReturnInst *RI : Returns) {
3483 UncondBrInst *BI = UncondBrInst::Create(Target: AfterCallBB, InsertBefore: RI->getIterator());
3484 Loc = RI->getDebugLoc();
3485 BI->setDebugLoc(Loc);
3486 RI->eraseFromParent();
3487 }
3488 // We need to set the debug location to *somewhere* inside the
3489 // inlined function. The line number may be nonsensical, but the
3490 // instruction will at least be associated with the right
3491 // function.
3492 if (CreatedBranchToNormalDest)
3493 CreatedBranchToNormalDest->setDebugLoc(Loc);
3494 } else if (!Returns.empty()) {
3495 // Otherwise, if there is exactly one return value, just replace anything
3496 // using the return value of the call with the computed value.
3497 if (!CB.use_empty()) {
3498 if (&CB == Returns[0]->getReturnValue())
3499 CB.replaceAllUsesWith(V: PoisonValue::get(T: CB.getType()));
3500 else
3501 CB.replaceAllUsesWith(V: Returns[0]->getReturnValue());
3502 }
3503
3504 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
3505 BasicBlock *ReturnBB = Returns[0]->getParent();
3506 ReturnBB->replaceAllUsesWith(V: AfterCallBB);
3507
3508 // Splice the code from the return block into the block that it will return
3509 // to, which contains the code that was after the call.
3510 AfterCallBB->splice(ToIt: AfterCallBB->begin(), FromBB: ReturnBB);
3511
3512 if (CreatedBranchToNormalDest)
3513 CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
3514
3515 // Delete the return instruction now and empty ReturnBB now.
3516 Returns[0]->eraseFromParent();
3517 ReturnBB->eraseFromParent();
3518 } else if (!CB.use_empty()) {
3519 // In this case there are no returns to use, so there is no clear source
3520 // location for the "return".
3521 // FIXME: It may be correct to use the scope end line of the function here,
3522 // since this likely means we are falling out of the function.
3523 if (CreatedBranchToNormalDest)
3524 CreatedBranchToNormalDest->setDebugLoc(DebugLoc::getUnknown());
3525 // No returns, but something is using the return value of the call. Just
3526 // nuke the result.
3527 CB.replaceAllUsesWith(V: PoisonValue::get(T: CB.getType()));
3528 }
3529
3530 // Since we are now done with the Call/Invoke, we can delete it.
3531 CB.eraseFromParent();
3532
3533 // If we inlined any musttail calls and the original return is now
3534 // unreachable, delete it. It can only contain a ret.
3535 if (InlinedMustTailCalls && pred_empty(BB: AfterCallBB))
3536 AfterCallBB->eraseFromParent();
3537
3538 // We should always be able to fold the entry block of the function into the
3539 // single predecessor of the block...
3540 BasicBlock *CalleeEntry = Br->getSuccessor();
3541
3542 // Splice the code entry block into calling block, right before the
3543 // unconditional branch.
3544 CalleeEntry->replaceAllUsesWith(V: OrigBB); // Update PHI nodes
3545 OrigBB->splice(ToIt: Br->getIterator(), FromBB: CalleeEntry);
3546
3547 // Remove the unconditional branch.
3548 Br->eraseFromParent();
3549
3550 // Now we can remove the CalleeEntry block, which is now empty.
3551 CalleeEntry->eraseFromParent();
3552
3553 // If we inserted a phi node, check to see if it has a single value (e.g. all
3554 // the entries are the same or undef). If so, remove the PHI so it doesn't
3555 // block other optimizations.
3556 if (PHI) {
3557 AssumptionCache *AC =
3558 IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr;
3559 auto &DL = Caller->getDataLayout();
3560 if (Value *V = simplifyInstruction(I: PHI, Q: {DL, nullptr, nullptr, AC})) {
3561 PHI->replaceAllUsesWith(V);
3562 PHI->eraseFromParent();
3563 }
3564 }
3565
3566 if (MergeAttributes)
3567 AttributeFuncs::mergeAttributesForInlining(Caller&: *Caller, Callee: *CalledFunc);
3568}
3569
3570llvm::InlineResult llvm::InlineFunction(
3571 CallBase &CB, InlineFunctionInfo &IFI, bool MergeAttributes,
3572 AAResults *CalleeAAR, bool InsertLifetime, bool TrackInlineHistory,
3573 Function *ForwardVarArgsTo, OptimizationRemarkEmitter *ORE) {
3574 llvm::InlineResult Result = CanInlineCallSite(CB, IFI);
3575 if (Result.isSuccess()) {
3576 InlineFunctionImpl(CB, IFI, MergeAttributes, CalleeAAR, InsertLifetime,
3577 TrackInlineHistory, ForwardVarArgsTo, ORE);
3578 }
3579
3580 return Result;
3581}
3582