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