Movatterモバイル変換


[0]ホーム

URL:


LLVM 20.0.0git
Local.cpp
Go to the documentation of this file.
1//===- Local.cpp - Functions to perform local transformations -------------===//
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 family of functions perform various local transformations to the
10// program.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/Local.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/DenseMapInfo.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/Hashing.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/Analysis/AssumeBundleQueries.h"
26#include "llvm/Analysis/ConstantFolding.h"
27#include "llvm/Analysis/DomTreeUpdater.h"
28#include "llvm/Analysis/InstructionSimplify.h"
29#include "llvm/Analysis/MemoryBuiltins.h"
30#include "llvm/Analysis/MemorySSAUpdater.h"
31#include "llvm/Analysis/TargetLibraryInfo.h"
32#include "llvm/Analysis/ValueTracking.h"
33#include "llvm/Analysis/VectorUtils.h"
34#include "llvm/BinaryFormat/Dwarf.h"
35#include "llvm/IR/Argument.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/CFG.h"
39#include "llvm/IR/Constant.h"
40#include "llvm/IR/ConstantRange.h"
41#include "llvm/IR/Constants.h"
42#include "llvm/IR/DIBuilder.h"
43#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/DebugInfo.h"
45#include "llvm/IR/DebugInfoMetadata.h"
46#include "llvm/IR/DebugLoc.h"
47#include "llvm/IR/DerivedTypes.h"
48#include "llvm/IR/Dominators.h"
49#include "llvm/IR/EHPersonalities.h"
50#include "llvm/IR/Function.h"
51#include "llvm/IR/GetElementPtrTypeIterator.h"
52#include "llvm/IR/GlobalObject.h"
53#include "llvm/IR/IRBuilder.h"
54#include "llvm/IR/InstrTypes.h"
55#include "llvm/IR/Instruction.h"
56#include "llvm/IR/Instructions.h"
57#include "llvm/IR/IntrinsicInst.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/IntrinsicsWebAssembly.h"
60#include "llvm/IR/LLVMContext.h"
61#include "llvm/IR/MDBuilder.h"
62#include "llvm/IR/MemoryModelRelaxationAnnotations.h"
63#include "llvm/IR/Metadata.h"
64#include "llvm/IR/Module.h"
65#include "llvm/IR/PatternMatch.h"
66#include "llvm/IR/ProfDataUtils.h"
67#include "llvm/IR/Type.h"
68#include "llvm/IR/Use.h"
69#include "llvm/IR/User.h"
70#include "llvm/IR/Value.h"
71#include "llvm/IR/ValueHandle.h"
72#include "llvm/Support/Casting.h"
73#include "llvm/Support/CommandLine.h"
74#include "llvm/Support/Debug.h"
75#include "llvm/Support/ErrorHandling.h"
76#include "llvm/Support/KnownBits.h"
77#include "llvm/Support/raw_ostream.h"
78#include "llvm/Transforms/Utils/BasicBlockUtils.h"
79#include "llvm/Transforms/Utils/ValueMapper.h"
80#include <algorithm>
81#include <cassert>
82#include <cstdint>
83#include <iterator>
84#include <map>
85#include <optional>
86#include <utility>
87
88using namespacellvm;
89using namespacellvm::PatternMatch;
90
91externcl::opt<bool>UseNewDbgInfoFormat;
92
93#define DEBUG_TYPE "local"
94
95STATISTIC(NumRemoved,"Number of unreachable basic blocks removed");
96STATISTIC(NumPHICSEs,"Number of PHI's that got CSE'd");
97
98staticcl::opt<bool>PHICSEDebugHash(
99"phicse-debug-hash",
100#ifdef EXPENSIVE_CHECKS
101cl::init(true),
102#else
103cl::init(false),
104#endif
105cl::Hidden,
106cl::desc("Perform extra assertion checking to verify that PHINodes's hash "
107"function is well-behaved w.r.t. its isEqual predicate"));
108
109staticcl::opt<unsigned>PHICSENumPHISmallSize(
110"phicse-num-phi-smallsize",cl::init(32),cl::Hidden,
111cl::desc(
112"When the basic block contains not more than this number of PHI nodes, "
113"perform a (faster!) exhaustive search instead of set-driven one."));
114
115staticcl::opt<unsigned>MaxPhiEntriesIncreaseAfterRemovingEmptyBlock(
116"max-phi-entries-increase-after-removing-empty-block",cl::init(1000),
117cl::Hidden,
118cl::desc("Stop removing an empty block if removing it will introduce more "
119"than this number of phi entries in its successor"));
120
121// Max recursion depth for collectBitParts used when detecting bswap and
122// bitreverse idioms.
123staticconstunsignedBitPartRecursionMaxDepth = 48;
124
125//===----------------------------------------------------------------------===//
126// Local constant propagation.
127//
128
129/// ConstantFoldTerminator - If a terminator instruction is predicated on a
130/// constant value, convert it into an unconditional branch to the constant
131/// destination. This is a nontrivial operation because the successors of this
132/// basic block must have their PHI nodes updated.
133/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
134/// conditions and indirectbr addresses this might make dead if
135/// DeleteDeadConditions is true.
136boolllvm::ConstantFoldTerminator(BasicBlock *BB,bool DeleteDeadConditions,
137constTargetLibraryInfo *TLI,
138DomTreeUpdater *DTU) {
139Instruction *T = BB->getTerminator();
140IRBuilder<> Builder(T);
141
142// Branch - See if we are conditional jumping on constant
143if (auto *BI = dyn_cast<BranchInst>(T)) {
144if (BI->isUnconditional())returnfalse;// Can't optimize uncond branch
145
146BasicBlock *Dest1 = BI->getSuccessor(0);
147BasicBlock *Dest2 = BI->getSuccessor(1);
148
149if (Dest2 == Dest1) {// Conditional branch to same location?
150// This branch matches something like this:
151// br bool %cond, label %Dest, label %Dest
152// and changes it into: br label %Dest
153
154// Let the basic block know that we are letting go of one copy of it.
155assert(BI->getParent() &&"Terminator not inserted in block!");
156 Dest1->removePredecessor(BI->getParent());
157
158// Replace the conditional branch with an unconditional one.
159BranchInst *NewBI = Builder.CreateBr(Dest1);
160
161// Transfer the metadata to the new branch instruction.
162 NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
163 LLVMContext::MD_annotation});
164
165Value *Cond = BI->getCondition();
166 BI->eraseFromParent();
167if (DeleteDeadConditions)
168RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
169returntrue;
170 }
171
172if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
173// Are we branching on constant?
174// YES. Change to unconditional branch...
175BasicBlock *Destination =Cond->getZExtValue() ? Dest1 : Dest2;
176BasicBlock *OldDest =Cond->getZExtValue() ? Dest2 : Dest1;
177
178// Let the basic block know that we are letting go of it. Based on this,
179// it will adjust it's PHI nodes.
180 OldDest->removePredecessor(BB);
181
182// Replace the conditional branch with an unconditional one.
183BranchInst *NewBI = Builder.CreateBr(Destination);
184
185// Transfer the metadata to the new branch instruction.
186 NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
187 LLVMContext::MD_annotation});
188
189 BI->eraseFromParent();
190if (DTU)
191 DTU->applyUpdates({{DominatorTree::Delete, BB, OldDest}});
192returntrue;
193 }
194
195returnfalse;
196 }
197
198if (auto *SI = dyn_cast<SwitchInst>(T)) {
199// If we are switching on a constant, we can convert the switch to an
200// unconditional branch.
201auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
202BasicBlock *DefaultDest = SI->getDefaultDest();
203BasicBlock *TheOnlyDest = DefaultDest;
204
205// If the default is unreachable, ignore it when searching for TheOnlyDest.
206if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
207 SI->getNumCases() > 0) {
208 TheOnlyDest = SI->case_begin()->getCaseSuccessor();
209 }
210
211bool Changed =false;
212
213// Figure out which case it goes to.
214for (auto It = SI->case_begin(),End = SI->case_end(); It !=End;) {
215// Found case matching a constant operand?
216if (It->getCaseValue() == CI) {
217 TheOnlyDest = It->getCaseSuccessor();
218break;
219 }
220
221// Check to see if this branch is going to the same place as the default
222// dest. If so, eliminate it as an explicit compare.
223if (It->getCaseSuccessor() == DefaultDest) {
224MDNode *MD =getValidBranchWeightMDNode(*SI);
225unsigned NCases = SI->getNumCases();
226// Fold the case metadata into the default if there will be any branches
227// left, unless the metadata doesn't match the switch.
228if (NCases > 1 && MD) {
229// Collect branch weights into a vector.
230SmallVector<uint32_t, 8> Weights;
231extractBranchWeights(MD, Weights);
232
233// Merge weight of this case to the default weight.
234unsignedIdx = It->getCaseIndex();
235// TODO: Add overflow check.
236 Weights[0] += Weights[Idx + 1];
237// Remove weight for this case.
238std::swap(Weights[Idx + 1], Weights.back());
239 Weights.pop_back();
240setBranchWeights(*SI, Weights,hasBranchWeightOrigin(MD));
241 }
242// Remove this entry.
243BasicBlock *ParentBB = SI->getParent();
244 DefaultDest->removePredecessor(ParentBB);
245 It = SI->removeCase(It);
246End = SI->case_end();
247
248// Removing this case may have made the condition constant. In that
249// case, update CI and restart iteration through the cases.
250if (auto *NewCI = dyn_cast<ConstantInt>(SI->getCondition())) {
251 CI = NewCI;
252 It = SI->case_begin();
253 }
254
255 Changed =true;
256continue;
257 }
258
259// Otherwise, check to see if the switch only branches to one destination.
260// We do this by reseting "TheOnlyDest" to null when we find two non-equal
261// destinations.
262if (It->getCaseSuccessor() != TheOnlyDest)
263 TheOnlyDest =nullptr;
264
265// Increment this iterator as we haven't removed the case.
266 ++It;
267 }
268
269if (CI && !TheOnlyDest) {
270// Branching on a constant, but not any of the cases, go to the default
271// successor.
272 TheOnlyDest = SI->getDefaultDest();
273 }
274
275// If we found a single destination that we can fold the switch into, do so
276// now.
277if (TheOnlyDest) {
278// Insert the new branch.
279 Builder.CreateBr(TheOnlyDest);
280BasicBlock *BB = SI->getParent();
281
282SmallSet<BasicBlock *, 8> RemovedSuccessors;
283
284// Remove entries from PHI nodes which we no longer branch to...
285BasicBlock *SuccToKeep = TheOnlyDest;
286for (BasicBlock *Succ :successors(SI)) {
287if (DTU && Succ != TheOnlyDest)
288 RemovedSuccessors.insert(Succ);
289// Found case matching a constant operand?
290if (Succ == SuccToKeep) {
291 SuccToKeep =nullptr;// Don't modify the first branch to TheOnlyDest
292 }else {
293 Succ->removePredecessor(BB);
294 }
295 }
296
297// Delete the old switch.
298Value *Cond = SI->getCondition();
299 SI->eraseFromParent();
300if (DeleteDeadConditions)
301RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
302if (DTU) {
303 std::vector<DominatorTree::UpdateType> Updates;
304 Updates.reserve(RemovedSuccessors.size());
305for (auto *RemovedSuccessor : RemovedSuccessors)
306 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
307 DTU->applyUpdates(Updates);
308 }
309returntrue;
310 }
311
312if (SI->getNumCases() == 1) {
313// Otherwise, we can fold this switch into a conditional branch
314// instruction if it has only one non-default destination.
315auto FirstCase = *SI->case_begin();
316Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
317 FirstCase.getCaseValue(),"cond");
318
319// Insert the new branch.
320BranchInst *NewBr = Builder.CreateCondBr(Cond,
321 FirstCase.getCaseSuccessor(),
322 SI->getDefaultDest());
323SmallVector<uint32_t> Weights;
324if (extractBranchWeights(*SI, Weights) && Weights.size() == 2) {
325uint32_t DefWeight = Weights[0];
326uint32_t CaseWeight = Weights[1];
327// The TrueWeight should be the weight for the single case of SI.
328 NewBr->setMetadata(LLVMContext::MD_prof,
329MDBuilder(BB->getContext())
330 .createBranchWeights(CaseWeight, DefWeight));
331 }
332
333// Update make.implicit metadata to the newly-created conditional branch.
334MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
335if (MakeImplicitMD)
336 NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
337
338// Delete the old switch.
339 SI->eraseFromParent();
340returntrue;
341 }
342return Changed;
343 }
344
345if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {
346// indirectbr blockaddress(@F, @BB) -> br label @BB
347if (auto *BA =
348 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
349BasicBlock *TheOnlyDest = BA->getBasicBlock();
350SmallSet<BasicBlock *, 8> RemovedSuccessors;
351
352// Insert the new branch.
353 Builder.CreateBr(TheOnlyDest);
354
355BasicBlock *SuccToKeep = TheOnlyDest;
356for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
357BasicBlock *DestBB = IBI->getDestination(i);
358if (DTU && DestBB != TheOnlyDest)
359 RemovedSuccessors.insert(DestBB);
360if (IBI->getDestination(i) == SuccToKeep) {
361 SuccToKeep =nullptr;
362 }else {
363 DestBB->removePredecessor(BB);
364 }
365 }
366Value *Address = IBI->getAddress();
367 IBI->eraseFromParent();
368if (DeleteDeadConditions)
369// Delete pointer cast instructions.
370RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
371
372// Also zap the blockaddress constant if there are no users remaining,
373// otherwise the destination is still marked as having its address taken.
374if (BA->use_empty())
375 BA->destroyConstant();
376
377// If we didn't find our destination in the IBI successor list, then we
378// have undefined behavior. Replace the unconditional branch with an
379// 'unreachable' instruction.
380if (SuccToKeep) {
381 BB->getTerminator()->eraseFromParent();
382newUnreachableInst(BB->getContext(), BB);
383 }
384
385if (DTU) {
386 std::vector<DominatorTree::UpdateType> Updates;
387 Updates.reserve(RemovedSuccessors.size());
388for (auto *RemovedSuccessor : RemovedSuccessors)
389 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
390 DTU->applyUpdates(Updates);
391 }
392returntrue;
393 }
394 }
395
396returnfalse;
397}
398
399//===----------------------------------------------------------------------===//
400// Local dead code elimination.
401//
402
403/// isInstructionTriviallyDead - Return true if the result produced by the
404/// instruction is not used, and the instruction has no side effects.
405///
406boolllvm::isInstructionTriviallyDead(Instruction *I,
407constTargetLibraryInfo *TLI) {
408if (!I->use_empty())
409returnfalse;
410returnwouldInstructionBeTriviallyDead(I, TLI);
411}
412
413boolllvm::wouldInstructionBeTriviallyDeadOnUnusedPaths(
414Instruction *I,constTargetLibraryInfo *TLI) {
415// Instructions that are "markers" and have implied meaning on code around
416// them (without explicit uses), are not dead on unused paths.
417if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
418if (II->getIntrinsicID() == Intrinsic::stacksave ||
419II->getIntrinsicID() == Intrinsic::launder_invariant_group ||
420II->isLifetimeStartOrEnd())
421returnfalse;
422returnwouldInstructionBeTriviallyDead(I, TLI);
423}
424
425boolllvm::wouldInstructionBeTriviallyDead(constInstruction *I,
426constTargetLibraryInfo *TLI) {
427if (I->isTerminator())
428returnfalse;
429
430// We don't want the landingpad-like instructions removed by anything this
431// general.
432if (I->isEHPad())
433returnfalse;
434
435// We don't want debug info removed by anything this general.
436if (isa<DbgVariableIntrinsic>(I))
437returnfalse;
438
439if (constDbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
440if (DLI->getLabel())
441returnfalse;
442returntrue;
443 }
444
445if (auto *CB = dyn_cast<CallBase>(I))
446if (isRemovableAlloc(CB, TLI))
447returntrue;
448
449if (!I->willReturn()) {
450auto *II = dyn_cast<IntrinsicInst>(I);
451if (!II)
452returnfalse;
453
454switch (II->getIntrinsicID()) {
455case Intrinsic::experimental_guard: {
456// Guards on true are operationally no-ops. In the future we can
457// consider more sophisticated tradeoffs for guards considering potential
458// for check widening, but for now we keep things simple.
459auto *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0));
460returnCond &&Cond->isOne();
461 }
462// TODO: These intrinsics are not safe to remove, because this may remove
463// a well-defined trap.
464case Intrinsic::wasm_trunc_signed:
465case Intrinsic::wasm_trunc_unsigned:
466case Intrinsic::ptrauth_auth:
467case Intrinsic::ptrauth_resign:
468returntrue;
469default:
470returnfalse;
471 }
472 }
473
474if (!I->mayHaveSideEffects())
475returntrue;
476
477// Special case intrinsics that "may have side effects" but can be deleted
478// when dead.
479if (constIntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
480// Safe to delete llvm.stacksave and launder.invariant.group if dead.
481if (II->getIntrinsicID() == Intrinsic::stacksave ||
482II->getIntrinsicID() == Intrinsic::launder_invariant_group)
483returntrue;
484
485// Intrinsics declare sideeffects to prevent them from moving, but they are
486// nops without users.
487if (II->getIntrinsicID() == Intrinsic::allow_runtime_check ||
488II->getIntrinsicID() == Intrinsic::allow_ubsan_check)
489returntrue;
490
491if (II->isLifetimeStartOrEnd()) {
492auto *Arg =II->getArgOperand(1);
493// Lifetime intrinsics are dead when their right-hand is undef.
494if (isa<UndefValue>(Arg))
495returntrue;
496// If the right-hand is an alloc, global, or argument and the only uses
497// are lifetime intrinsics then the intrinsics are dead.
498if (isa<AllocaInst>(Arg) || isa<GlobalValue>(Arg) || isa<Argument>(Arg))
499returnllvm::all_of(Arg->uses(), [](Use &Use) {
500 if (IntrinsicInst *IntrinsicUse =
501 dyn_cast<IntrinsicInst>(Use.getUser()))
502 return IntrinsicUse->isLifetimeStartOrEnd();
503 return false;
504 });
505returnfalse;
506 }
507
508// Assumptions are dead if their condition is trivially true.
509if (II->getIntrinsicID() == Intrinsic::assume &&
510isAssumeWithEmptyBundle(cast<AssumeInst>(*II))) {
511if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
512return !Cond->isZero();
513
514returnfalse;
515 }
516
517if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(I)) {
518 std::optional<fp::ExceptionBehavior> ExBehavior =
519 FPI->getExceptionBehavior();
520return *ExBehavior !=fp::ebStrict;
521 }
522 }
523
524if (auto *Call = dyn_cast<CallBase>(I)) {
525if (Value *FreedOp =getFreedOperand(Call, TLI))
526if (Constant *C = dyn_cast<Constant>(FreedOp))
527returnC->isNullValue() || isa<UndefValue>(C);
528if (isMathLibCallNoop(Call, TLI))
529returntrue;
530 }
531
532// Non-volatile atomic loads from constants can be removed.
533if (auto *LI = dyn_cast<LoadInst>(I))
534if (auto *GV = dyn_cast<GlobalVariable>(
535 LI->getPointerOperand()->stripPointerCasts()))
536if (!LI->isVolatile() && GV->isConstant())
537returntrue;
538
539returnfalse;
540}
541
542/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
543/// trivially dead instruction, delete it. If that makes any of its operands
544/// trivially dead, delete them too, recursively. Return true if any
545/// instructions were deleted.
546boolllvm::RecursivelyDeleteTriviallyDeadInstructions(
547Value *V,constTargetLibraryInfo *TLI,MemorySSAUpdater *MSSAU,
548 std::function<void(Value *)> AboutToDeleteCallback) {
549Instruction *I = dyn_cast<Instruction>(V);
550if (!I || !isInstructionTriviallyDead(I, TLI))
551returnfalse;
552
553SmallVector<WeakTrackingVH, 16> DeadInsts;
554 DeadInsts.push_back(I);
555RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
556 AboutToDeleteCallback);
557
558returntrue;
559}
560
561boolllvm::RecursivelyDeleteTriviallyDeadInstructionsPermissive(
562SmallVectorImpl<WeakTrackingVH> &DeadInsts,constTargetLibraryInfo *TLI,
563MemorySSAUpdater *MSSAU,
564 std::function<void(Value *)> AboutToDeleteCallback) {
565unsigned S = 0, E = DeadInsts.size(), Alive = 0;
566for (; S != E; ++S) {
567auto *I = dyn_cast_or_null<Instruction>(DeadInsts[S]);
568if (!I || !isInstructionTriviallyDead(I)) {
569 DeadInsts[S] =nullptr;
570 ++Alive;
571 }
572 }
573if (Alive == E)
574returnfalse;
575RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
576 AboutToDeleteCallback);
577returntrue;
578}
579
580voidllvm::RecursivelyDeleteTriviallyDeadInstructions(
581SmallVectorImpl<WeakTrackingVH> &DeadInsts,constTargetLibraryInfo *TLI,
582MemorySSAUpdater *MSSAU,
583 std::function<void(Value *)> AboutToDeleteCallback) {
584// Process the dead instruction list until empty.
585while (!DeadInsts.empty()) {
586Value *V = DeadInsts.pop_back_val();
587Instruction *I = cast_or_null<Instruction>(V);
588if (!I)
589continue;
590assert(isInstructionTriviallyDead(I, TLI) &&
591"Live instruction found in dead worklist!");
592assert(I->use_empty() &&"Instructions with uses are not dead.");
593
594// Don't lose the debug info while deleting the instructions.
595salvageDebugInfo(*I);
596
597if (AboutToDeleteCallback)
598 AboutToDeleteCallback(I);
599
600// Null out all of the instruction's operands to see if any operand becomes
601// dead as we go.
602for (Use &OpU :I->operands()) {
603Value *OpV = OpU.get();
604 OpU.set(nullptr);
605
606if (!OpV->use_empty())
607continue;
608
609// If the operand is an instruction that became dead as we nulled out the
610// operand, and if it is 'trivially' dead, delete it in a future loop
611// iteration.
612if (Instruction *OpI = dyn_cast<Instruction>(OpV))
613if (isInstructionTriviallyDead(OpI, TLI))
614 DeadInsts.push_back(OpI);
615 }
616if (MSSAU)
617 MSSAU->removeMemoryAccess(I);
618
619I->eraseFromParent();
620 }
621}
622
623boolllvm::replaceDbgUsesWithUndef(Instruction *I) {
624SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
625SmallVector<DbgVariableRecord *, 1> DPUsers;
626findDbgUsers(DbgUsers,I, &DPUsers);
627for (auto *DII : DbgUsers)
628 DII->setKillLocation();
629for (auto *DVR : DPUsers)
630 DVR->setKillLocation();
631return !DbgUsers.empty() || !DPUsers.empty();
632}
633
634/// areAllUsesEqual - Check whether the uses of a value are all the same.
635/// This is similar to Instruction::hasOneUse() except this will also return
636/// true when there are no uses or multiple uses that all refer to the same
637/// value.
638staticboolareAllUsesEqual(Instruction *I) {
639Value::user_iterator UI =I->user_begin();
640Value::user_iterator UE =I->user_end();
641if (UI == UE)
642returntrue;
643
644User *TheUse = *UI;
645for (++UI; UI != UE; ++UI) {
646if (*UI != TheUse)
647returnfalse;
648 }
649returntrue;
650}
651
652/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
653/// dead PHI node, due to being a def-use chain of single-use nodes that
654/// either forms a cycle or is terminated by a trivially dead instruction,
655/// delete it. If that makes any of its operands trivially dead, delete them
656/// too, recursively. Return true if a change was made.
657boolllvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
658constTargetLibraryInfo *TLI,
659llvm::MemorySSAUpdater *MSSAU) {
660SmallPtrSet<Instruction*, 4> Visited;
661for (Instruction *I = PN;areAllUsesEqual(I) && !I->mayHaveSideEffects();
662I = cast<Instruction>(*I->user_begin())) {
663if (I->use_empty())
664returnRecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
665
666// If we find an instruction more than once, we're on a cycle that
667// won't prove fruitful.
668if (!Visited.insert(I).second) {
669// Break the cycle and delete the instruction and its operands.
670I->replaceAllUsesWith(PoisonValue::get(I->getType()));
671 (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
672returntrue;
673 }
674 }
675returnfalse;
676}
677
678staticbool
679simplifyAndDCEInstruction(Instruction *I,
680SmallSetVector<Instruction *, 16> &WorkList,
681constDataLayout &DL,
682constTargetLibraryInfo *TLI) {
683if (isInstructionTriviallyDead(I, TLI)) {
684salvageDebugInfo(*I);
685
686// Null out all of the instruction's operands to see if any operand becomes
687// dead as we go.
688for (unsigned i = 0, e =I->getNumOperands(); i != e; ++i) {
689Value *OpV =I->getOperand(i);
690I->setOperand(i,nullptr);
691
692if (!OpV->use_empty() ||I == OpV)
693continue;
694
695// If the operand is an instruction that became dead as we nulled out the
696// operand, and if it is 'trivially' dead, delete it in a future loop
697// iteration.
698if (Instruction *OpI = dyn_cast<Instruction>(OpV))
699if (isInstructionTriviallyDead(OpI, TLI))
700 WorkList.insert(OpI);
701 }
702
703I->eraseFromParent();
704
705returntrue;
706 }
707
708if (Value *SimpleV =simplifyInstruction(I,DL)) {
709// Add the users to the worklist. CAREFUL: an instruction can use itself,
710// in the case of a phi node.
711for (User *U :I->users()) {
712if (U !=I) {
713 WorkList.insert(cast<Instruction>(U));
714 }
715 }
716
717// Replace the instruction with its simplified value.
718bool Changed =false;
719if (!I->use_empty()) {
720I->replaceAllUsesWith(SimpleV);
721 Changed =true;
722 }
723if (isInstructionTriviallyDead(I, TLI)) {
724I->eraseFromParent();
725 Changed =true;
726 }
727return Changed;
728 }
729returnfalse;
730}
731
732/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
733/// simplify any instructions in it and recursively delete dead instructions.
734///
735/// This returns true if it changed the code, note that it can delete
736/// instructions in other blocks as well in this block.
737boolllvm::SimplifyInstructionsInBlock(BasicBlock *BB,
738constTargetLibraryInfo *TLI) {
739bool MadeChange =false;
740constDataLayout &DL = BB->getDataLayout();
741
742#ifndef NDEBUG
743// In debug builds, ensure that the terminator of the block is never replaced
744// or deleted by these simplifications. The idea of simplification is that it
745// cannot introduce new instructions, and there is no way to replace the
746// terminator of a block without introducing a new instruction.
747AssertingVH<Instruction> TerminatorVH(&BB->back());
748#endif
749
750SmallSetVector<Instruction *, 16> WorkList;
751// Iterate over the original function, only adding insts to the worklist
752// if they actually need to be revisited. This avoids having to pre-init
753// the worklist with the entire function's worth of instructions.
754for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
755 BI != E;) {
756assert(!BI->isTerminator());
757Instruction *I = &*BI;
758 ++BI;
759
760// We're visiting this instruction now, so make sure it's not in the
761// worklist from an earlier visit.
762if (!WorkList.count(I))
763 MadeChange |=simplifyAndDCEInstruction(I, WorkList,DL, TLI);
764 }
765
766while (!WorkList.empty()) {
767Instruction *I = WorkList.pop_back_val();
768 MadeChange |=simplifyAndDCEInstruction(I, WorkList,DL, TLI);
769 }
770return MadeChange;
771}
772
773//===----------------------------------------------------------------------===//
774// Control Flow Graph Restructuring.
775//
776
777voidllvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
778DomTreeUpdater *DTU) {
779
780// If BB has single-entry PHI nodes, fold them.
781while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
782Value *NewVal = PN->getIncomingValue(0);
783// Replace self referencing PHI with poison, it must be dead.
784if (NewVal == PN) NewVal =PoisonValue::get(PN->getType());
785 PN->replaceAllUsesWith(NewVal);
786 PN->eraseFromParent();
787 }
788
789BasicBlock *PredBB = DestBB->getSinglePredecessor();
790assert(PredBB &&"Block doesn't have a single predecessor!");
791
792bool ReplaceEntryBB = PredBB->isEntryBlock();
793
794// DTU updates: Collect all the edges that enter
795// PredBB. These dominator edges will be redirected to DestBB.
796SmallVector<DominatorTree::UpdateType, 32> Updates;
797
798if (DTU) {
799// To avoid processing the same predecessor more than once.
800SmallPtrSet<BasicBlock *, 2> SeenPreds;
801 Updates.reserve(Updates.size() + 2 *pred_size(PredBB) + 1);
802for (BasicBlock *PredOfPredBB :predecessors(PredBB))
803// This predecessor of PredBB may already have DestBB as a successor.
804if (PredOfPredBB != PredBB)
805if (SeenPreds.insert(PredOfPredBB).second)
806 Updates.push_back({DominatorTree::Insert, PredOfPredBB, DestBB});
807 SeenPreds.clear();
808for (BasicBlock *PredOfPredBB :predecessors(PredBB))
809if (SeenPreds.insert(PredOfPredBB).second)
810 Updates.push_back({DominatorTree::Delete, PredOfPredBB, PredBB});
811 Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
812 }
813
814// Zap anything that took the address of DestBB. Not doing this will give the
815// address an invalid value.
816if (DestBB->hasAddressTaken()) {
817BlockAddress *BA =BlockAddress::get(DestBB);
818Constant *Replacement =
819 ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
820 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
821 BA->getType()));
822 BA->destroyConstant();
823 }
824
825// Anything that branched to PredBB now branches to DestBB.
826 PredBB->replaceAllUsesWith(DestBB);
827
828// Splice all the instructions from PredBB to DestBB.
829 PredBB->getTerminator()->eraseFromParent();
830 DestBB->splice(DestBB->begin(), PredBB);
831newUnreachableInst(PredBB->getContext(), PredBB);
832
833// If the PredBB is the entry block of the function, move DestBB up to
834// become the entry block after we erase PredBB.
835if (ReplaceEntryBB)
836 DestBB->moveAfter(PredBB);
837
838if (DTU) {
839assert(PredBB->size() == 1 &&
840 isa<UnreachableInst>(PredBB->getTerminator()) &&
841"The successor list of PredBB isn't empty before "
842"applying corresponding DTU updates.");
843 DTU->applyUpdatesPermissive(Updates);
844 DTU->deleteBB(PredBB);
845// Recalculation of DomTree is needed when updating a forward DomTree and
846// the Entry BB is replaced.
847if (ReplaceEntryBB && DTU->hasDomTree()) {
848// The entry block was removed and there is no external interface for
849// the dominator tree to be notified of this change. In this corner-case
850// we recalculate the entire tree.
851 DTU->recalculate(*(DestBB->getParent()));
852 }
853 }
854
855else {
856 PredBB->eraseFromParent();// Nuke BB if DTU is nullptr.
857 }
858}
859
860/// Return true if we can choose one of these values to use in place of the
861/// other. Note that we will always choose the non-undef value to keep.
862staticboolCanMergeValues(Value *First,Value *Second) {
863returnFirst == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
864}
865
866/// Return true if we can fold BB, an almost-empty BB ending in an unconditional
867/// branch to Succ, into Succ.
868///
869/// Assumption: Succ is the single successor for BB.
870staticbool
871CanPropagatePredecessorsForPHIs(BasicBlock *BB,BasicBlock *Succ,
872constSmallPtrSetImpl<BasicBlock *> &BBPreds) {
873assert(*succ_begin(BB) == Succ &&"Succ is not successor of BB!");
874
875LLVM_DEBUG(dbgs() <<"Looking to fold " << BB->getName() <<" into "
876 << Succ->getName() <<"\n");
877// Shortcut, if there is only a single predecessor it must be BB and merging
878// is always safe
879if (Succ->getSinglePredecessor())
880returntrue;
881
882// Look at all the phi nodes in Succ, to see if they present a conflict when
883// merging these blocks
884for (BasicBlock::iteratorI = Succ->begin(); isa<PHINode>(I); ++I) {
885PHINode *PN = cast<PHINode>(I);
886
887// If the incoming value from BB is again a PHINode in
888// BB which has the same incoming value for *PI as PN does, we can
889// merge the phi nodes and then the blocks can still be merged
890PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
891if (BBPN && BBPN->getParent() == BB) {
892for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
893BasicBlock *IBB = PN->getIncomingBlock(PI);
894if (BBPreds.count(IBB) &&
895 !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
896 PN->getIncomingValue(PI))) {
897LLVM_DEBUG(dbgs()
898 <<"Can't fold, phi node " << PN->getName() <<" in "
899 << Succ->getName() <<" is conflicting with "
900 << BBPN->getName() <<" with regard to common predecessor "
901 << IBB->getName() <<"\n");
902returnfalse;
903 }
904 }
905 }else {
906Value* Val = PN->getIncomingValueForBlock(BB);
907for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
908// See if the incoming value for the common predecessor is equal to the
909// one for BB, in which case this phi node will not prevent the merging
910// of the block.
911BasicBlock *IBB = PN->getIncomingBlock(PI);
912if (BBPreds.count(IBB) &&
913 !CanMergeValues(Val, PN->getIncomingValue(PI))) {
914LLVM_DEBUG(dbgs() <<"Can't fold, phi node " << PN->getName()
915 <<" in " << Succ->getName()
916 <<" is conflicting with regard to common "
917 <<"predecessor " << IBB->getName() <<"\n");
918returnfalse;
919 }
920 }
921 }
922 }
923
924returntrue;
925}
926
927usingPredBlockVector =SmallVector<BasicBlock *, 16>;
928usingIncomingValueMap =SmallDenseMap<BasicBlock *, Value *, 16>;
929
930/// Determines the value to use as the phi node input for a block.
931///
932/// Select between \p OldVal any value that we know flows from \p BB
933/// to a particular phi on the basis of which one (if either) is not
934/// undef. Update IncomingValues based on the selected value.
935///
936/// \param OldVal The value we are considering selecting.
937/// \param BB The block that the value flows in from.
938/// \param IncomingValues A map from block-to-value for other phi inputs
939/// that we have examined.
940///
941/// \returns the selected value.
942staticValue *selectIncomingValueForBlock(Value *OldVal,BasicBlock *BB,
943IncomingValueMap &IncomingValues) {
944if (!isa<UndefValue>(OldVal)) {
945assert((!IncomingValues.count(BB) ||
946 IncomingValues.find(BB)->second == OldVal) &&
947"Expected OldVal to match incoming value from BB!");
948
949 IncomingValues.insert(std::make_pair(BB, OldVal));
950return OldVal;
951 }
952
953IncomingValueMap::const_iterator It = IncomingValues.find(BB);
954if (It != IncomingValues.end())return It->second;
955
956return OldVal;
957}
958
959/// Create a map from block to value for the operands of a
960/// given phi.
961///
962/// Create a map from block to value for each non-undef value flowing
963/// into \p PN.
964///
965/// \param PN The phi we are collecting the map for.
966/// \param IncomingValues [out] The map from block to value for this phi.
967staticvoidgatherIncomingValuesToPhi(PHINode *PN,
968IncomingValueMap &IncomingValues) {
969for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
970BasicBlock *BB = PN->getIncomingBlock(i);
971Value *V = PN->getIncomingValue(i);
972
973if (!isa<UndefValue>(V))
974 IncomingValues.insert(std::make_pair(BB, V));
975 }
976}
977
978/// Replace the incoming undef values to a phi with the values
979/// from a block-to-value map.
980///
981/// \param PN The phi we are replacing the undefs in.
982/// \param IncomingValues A map from block to value.
983staticvoidreplaceUndefValuesInPhi(PHINode *PN,
984constIncomingValueMap &IncomingValues) {
985SmallVector<unsigned> TrueUndefOps;
986for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
987Value *V = PN->getIncomingValue(i);
988
989if (!isa<UndefValue>(V))continue;
990
991BasicBlock *BB = PN->getIncomingBlock(i);
992IncomingValueMap::const_iterator It = IncomingValues.find(BB);
993
994// Keep track of undef/poison incoming values. Those must match, so we fix
995// them up below if needed.
996// Note: this is conservatively correct, but we could try harder and group
997// the undef values per incoming basic block.
998if (It == IncomingValues.end()) {
999 TrueUndefOps.push_back(i);
1000continue;
1001 }
1002
1003// There is a defined value for this incoming block, so map this undef
1004// incoming value to the defined value.
1005 PN->setIncomingValue(i, It->second);
1006 }
1007
1008// If there are both undef and poison values incoming, then convert those
1009// values to undef. It is invalid to have different values for the same
1010// incoming block.
1011unsigned PoisonCount =count_if(TrueUndefOps, [&](unsigned i) {
1012return isa<PoisonValue>(PN->getIncomingValue(i));
1013 });
1014if (PoisonCount != 0 && PoisonCount != TrueUndefOps.size()) {
1015for (unsigned i : TrueUndefOps)
1016 PN->setIncomingValue(i,UndefValue::get(PN->getType()));
1017 }
1018}
1019
1020// Only when they shares a single common predecessor, return true.
1021// Only handles cases when BB can't be merged while its predecessors can be
1022// redirected.
1023staticbool
1024CanRedirectPredsOfEmptyBBToSucc(BasicBlock *BB,BasicBlock *Succ,
1025constSmallPtrSetImpl<BasicBlock *> &BBPreds,
1026BasicBlock *&CommonPred) {
1027
1028// There must be phis in BB, otherwise BB will be merged into Succ directly
1029if (BB->phis().empty() || Succ->phis().empty())
1030returnfalse;
1031
1032// BB must have predecessors not shared that can be redirected to Succ
1033if (!BB->hasNPredecessorsOrMore(2))
1034returnfalse;
1035
1036if (any_of(BBPreds, [](constBasicBlock *Pred) {
1037return isa<IndirectBrInst>(Pred->getTerminator());
1038 }))
1039returnfalse;
1040
1041// Get the single common predecessor of both BB and Succ. Return false
1042// when there are more than one common predecessors.
1043for (BasicBlock *SuccPred :predecessors(Succ)) {
1044if (BBPreds.count(SuccPred)) {
1045if (CommonPred)
1046returnfalse;
1047 CommonPred = SuccPred;
1048 }
1049 }
1050
1051returntrue;
1052}
1053
1054/// Check whether removing \p BB will make the phis in its \p Succ have too
1055/// many incoming entries. This function does not check whether \p BB is
1056/// foldable or not.
1057staticboolintroduceTooManyPhiEntries(BasicBlock *BB,BasicBlock *Succ) {
1058// If BB only has one predecessor, then removing it will not introduce more
1059// incoming edges for phis.
1060if (BB->hasNPredecessors(1))
1061returnfalse;
1062unsigned NumPreds =pred_size(BB);
1063unsigned NumChangedPhi = 0;
1064for (auto &Phi : Succ->phis()) {
1065// If the incoming value is a phi and the phi is defined in BB,
1066// then removing BB will not increase the total phi entries of the ir.
1067if (auto *IncomingPhi = dyn_cast<PHINode>(Phi.getIncomingValueForBlock(BB)))
1068if (IncomingPhi->getParent() == BB)
1069continue;
1070// Otherwise, we need to add entries to the phi
1071 NumChangedPhi++;
1072 }
1073// For every phi that needs to be changed, (NumPreds - 1) new entries will be
1074// added. If the total increase in phi entries exceeds
1075// MaxPhiEntriesIncreaseAfterRemovingEmptyBlock, it will be considered as
1076// introducing too many new phi entries.
1077return (NumPreds - 1) * NumChangedPhi >
1078MaxPhiEntriesIncreaseAfterRemovingEmptyBlock;
1079}
1080
1081/// Replace a value flowing from a block to a phi with
1082/// potentially multiple instances of that value flowing from the
1083/// block's predecessors to the phi.
1084///
1085/// \param BB The block with the value flowing into the phi.
1086/// \param BBPreds The predecessors of BB.
1087/// \param PN The phi that we are updating.
1088/// \param CommonPred The common predecessor of BB and PN's BasicBlock
1089staticvoidredirectValuesFromPredecessorsToPhi(BasicBlock *BB,
1090constPredBlockVector &BBPreds,
1091PHINode *PN,
1092BasicBlock *CommonPred) {
1093Value *OldVal = PN->removeIncomingValue(BB,false);
1094assert(OldVal &&"No entry in PHI for Pred BB!");
1095
1096IncomingValueMap IncomingValues;
1097
1098// We are merging two blocks - BB, and the block containing PN - and
1099// as a result we need to redirect edges from the predecessors of BB
1100// to go to the block containing PN, and update PN
1101// accordingly. Since we allow merging blocks in the case where the
1102// predecessor and successor blocks both share some predecessors,
1103// and where some of those common predecessors might have undef
1104// values flowing into PN, we want to rewrite those values to be
1105// consistent with the non-undef values.
1106
1107gatherIncomingValuesToPhi(PN, IncomingValues);
1108
1109// If this incoming value is one of the PHI nodes in BB, the new entries
1110// in the PHI node are the entries from the old PHI.
1111if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
1112PHINode *OldValPN = cast<PHINode>(OldVal);
1113for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
1114// Note that, since we are merging phi nodes and BB and Succ might
1115// have common predecessors, we could end up with a phi node with
1116// identical incoming branches. This will be cleaned up later (and
1117// will trigger asserts if we try to clean it up now, without also
1118// simplifying the corresponding conditional branch).
1119BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
1120
1121if (PredBB == CommonPred)
1122continue;
1123
1124Value *PredVal = OldValPN->getIncomingValue(i);
1125Value *Selected =
1126selectIncomingValueForBlock(PredVal, PredBB, IncomingValues);
1127
1128// And add a new incoming value for this predecessor for the
1129// newly retargeted branch.
1130 PN->addIncoming(Selected, PredBB);
1131 }
1132if (CommonPred)
1133 PN->addIncoming(OldValPN->getIncomingValueForBlock(CommonPred), BB);
1134
1135 }else {
1136for (BasicBlock *PredBB : BBPreds) {
1137// Update existing incoming values in PN for this
1138// predecessor of BB.
1139if (PredBB == CommonPred)
1140continue;
1141
1142Value *Selected =
1143selectIncomingValueForBlock(OldVal, PredBB, IncomingValues);
1144
1145// And add a new incoming value for this predecessor for the
1146// newly retargeted branch.
1147 PN->addIncoming(Selected, PredBB);
1148 }
1149if (CommonPred)
1150 PN->addIncoming(OldVal, BB);
1151 }
1152
1153replaceUndefValuesInPhi(PN, IncomingValues);
1154}
1155
1156boolllvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
1157DomTreeUpdater *DTU) {
1158assert(BB != &BB->getParent()->getEntryBlock() &&
1159"TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
1160
1161// We can't simplify infinite loops.
1162BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
1163if (BB == Succ)
1164returnfalse;
1165
1166SmallPtrSet<BasicBlock *, 16> BBPreds(pred_begin(BB),pred_end(BB));
1167
1168// The single common predecessor of BB and Succ when BB cannot be killed
1169BasicBlock *CommonPred =nullptr;
1170
1171bool BBKillable =CanPropagatePredecessorsForPHIs(BB, Succ, BBPreds);
1172
1173// Even if we can not fold BB into Succ, we may be able to redirect the
1174// predecessors of BB to Succ.
1175bool BBPhisMergeable = BBKillable ||CanRedirectPredsOfEmptyBBToSucc(
1176 BB, Succ, BBPreds, CommonPred);
1177
1178if ((!BBKillable && !BBPhisMergeable) ||introduceTooManyPhiEntries(BB, Succ))
1179returnfalse;
1180
1181// Check to see if merging these blocks/phis would cause conflicts for any of
1182// the phi nodes in BB or Succ. If not, we can safely merge.
1183
1184// Check for cases where Succ has multiple predecessors and a PHI node in BB
1185// has uses which will not disappear when the PHI nodes are merged. It is
1186// possible to handle such cases, but difficult: it requires checking whether
1187// BB dominates Succ, which is non-trivial to calculate in the case where
1188// Succ has multiple predecessors. Also, it requires checking whether
1189// constructing the necessary self-referential PHI node doesn't introduce any
1190// conflicts; this isn't too difficult, but the previous code for doing this
1191// was incorrect.
1192//
1193// Note that if this check finds a live use, BB dominates Succ, so BB is
1194// something like a loop pre-header (or rarely, a part of an irreducible CFG);
1195// folding the branch isn't profitable in that case anyway.
1196if (!Succ->getSinglePredecessor()) {
1197BasicBlock::iterator BBI = BB->begin();
1198while (isa<PHINode>(*BBI)) {
1199for (Use &U : BBI->uses()) {
1200if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
1201if (PN->getIncomingBlock(U) != BB)
1202returnfalse;
1203 }else {
1204returnfalse;
1205 }
1206 }
1207 ++BBI;
1208 }
1209 }
1210
1211if (BBPhisMergeable && CommonPred)
1212LLVM_DEBUG(dbgs() <<"Found Common Predecessor between: " << BB->getName()
1213 <<" and " << Succ->getName() <<" : "
1214 << CommonPred->getName() <<"\n");
1215
1216// 'BB' and 'BB->Pred' are loop latches, bail out to presrve inner loop
1217// metadata.
1218//
1219// FIXME: This is a stop-gap solution to preserve inner-loop metadata given
1220// current status (that loop metadata is implemented as metadata attached to
1221// the branch instruction in the loop latch block). To quote from review
1222// comments, "the current representation of loop metadata (using a loop latch
1223// terminator attachment) is known to be fundamentally broken. Loop latches
1224// are not uniquely associated with loops (both in that a latch can be part of
1225// multiple loops and a loop may have multiple latches). Loop headers are. The
1226// solution to this problem is also known: Add support for basic block
1227// metadata, and attach loop metadata to the loop header."
1228//
1229// Why bail out:
1230// In this case, we expect 'BB' is the latch for outer-loop and 'BB->Pred' is
1231// the latch for inner-loop (see reason below), so bail out to prerserve
1232// inner-loop metadata rather than eliminating 'BB' and attaching its metadata
1233// to this inner-loop.
1234// - The reason we believe 'BB' and 'BB->Pred' have different inner-most
1235// loops: assuming 'BB' and 'BB->Pred' are from the same inner-most loop L,
1236// then 'BB' is the header and latch of 'L' and thereby 'L' must consist of
1237// one self-looping basic block, which is contradictory with the assumption.
1238//
1239// To illustrate how inner-loop metadata is dropped:
1240//
1241// CFG Before
1242//
1243// BB is while.cond.exit, attached with loop metdata md2.
1244// BB->Pred is for.body, attached with loop metadata md1.
1245//
1246// entry
1247// |
1248// v
1249// ---> while.cond -------------> while.end
1250// | |
1251// | v
1252// | while.body
1253// | |
1254// | v
1255// | for.body <---- (md1)
1256// | | |______|
1257// | v
1258// | while.cond.exit (md2)
1259// | |
1260// |_______|
1261//
1262// CFG After
1263//
1264// while.cond1 is the merge of while.cond.exit and while.cond above.
1265// for.body is attached with md2, and md1 is dropped.
1266// If LoopSimplify runs later (as a part of loop pass), it could create
1267// dedicated exits for inner-loop (essentially adding `while.cond.exit`
1268// back), but won't it won't see 'md1' nor restore it for the inner-loop.
1269//
1270// entry
1271// |
1272// v
1273// ---> while.cond1 -------------> while.end
1274// | |
1275// | v
1276// | while.body
1277// | |
1278// | v
1279// | for.body <---- (md2)
1280// |_______| |______|
1281if (Instruction *TI = BB->getTerminator())
1282if (TI->hasNonDebugLocLoopMetadata())
1283for (BasicBlock *Pred :predecessors(BB))
1284if (Instruction *PredTI = Pred->getTerminator())
1285if (PredTI->hasNonDebugLocLoopMetadata())
1286returnfalse;
1287
1288if (BBKillable)
1289LLVM_DEBUG(dbgs() <<"Killing Trivial BB: \n" << *BB);
1290elseif (BBPhisMergeable)
1291LLVM_DEBUG(dbgs() <<"Merge Phis in Trivial BB: \n" << *BB);
1292
1293SmallVector<DominatorTree::UpdateType, 32> Updates;
1294
1295if (DTU) {
1296// To avoid processing the same predecessor more than once.
1297SmallPtrSet<BasicBlock *, 8> SeenPreds;
1298// All predecessors of BB (except the common predecessor) will be moved to
1299// Succ.
1300 Updates.reserve(Updates.size() + 2 *pred_size(BB) + 1);
1301SmallPtrSet<BasicBlock *, 16> SuccPreds(pred_begin(Succ),pred_end(Succ));
1302for (auto *PredOfBB :predecessors(BB)) {
1303// Do not modify those common predecessors of BB and Succ
1304if (!SuccPreds.contains(PredOfBB))
1305if (SeenPreds.insert(PredOfBB).second)
1306 Updates.push_back({DominatorTree::Insert, PredOfBB, Succ});
1307 }
1308
1309 SeenPreds.clear();
1310
1311for (auto *PredOfBB :predecessors(BB))
1312// When BB cannot be killed, do not remove the edge between BB and
1313// CommonPred.
1314if (SeenPreds.insert(PredOfBB).second && PredOfBB != CommonPred)
1315 Updates.push_back({DominatorTree::Delete, PredOfBB, BB});
1316
1317if (BBKillable)
1318 Updates.push_back({DominatorTree::Delete, BB, Succ});
1319 }
1320
1321if (isa<PHINode>(Succ->begin())) {
1322// If there is more than one pred of succ, and there are PHI nodes in
1323// the successor, then we need to add incoming edges for the PHI nodes
1324//
1325constPredBlockVector BBPreds(predecessors(BB));
1326
1327// Loop over all of the PHI nodes in the successor of BB.
1328for (BasicBlock::iteratorI = Succ->begin(); isa<PHINode>(I); ++I) {
1329PHINode *PN = cast<PHINode>(I);
1330redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN, CommonPred);
1331 }
1332 }
1333
1334if (Succ->getSinglePredecessor()) {
1335// BB is the only predecessor of Succ, so Succ will end up with exactly
1336// the same predecessors BB had.
1337// Copy over any phi, debug or lifetime instruction.
1338 BB->getTerminator()->eraseFromParent();
1339 Succ->splice(Succ->getFirstNonPHIIt(), BB);
1340 }else {
1341while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1342// We explicitly check for such uses for merging phis.
1343assert(PN->use_empty() &&"There shouldn't be any uses here!");
1344 PN->eraseFromParent();
1345 }
1346 }
1347
1348// If the unconditional branch we replaced contains non-debug llvm.loop
1349// metadata, we add the metadata to the branch instructions in the
1350// predecessors.
1351if (Instruction *TI = BB->getTerminator())
1352if (TI->hasNonDebugLocLoopMetadata()) {
1353MDNode *LoopMD = TI->getMetadata(LLVMContext::MD_loop);
1354for (BasicBlock *Pred :predecessors(BB))
1355 Pred->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopMD);
1356 }
1357
1358if (BBKillable) {
1359// Everything that jumped to BB now goes to Succ.
1360 BB->replaceAllUsesWith(Succ);
1361
1362if (!Succ->hasName())
1363 Succ->takeName(BB);
1364
1365// Clear the successor list of BB to match updates applying to DTU later.
1366if (BB->getTerminator())
1367 BB->back().eraseFromParent();
1368
1369newUnreachableInst(BB->getContext(), BB);
1370assert(succ_empty(BB) &&"The successor list of BB isn't empty before "
1371"applying corresponding DTU updates.");
1372 }elseif (BBPhisMergeable) {
1373// Everything except CommonPred that jumped to BB now goes to Succ.
1374 BB->replaceUsesWithIf(Succ, [BBPreds, CommonPred](Use &U) ->bool {
1375if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser()))
1376return UseInst->getParent() != CommonPred &&
1377 BBPreds.contains(UseInst->getParent());
1378returnfalse;
1379 });
1380 }
1381
1382if (DTU)
1383 DTU->applyUpdates(Updates);
1384
1385if (BBKillable)
1386DeleteDeadBlock(BB, DTU);
1387
1388returntrue;
1389}
1390
1391staticbool
1392EliminateDuplicatePHINodesNaiveImpl(BasicBlock *BB,
1393SmallPtrSetImpl<PHINode *> &ToRemove) {
1394// This implementation doesn't currently consider undef operands
1395// specially. Theoretically, two phis which are identical except for
1396// one having an undef where the other doesn't could be collapsed.
1397
1398bool Changed =false;
1399
1400// Examine each PHI.
1401// Note that increment of I must *NOT* be in the iteration_expression, since
1402// we don't want to immediately advance when we restart from the beginning.
1403for (autoI = BB->begin();PHINode *PN = dyn_cast<PHINode>(I);) {
1404 ++I;
1405// Is there an identical PHI node in this basic block?
1406// Note that we only look in the upper square's triangle,
1407// we already checked that the lower triangle PHI's aren't identical.
1408for (auto J =I;PHINode *DuplicatePN = dyn_cast<PHINode>(J); ++J) {
1409if (ToRemove.contains(DuplicatePN))
1410continue;
1411if (!DuplicatePN->isIdenticalToWhenDefined(PN))
1412continue;
1413// A duplicate. Replace this PHI with the base PHI.
1414 ++NumPHICSEs;
1415 DuplicatePN->replaceAllUsesWith(PN);
1416ToRemove.insert(DuplicatePN);
1417 Changed =true;
1418
1419// The RAUW can change PHIs that we already visited.
1420I = BB->begin();
1421break;// Start over from the beginning.
1422 }
1423 }
1424return Changed;
1425}
1426
1427staticbool
1428EliminateDuplicatePHINodesSetBasedImpl(BasicBlock *BB,
1429SmallPtrSetImpl<PHINode *> &ToRemove) {
1430// This implementation doesn't currently consider undef operands
1431// specially. Theoretically, two phis which are identical except for
1432// one having an undef where the other doesn't could be collapsed.
1433
1434structPHIDenseMapInfo {
1435staticPHINode *getEmptyKey() {
1436returnDenseMapInfo<PHINode *>::getEmptyKey();
1437 }
1438
1439staticPHINode *getTombstoneKey() {
1440returnDenseMapInfo<PHINode *>::getTombstoneKey();
1441 }
1442
1443staticboolisSentinel(PHINode *PN) {
1444return PN == getEmptyKey() || PN == getTombstoneKey();
1445 }
1446
1447// WARNING: this logic must be kept in sync with
1448// Instruction::isIdenticalToWhenDefined()!
1449staticunsignedgetHashValueImpl(PHINode *PN) {
1450// Compute a hash value on the operands. Instcombine will likely have
1451// sorted them, which helps expose duplicates, but we have to check all
1452// the operands to be safe in case instcombine hasn't run.
1453returnstatic_cast<unsigned>(hash_combine(
1454hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
1455hash_combine_range(PN->block_begin(), PN->block_end())));
1456 }
1457
1458staticunsigned getHashValue(PHINode *PN) {
1459#ifndef NDEBUG
1460// If -phicse-debug-hash was specified, return a constant -- this
1461// will force all hashing to collide, so we'll exhaustively search
1462// the table for a match, and the assertion in isEqual will fire if
1463// there's a bug causing equal keys to hash differently.
1464if (PHICSEDebugHash)
1465return 0;
1466#endif
1467returngetHashValueImpl(PN);
1468 }
1469
1470staticboolisEqualImpl(PHINode *LHS,PHINode *RHS) {
1471if (isSentinel(LHS) ||isSentinel(RHS))
1472returnLHS ==RHS;
1473returnLHS->isIdenticalTo(RHS);
1474 }
1475
1476staticboolisEqual(PHINode *LHS,PHINode *RHS) {
1477// These comparisons are nontrivial, so assert that equality implies
1478// hash equality (DenseMap demands this as an invariant).
1479bool Result =isEqualImpl(LHS,RHS);
1480assert(!Result || (isSentinel(LHS) &&LHS ==RHS) ||
1481getHashValueImpl(LHS) ==getHashValueImpl(RHS));
1482return Result;
1483 }
1484 };
1485
1486// Set of unique PHINodes.
1487DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
1488 PHISet.reserve(4 *PHICSENumPHISmallSize);
1489
1490// Examine each PHI.
1491bool Changed =false;
1492for (autoI = BB->begin();PHINode *PN = dyn_cast<PHINode>(I++);) {
1493if (ToRemove.contains(PN))
1494continue;
1495auto Inserted = PHISet.insert(PN);
1496if (!Inserted.second) {
1497// A duplicate. Replace this PHI with its duplicate.
1498 ++NumPHICSEs;
1499 PN->replaceAllUsesWith(*Inserted.first);
1500ToRemove.insert(PN);
1501 Changed =true;
1502
1503// The RAUW can change PHIs that we already visited. Start over from the
1504// beginning.
1505 PHISet.clear();
1506I = BB->begin();
1507 }
1508 }
1509
1510return Changed;
1511}
1512
1513boolllvm::EliminateDuplicatePHINodes(BasicBlock *BB,
1514SmallPtrSetImpl<PHINode *> &ToRemove) {
1515if (
1516#ifndefNDEBUG
1517 !PHICSEDebugHash &&
1518#endif
1519hasNItemsOrLess(BB->phis(),PHICSENumPHISmallSize))
1520returnEliminateDuplicatePHINodesNaiveImpl(BB,ToRemove);
1521returnEliminateDuplicatePHINodesSetBasedImpl(BB,ToRemove);
1522}
1523
1524boolllvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
1525SmallPtrSet<PHINode *, 8>ToRemove;
1526bool Changed =EliminateDuplicatePHINodes(BB,ToRemove);
1527for (PHINode *PN :ToRemove)
1528 PN->eraseFromParent();
1529return Changed;
1530}
1531
1532Alignllvm::tryEnforceAlignment(Value *V,Align PrefAlign,
1533constDataLayout &DL) {
1534 V = V->stripPointerCasts();
1535
1536if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1537// TODO: Ideally, this function would not be called if PrefAlign is smaller
1538// than the current alignment, as the known bits calculation should have
1539// already taken it into account. However, this is not always the case,
1540// as computeKnownBits() has a depth limit, while stripPointerCasts()
1541// doesn't.
1542Align CurrentAlign = AI->getAlign();
1543if (PrefAlign <= CurrentAlign)
1544return CurrentAlign;
1545
1546// If the preferred alignment is greater than the natural stack alignment
1547// then don't round up. This avoids dynamic stack realignment.
1548MaybeAlign StackAlign =DL.getStackAlignment();
1549if (StackAlign && PrefAlign > *StackAlign)
1550return CurrentAlign;
1551 AI->setAlignment(PrefAlign);
1552return PrefAlign;
1553 }
1554
1555if (auto *GO = dyn_cast<GlobalObject>(V)) {
1556// TODO: as above, this shouldn't be necessary.
1557Align CurrentAlign = GO->getPointerAlignment(DL);
1558if (PrefAlign <= CurrentAlign)
1559return CurrentAlign;
1560
1561// If there is a large requested alignment and we can, bump up the alignment
1562// of the global. If the memory we set aside for the global may not be the
1563// memory used by the final program then it is impossible for us to reliably
1564// enforce the preferred alignment.
1565if (!GO->canIncreaseAlignment())
1566return CurrentAlign;
1567
1568if (GO->isThreadLocal()) {
1569unsigned MaxTLSAlign = GO->getParent()->getMaxTLSAlignment() / CHAR_BIT;
1570if (MaxTLSAlign && PrefAlign >Align(MaxTLSAlign))
1571 PrefAlign =Align(MaxTLSAlign);
1572 }
1573
1574 GO->setAlignment(PrefAlign);
1575return PrefAlign;
1576 }
1577
1578returnAlign(1);
1579}
1580
1581Alignllvm::getOrEnforceKnownAlignment(Value *V,MaybeAlign PrefAlign,
1582constDataLayout &DL,
1583constInstruction *CxtI,
1584AssumptionCache *AC,
1585constDominatorTree *DT) {
1586assert(V->getType()->isPointerTy() &&
1587"getOrEnforceKnownAlignment expects a pointer!");
1588
1589KnownBits Known =computeKnownBits(V,DL, 0, AC, CxtI, DT);
1590unsigned TrailZ = Known.countMinTrailingZeros();
1591
1592// Avoid trouble with ridiculously large TrailZ values, such as
1593// those computed from a null pointer.
1594// LLVM doesn't support alignments larger than (1 << MaxAlignmentExponent).
1595 TrailZ = std::min(TrailZ, +Value::MaxAlignmentExponent);
1596
1597Align Alignment =Align(1ull << std::min(Known.getBitWidth() - 1, TrailZ));
1598
1599if (PrefAlign && *PrefAlign > Alignment)
1600 Alignment = std::max(Alignment,tryEnforceAlignment(V, *PrefAlign,DL));
1601
1602// We don't need to make any adjustment.
1603return Alignment;
1604}
1605
1606///===---------------------------------------------------------------------===//
1607/// Dbg Intrinsic utilities
1608///
1609
1610/// See if there is a dbg.value intrinsic for DIVar for the PHI node.
1611staticboolPhiHasDebugValue(DILocalVariable *DIVar,
1612DIExpression *DIExpr,
1613PHINode *APN) {
1614// Since we can't guarantee that the original dbg.declare intrinsic
1615// is removed by LowerDbgDeclare(), we need to make sure that we are
1616// not inserting the same dbg.value intrinsic over and over.
1617SmallVector<DbgValueInst *, 1> DbgValues;
1618SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
1619findDbgValues(DbgValues, APN, &DbgVariableRecords);
1620for (auto *DVI : DbgValues) {
1621assert(is_contained(DVI->getValues(), APN));
1622if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
1623returntrue;
1624 }
1625for (auto *DVR : DbgVariableRecords) {
1626assert(is_contained(DVR->location_ops(), APN));
1627if ((DVR->getVariable() == DIVar) && (DVR->getExpression() == DIExpr))
1628returntrue;
1629 }
1630returnfalse;
1631}
1632
1633/// Check if the alloc size of \p ValTy is large enough to cover the variable
1634/// (or fragment of the variable) described by \p DII.
1635///
1636/// This is primarily intended as a helper for the different
1637/// ConvertDebugDeclareToDebugValue functions. The dbg.declare that is converted
1638/// describes an alloca'd variable, so we need to use the alloc size of the
1639/// value when doing the comparison. E.g. an i1 value will be identified as
1640/// covering an n-bit fragment, if the store size of i1 is at least n bits.
1641staticboolvalueCoversEntireFragment(Type *ValTy,DbgVariableIntrinsic *DII) {
1642constDataLayout &DL = DII->getDataLayout();
1643TypeSize ValueSize =DL.getTypeAllocSizeInBits(ValTy);
1644if (std::optional<uint64_t> FragmentSize =
1645 DII->getExpression()->getActiveBits(DII->getVariable()))
1646return TypeSize::isKnownGE(ValueSize,TypeSize::getFixed(*FragmentSize));
1647
1648// We can't always calculate the size of the DI variable (e.g. if it is a
1649// VLA). Try to use the size of the alloca that the dbg intrinsic describes
1650// instead.
1651if (DII->isAddressOfVariable()) {
1652// DII should have exactly 1 location when it is an address.
1653assert(DII->getNumVariableLocationOps() == 1 &&
1654"address of variable must have exactly 1 location operand.");
1655if (auto *AI =
1656 dyn_cast_or_null<AllocaInst>(DII->getVariableLocationOp(0))) {
1657if (std::optional<TypeSize> FragmentSize =
1658 AI->getAllocationSizeInBits(DL)) {
1659return TypeSize::isKnownGE(ValueSize, *FragmentSize);
1660 }
1661 }
1662 }
1663// Could not determine size of variable. Conservatively return false.
1664returnfalse;
1665}
1666// RemoveDIs: duplicate implementation of the above, using DbgVariableRecords,
1667// the replacement for dbg.values.
1668staticboolvalueCoversEntireFragment(Type *ValTy,DbgVariableRecord *DVR) {
1669constDataLayout &DL = DVR->getModule()->getDataLayout();
1670TypeSize ValueSize =DL.getTypeAllocSizeInBits(ValTy);
1671if (std::optional<uint64_t> FragmentSize =
1672 DVR->getExpression()->getActiveBits(DVR->getVariable()))
1673return TypeSize::isKnownGE(ValueSize,TypeSize::getFixed(*FragmentSize));
1674
1675// We can't always calculate the size of the DI variable (e.g. if it is a
1676// VLA). Try to use the size of the alloca that the dbg intrinsic describes
1677// instead.
1678if (DVR->isAddressOfVariable()) {
1679// DVR should have exactly 1 location when it is an address.
1680assert(DVR->getNumVariableLocationOps() == 1 &&
1681"address of variable must have exactly 1 location operand.");
1682if (auto *AI =
1683 dyn_cast_or_null<AllocaInst>(DVR->getVariableLocationOp(0))) {
1684if (std::optional<TypeSize> FragmentSize = AI->getAllocationSizeInBits(DL)) {
1685return TypeSize::isKnownGE(ValueSize, *FragmentSize);
1686 }
1687 }
1688 }
1689// Could not determine size of variable. Conservatively return false.
1690returnfalse;
1691}
1692
1693staticvoidinsertDbgValueOrDbgVariableRecord(DIBuilder &Builder,Value *DV,
1694DILocalVariable *DIVar,
1695DIExpression *DIExpr,
1696constDebugLoc &NewLoc,
1697BasicBlock::iterator Instr) {
1698if (!UseNewDbgInfoFormat) {
1699auto DbgVal = Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc,
1700 (Instruction *)nullptr);
1701 cast<Instruction *>(DbgVal)->insertBefore(Instr);
1702 }else {
1703// RemoveDIs: if we're using the new debug-info format, allocate a
1704// DbgVariableRecord directly instead of a dbg.value intrinsic.
1705ValueAsMetadata *DVAM =ValueAsMetadata::get(DV);
1706DbgVariableRecord *DV =
1707newDbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());
1708 Instr->getParent()->insertDbgRecordBefore(DV, Instr);
1709 }
1710}
1711
1712staticvoidinsertDbgValueOrDbgVariableRecordAfter(
1713DIBuilder &Builder,Value *DV,DILocalVariable *DIVar,DIExpression *DIExpr,
1714constDebugLoc &NewLoc,BasicBlock::iterator Instr) {
1715if (!UseNewDbgInfoFormat) {
1716auto DbgVal = Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc,
1717 (Instruction *)nullptr);
1718 cast<Instruction *>(DbgVal)->insertAfter(Instr);
1719 }else {
1720// RemoveDIs: if we're using the new debug-info format, allocate a
1721// DbgVariableRecord directly instead of a dbg.value intrinsic.
1722ValueAsMetadata *DVAM =ValueAsMetadata::get(DV);
1723DbgVariableRecord *DV =
1724newDbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());
1725 Instr->getParent()->insertDbgRecordAfter(DV, &*Instr);
1726 }
1727}
1728
1729/// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
1730/// that has an associated llvm.dbg.declare intrinsic.
1731voidllvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1732StoreInst *SI,DIBuilder &Builder) {
1733assert(DII->isAddressOfVariable() || isa<DbgAssignIntrinsic>(DII));
1734auto *DIVar = DII->getVariable();
1735assert(DIVar &&"Missing variable");
1736auto *DIExpr = DII->getExpression();
1737Value *DV = SI->getValueOperand();
1738
1739DebugLoc NewLoc =getDebugValueLoc(DII);
1740
1741// If the alloca describes the variable itself, i.e. the expression in the
1742// dbg.declare doesn't start with a dereference, we can perform the
1743// conversion if the value covers the entire fragment of DII.
1744// If the alloca describes the *address* of DIVar, i.e. DIExpr is
1745// *just* a DW_OP_deref, we use DV as is for the dbg.value.
1746// We conservatively ignore other dereferences, because the following two are
1747// not equivalent:
1748// dbg.declare(alloca, ..., !Expr(deref, plus_uconstant, 2))
1749// dbg.value(DV, ..., !Expr(deref, plus_uconstant, 2))
1750// The former is adding 2 to the address of the variable, whereas the latter
1751// is adding 2 to the value of the variable. As such, we insist on just a
1752// deref expression.
1753bool CanConvert =
1754 DIExpr->isDeref() || (!DIExpr->startsWithDeref() &&
1755valueCoversEntireFragment(DV->getType(), DII));
1756if (CanConvert) {
1757insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1758 SI->getIterator());
1759return;
1760 }
1761
1762// FIXME: If storing to a part of the variable described by the dbg.declare,
1763// then we want to insert a dbg.value for the corresponding fragment.
1764LLVM_DEBUG(dbgs() <<"Failed to convert dbg.declare to dbg.value: " << *DII
1765 <<'\n');
1766// For now, when there is a store to parts of the variable (but we do not
1767// know which part) we insert an dbg.value intrinsic to indicate that we
1768// know nothing about the variable's content.
1769 DV =PoisonValue::get(DV->getType());
1770insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1771 SI->getIterator());
1772}
1773
1774staticDIExpression *dropInitialDeref(constDIExpression *DIExpr) {
1775int NumEltDropped = DIExpr->getElements()[0] ==dwarf::DW_OP_LLVM_arg ? 3 : 1;
1776return DIExpression::get(DIExpr->getContext(),
1777 DIExpr->getElements().drop_front(NumEltDropped));
1778}
1779
1780voidllvm::InsertDebugValueAtStoreLoc(DbgVariableIntrinsic *DII,StoreInst *SI,
1781DIBuilder &Builder) {
1782auto *DIVar = DII->getVariable();
1783assert(DIVar &&"Missing variable");
1784auto *DIExpr = DII->getExpression();
1785 DIExpr =dropInitialDeref(DIExpr);
1786Value *DV = SI->getValueOperand();
1787
1788DebugLoc NewLoc =getDebugValueLoc(DII);
1789
1790insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1791 SI->getIterator());
1792}
1793
1794/// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
1795/// that has an associated llvm.dbg.declare intrinsic.
1796voidllvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1797LoadInst *LI,DIBuilder &Builder) {
1798auto *DIVar = DII->getVariable();
1799auto *DIExpr = DII->getExpression();
1800assert(DIVar &&"Missing variable");
1801
1802if (!valueCoversEntireFragment(LI->getType(), DII)) {
1803// FIXME: If only referring to a part of the variable described by the
1804// dbg.declare, then we want to insert a dbg.value for the corresponding
1805// fragment.
1806LLVM_DEBUG(dbgs() <<"Failed to convert dbg.declare to dbg.value: "
1807 << *DII <<'\n');
1808return;
1809 }
1810
1811DebugLoc NewLoc =getDebugValueLoc(DII);
1812
1813// We are now tracking the loaded value instead of the address. In the
1814// future if multi-location support is added to the IR, it might be
1815// preferable to keep tracking both the loaded value and the original
1816// address in case the alloca can not be elided.
1817insertDbgValueOrDbgVariableRecordAfter(Builder, LI, DIVar, DIExpr, NewLoc,
1818 LI->getIterator());
1819}
1820
1821voidllvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
1822StoreInst *SI,DIBuilder &Builder) {
1823assert(DVR->isAddressOfVariable() || DVR->isDbgAssign());
1824auto *DIVar = DVR->getVariable();
1825assert(DIVar &&"Missing variable");
1826auto *DIExpr = DVR->getExpression();
1827Value *DV = SI->getValueOperand();
1828
1829DebugLoc NewLoc =getDebugValueLoc(DVR);
1830
1831// If the alloca describes the variable itself, i.e. the expression in the
1832// dbg.declare doesn't start with a dereference, we can perform the
1833// conversion if the value covers the entire fragment of DII.
1834// If the alloca describes the *address* of DIVar, i.e. DIExpr is
1835// *just* a DW_OP_deref, we use DV as is for the dbg.value.
1836// We conservatively ignore other dereferences, because the following two are
1837// not equivalent:
1838// dbg.declare(alloca, ..., !Expr(deref, plus_uconstant, 2))
1839// dbg.value(DV, ..., !Expr(deref, plus_uconstant, 2))
1840// The former is adding 2 to the address of the variable, whereas the latter
1841// is adding 2 to the value of the variable. As such, we insist on just a
1842// deref expression.
1843bool CanConvert =
1844 DIExpr->isDeref() || (!DIExpr->startsWithDeref() &&
1845valueCoversEntireFragment(DV->getType(), DVR));
1846if (CanConvert) {
1847insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1848 SI->getIterator());
1849return;
1850 }
1851
1852// FIXME: If storing to a part of the variable described by the dbg.declare,
1853// then we want to insert a dbg.value for the corresponding fragment.
1854LLVM_DEBUG(dbgs() <<"Failed to convert dbg.declare to dbg.value: " << *DVR
1855 <<'\n');
1856assert(UseNewDbgInfoFormat);
1857
1858// For now, when there is a store to parts of the variable (but we do not
1859// know which part) we insert an dbg.value intrinsic to indicate that we
1860// know nothing about the variable's content.
1861 DV =PoisonValue::get(DV->getType());
1862ValueAsMetadata *DVAM =ValueAsMetadata::get(DV);
1863DbgVariableRecord *NewDVR =
1864newDbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());
1865 SI->getParent()->insertDbgRecordBefore(NewDVR, SI->getIterator());
1866}
1867
1868voidllvm::InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR,StoreInst *SI,
1869DIBuilder &Builder) {
1870auto *DIVar = DVR->getVariable();
1871assert(DIVar &&"Missing variable");
1872auto *DIExpr = DVR->getExpression();
1873 DIExpr =dropInitialDeref(DIExpr);
1874Value *DV = SI->getValueOperand();
1875
1876DebugLoc NewLoc =getDebugValueLoc(DVR);
1877
1878insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1879 SI->getIterator());
1880}
1881
1882/// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
1883/// llvm.dbg.declare intrinsic.
1884voidllvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1885PHINode *APN,DIBuilder &Builder) {
1886auto *DIVar = DII->getVariable();
1887auto *DIExpr = DII->getExpression();
1888assert(DIVar &&"Missing variable");
1889
1890if (PhiHasDebugValue(DIVar, DIExpr, APN))
1891return;
1892
1893if (!valueCoversEntireFragment(APN->getType(), DII)) {
1894// FIXME: If only referring to a part of the variable described by the
1895// dbg.declare, then we want to insert a dbg.value for the corresponding
1896// fragment.
1897LLVM_DEBUG(dbgs() <<"Failed to convert dbg.declare to dbg.value: "
1898 << *DII <<'\n');
1899return;
1900 }
1901
1902BasicBlock *BB = APN->getParent();
1903auto InsertionPt = BB->getFirstInsertionPt();
1904
1905DebugLoc NewLoc =getDebugValueLoc(DII);
1906
1907// The block may be a catchswitch block, which does not have a valid
1908// insertion point.
1909// FIXME: Insert dbg.value markers in the successors when appropriate.
1910if (InsertionPt != BB->end()) {
1911insertDbgValueOrDbgVariableRecord(Builder, APN, DIVar, DIExpr, NewLoc,
1912 InsertionPt);
1913 }
1914}
1915
1916voidllvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,LoadInst *LI,
1917DIBuilder &Builder) {
1918auto *DIVar = DVR->getVariable();
1919auto *DIExpr = DVR->getExpression();
1920assert(DIVar &&"Missing variable");
1921
1922if (!valueCoversEntireFragment(LI->getType(), DVR)) {
1923// FIXME: If only referring to a part of the variable described by the
1924// dbg.declare, then we want to insert a DbgVariableRecord for the
1925// corresponding fragment.
1926LLVM_DEBUG(dbgs() <<"Failed to convert dbg.declare to DbgVariableRecord: "
1927 << *DVR <<'\n');
1928return;
1929 }
1930
1931DebugLoc NewLoc =getDebugValueLoc(DVR);
1932
1933// We are now tracking the loaded value instead of the address. In the
1934// future if multi-location support is added to the IR, it might be
1935// preferable to keep tracking both the loaded value and the original
1936// address in case the alloca can not be elided.
1937assert(UseNewDbgInfoFormat);
1938
1939// Create a DbgVariableRecord directly and insert.
1940ValueAsMetadata *LIVAM =ValueAsMetadata::get(LI);
1941DbgVariableRecord *DV =
1942newDbgVariableRecord(LIVAM, DIVar, DIExpr, NewLoc.get());
1943 LI->getParent()->insertDbgRecordAfter(DV, LI);
1944}
1945
1946/// Determine whether this alloca is either a VLA or an array.
1947staticboolisArray(AllocaInst *AI) {
1948return AI->isArrayAllocation() ||
1949 (AI->getAllocatedType() && AI->getAllocatedType()->isArrayTy());
1950}
1951
1952/// Determine whether this alloca is a structure.
1953staticboolisStructure(AllocaInst *AI) {
1954return AI->getAllocatedType() && AI->getAllocatedType()->isStructTy();
1955}
1956voidllvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,PHINode *APN,
1957DIBuilder &Builder) {
1958auto *DIVar = DVR->getVariable();
1959auto *DIExpr = DVR->getExpression();
1960assert(DIVar &&"Missing variable");
1961
1962if (PhiHasDebugValue(DIVar, DIExpr, APN))
1963return;
1964
1965if (!valueCoversEntireFragment(APN->getType(), DVR)) {
1966// FIXME: If only referring to a part of the variable described by the
1967// dbg.declare, then we want to insert a DbgVariableRecord for the
1968// corresponding fragment.
1969LLVM_DEBUG(dbgs() <<"Failed to convert dbg.declare to DbgVariableRecord: "
1970 << *DVR <<'\n');
1971return;
1972 }
1973
1974BasicBlock *BB = APN->getParent();
1975auto InsertionPt = BB->getFirstInsertionPt();
1976
1977DebugLoc NewLoc =getDebugValueLoc(DVR);
1978
1979// The block may be a catchswitch block, which does not have a valid
1980// insertion point.
1981// FIXME: Insert DbgVariableRecord markers in the successors when appropriate.
1982if (InsertionPt != BB->end()) {
1983insertDbgValueOrDbgVariableRecord(Builder, APN, DIVar, DIExpr, NewLoc,
1984 InsertionPt);
1985 }
1986}
1987
1988/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1989/// of llvm.dbg.value intrinsics.
1990boolllvm::LowerDbgDeclare(Function &F) {
1991bool Changed =false;
1992DIBuilder DIB(*F.getParent(),/*AllowUnresolved*/false);
1993SmallVector<DbgDeclareInst *, 4> Dbgs;
1994SmallVector<DbgVariableRecord *> DVRs;
1995for (auto &FI :F) {
1996for (Instruction &BI : FI) {
1997if (auto *DDI = dyn_cast<DbgDeclareInst>(&BI))
1998 Dbgs.push_back(DDI);
1999for (DbgVariableRecord &DVR :filterDbgVars(BI.getDbgRecordRange())) {
2000if (DVR.getType() == DbgVariableRecord::LocationType::Declare)
2001 DVRs.push_back(&DVR);
2002 }
2003 }
2004 }
2005
2006if (Dbgs.empty() && DVRs.empty())
2007return Changed;
2008
2009auto LowerOne = [&](auto *DDI) {
2010AllocaInst *AI =
2011 dyn_cast_or_null<AllocaInst>(DDI->getVariableLocationOp(0));
2012// If this is an alloca for a scalar variable, insert a dbg.value
2013// at each load and store to the alloca and erase the dbg.declare.
2014// The dbg.values allow tracking a variable even if it is not
2015// stored on the stack, while the dbg.declare can only describe
2016// the stack slot (and at a lexical-scope granularity). Later
2017// passes will attempt to elide the stack slot.
2018if (!AI ||isArray(AI) ||isStructure(AI))
2019return;
2020
2021// A volatile load/store means that the alloca can't be elided anyway.
2022if (llvm::any_of(AI->users(), [](User *U) ->bool {
2023 if (LoadInst *LI = dyn_cast<LoadInst>(U))
2024 return LI->isVolatile();
2025 if (StoreInst *SI = dyn_cast<StoreInst>(U))
2026 return SI->isVolatile();
2027 return false;
2028 }))
2029return;
2030
2031SmallVector<const Value *, 8> WorkList;
2032 WorkList.push_back(AI);
2033while (!WorkList.empty()) {
2034constValue *V = WorkList.pop_back_val();
2035for (constauto &AIUse : V->uses()) {
2036User *U = AIUse.getUser();
2037if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
2038if (AIUse.getOperandNo() == 1)
2039ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
2040 }elseif (LoadInst *LI = dyn_cast<LoadInst>(U)) {
2041ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
2042 }elseif (CallInst *CI = dyn_cast<CallInst>(U)) {
2043// This is a call by-value or some other instruction that takes a
2044// pointer to the variable. Insert a *value* intrinsic that describes
2045// the variable by dereferencing the alloca.
2046if (!CI->isLifetimeStartOrEnd()) {
2047DebugLoc NewLoc =getDebugValueLoc(DDI);
2048auto *DerefExpr =
2049DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
2050insertDbgValueOrDbgVariableRecord(DIB, AI, DDI->getVariable(),
2051 DerefExpr, NewLoc,
2052 CI->getIterator());
2053 }
2054 }elseif (BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
2055if (BI->getType()->isPointerTy())
2056 WorkList.push_back(BI);
2057 }
2058 }
2059 }
2060 DDI->eraseFromParent();
2061 Changed =true;
2062 };
2063
2064for_each(Dbgs, LowerOne);
2065for_each(DVRs, LowerOne);
2066
2067if (Changed)
2068for (BasicBlock &BB :F)
2069RemoveRedundantDbgInstrs(&BB);
2070
2071return Changed;
2072}
2073
2074// RemoveDIs: re-implementation of insertDebugValuesForPHIs, but which pulls the
2075// debug-info out of the block's DbgVariableRecords rather than dbg.value
2076// intrinsics.
2077staticvoid
2078insertDbgVariableRecordsForPHIs(BasicBlock *BB,
2079SmallVectorImpl<PHINode *> &InsertedPHIs) {
2080assert(BB &&"No BasicBlock to clone DbgVariableRecord(s) from.");
2081if (InsertedPHIs.size() == 0)
2082return;
2083
2084// Map existing PHI nodes to their DbgVariableRecords.
2085DenseMap<Value *, DbgVariableRecord *> DbgValueMap;
2086for (auto &I : *BB) {
2087for (DbgVariableRecord &DVR :filterDbgVars(I.getDbgRecordRange())) {
2088for (Value *V : DVR.location_ops())
2089if (auto *Loc = dyn_cast_or_null<PHINode>(V))
2090 DbgValueMap.insert({Loc, &DVR});
2091 }
2092 }
2093if (DbgValueMap.size() == 0)
2094return;
2095
2096// Map a pair of the destination BB and old DbgVariableRecord to the new
2097// DbgVariableRecord, so that if a DbgVariableRecord is being rewritten to use
2098// more than one of the inserted PHIs in the same destination BB, we can
2099// update the same DbgVariableRecord with all the new PHIs instead of creating
2100// one copy for each.
2101MapVector<std::pair<BasicBlock *, DbgVariableRecord *>,DbgVariableRecord *>
2102 NewDbgValueMap;
2103// Then iterate through the new PHIs and look to see if they use one of the
2104// previously mapped PHIs. If so, create a new DbgVariableRecord that will
2105// propagate the info through the new PHI. If we use more than one new PHI in
2106// a single destination BB with the same old dbg.value, merge the updates so
2107// that we get a single new DbgVariableRecord with all the new PHIs.
2108for (autoPHI : InsertedPHIs) {
2109BasicBlock *Parent =PHI->getParent();
2110// Avoid inserting a debug-info record into an EH block.
2111if (Parent->getFirstNonPHIIt()->isEHPad())
2112continue;
2113for (auto VI :PHI->operand_values()) {
2114auto V = DbgValueMap.find(VI);
2115if (V != DbgValueMap.end()) {
2116DbgVariableRecord *DbgII = cast<DbgVariableRecord>(V->second);
2117auto NewDI = NewDbgValueMap.find({Parent, DbgII});
2118if (NewDI == NewDbgValueMap.end()) {
2119DbgVariableRecord *NewDbgII = DbgII->clone();
2120 NewDI = NewDbgValueMap.insert({{Parent, DbgII}, NewDbgII}).first;
2121 }
2122DbgVariableRecord *NewDbgII = NewDI->second;
2123// If PHI contains VI as an operand more than once, we may
2124// replaced it in NewDbgII; confirm that it is present.
2125if (is_contained(NewDbgII->location_ops(), VI))
2126 NewDbgII->replaceVariableLocationOp(VI,PHI);
2127 }
2128 }
2129 }
2130// Insert the new DbgVariableRecords into their destination blocks.
2131for (auto DI : NewDbgValueMap) {
2132BasicBlock *Parent = DI.first.first;
2133DbgVariableRecord *NewDbgII = DI.second;
2134auto InsertionPt = Parent->getFirstInsertionPt();
2135assert(InsertionPt != Parent->end() &&"Ill-formed basic block");
2136
2137 Parent->insertDbgRecordBefore(NewDbgII, InsertionPt);
2138 }
2139}
2140
2141/// Propagate dbg.value intrinsics through the newly inserted PHIs.
2142voidllvm::insertDebugValuesForPHIs(BasicBlock *BB,
2143SmallVectorImpl<PHINode *> &InsertedPHIs) {
2144assert(BB &&"No BasicBlock to clone dbg.value(s) from.");
2145if (InsertedPHIs.size() == 0)
2146return;
2147
2148insertDbgVariableRecordsForPHIs(BB, InsertedPHIs);
2149
2150// Map existing PHI nodes to their dbg.values.
2151ValueToValueMapTy DbgValueMap;
2152for (auto &I : *BB) {
2153if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
2154for (Value *V : DbgII->location_ops())
2155if (auto *Loc = dyn_cast_or_null<PHINode>(V))
2156 DbgValueMap.insert({Loc, DbgII});
2157 }
2158 }
2159if (DbgValueMap.size() == 0)
2160return;
2161
2162// Map a pair of the destination BB and old dbg.value to the new dbg.value,
2163// so that if a dbg.value is being rewritten to use more than one of the
2164// inserted PHIs in the same destination BB, we can update the same dbg.value
2165// with all the new PHIs instead of creating one copy for each.
2166MapVector<std::pair<BasicBlock *, DbgVariableIntrinsic *>,
2167DbgVariableIntrinsic *>
2168 NewDbgValueMap;
2169// Then iterate through the new PHIs and look to see if they use one of the
2170// previously mapped PHIs. If so, create a new dbg.value intrinsic that will
2171// propagate the info through the new PHI. If we use more than one new PHI in
2172// a single destination BB with the same old dbg.value, merge the updates so
2173// that we get a single new dbg.value with all the new PHIs.
2174for (auto *PHI : InsertedPHIs) {
2175BasicBlock *Parent =PHI->getParent();
2176// Avoid inserting an intrinsic into an EH block.
2177if (Parent->getFirstNonPHIIt()->isEHPad())
2178continue;
2179for (auto *VI :PHI->operand_values()) {
2180auto V = DbgValueMap.find(VI);
2181if (V != DbgValueMap.end()) {
2182auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
2183auto [NewDI, Inserted] = NewDbgValueMap.try_emplace({Parent, DbgII});
2184if (Inserted)
2185 NewDI->second = cast<DbgVariableIntrinsic>(DbgII->clone());
2186DbgVariableIntrinsic *NewDbgII = NewDI->second;
2187// If PHI contains VI as an operand more than once, we may
2188// replaced it in NewDbgII; confirm that it is present.
2189if (is_contained(NewDbgII->location_ops(), VI))
2190 NewDbgII->replaceVariableLocationOp(VI,PHI);
2191 }
2192 }
2193 }
2194// Insert thew new dbg.values into their destination blocks.
2195for (auto DI : NewDbgValueMap) {
2196BasicBlock *Parent = DI.first.first;
2197auto *NewDbgII = DI.second;
2198auto InsertionPt = Parent->getFirstInsertionPt();
2199assert(InsertionPt != Parent->end() &&"Ill-formed basic block");
2200 NewDbgII->insertBefore(InsertionPt);
2201 }
2202}
2203
2204boolllvm::replaceDbgDeclare(Value *Address,Value *NewAddress,
2205DIBuilder &Builder,uint8_t DIExprFlags,
2206intOffset) {
2207TinyPtrVector<DbgDeclareInst *> DbgDeclares =findDbgDeclares(Address);
2208TinyPtrVector<DbgVariableRecord *> DVRDeclares =findDVRDeclares(Address);
2209
2210auto ReplaceOne = [&](auto *DII) {
2211assert(DII->getVariable() &&"Missing variable");
2212auto *DIExpr = DII->getExpression();
2213 DIExpr =DIExpression::prepend(DIExpr, DIExprFlags,Offset);
2214 DII->setExpression(DIExpr);
2215 DII->replaceVariableLocationOp(Address, NewAddress);
2216 };
2217
2218for_each(DbgDeclares, ReplaceOne);
2219for_each(DVRDeclares, ReplaceOne);
2220
2221return !DbgDeclares.empty() || !DVRDeclares.empty();
2222}
2223
2224staticvoidupdateOneDbgValueForAlloca(constDebugLoc &Loc,
2225DILocalVariable *DIVar,
2226DIExpression *DIExpr,Value *NewAddress,
2227DbgValueInst *DVI,
2228DbgVariableRecord *DVR,
2229DIBuilder &Builder,intOffset) {
2230assert(DIVar &&"Missing variable");
2231
2232// This is an alloca-based dbg.value/DbgVariableRecord. The first thing it
2233// should do with the alloca pointer is dereference it. Otherwise we don't
2234// know how to handle it and give up.
2235if (!DIExpr || DIExpr->getNumElements() < 1 ||
2236 DIExpr->getElement(0) != dwarf::DW_OP_deref)
2237return;
2238
2239// Insert the offset before the first deref.
2240if (Offset)
2241 DIExpr =DIExpression::prepend(DIExpr, 0,Offset);
2242
2243if (DVI) {
2244 DVI->setExpression(DIExpr);
2245 DVI->replaceVariableLocationOp(0u, NewAddress);
2246 }else {
2247assert(DVR);
2248 DVR->setExpression(DIExpr);
2249 DVR->replaceVariableLocationOp(0u, NewAddress);
2250 }
2251}
2252
2253voidllvm::replaceDbgValueForAlloca(AllocaInst *AI,Value *NewAllocaAddress,
2254DIBuilder &Builder,intOffset) {
2255SmallVector<DbgValueInst *, 1> DbgUsers;
2256SmallVector<DbgVariableRecord *, 1> DPUsers;
2257findDbgValues(DbgUsers, AI, &DPUsers);
2258
2259// Attempt to replace dbg.values that use this alloca.
2260for (auto *DVI : DbgUsers)
2261updateOneDbgValueForAlloca(DVI->getDebugLoc(), DVI->getVariable(),
2262 DVI->getExpression(), NewAllocaAddress, DVI,
2263nullptr, Builder,Offset);
2264
2265// Replace any DbgVariableRecords that use this alloca.
2266for (DbgVariableRecord *DVR : DPUsers)
2267updateOneDbgValueForAlloca(DVR->getDebugLoc(), DVR->getVariable(),
2268 DVR->getExpression(), NewAllocaAddress,nullptr,
2269 DVR, Builder,Offset);
2270}
2271
2272/// Where possible to salvage debug information for \p I do so.
2273/// If not possible mark undef.
2274voidllvm::salvageDebugInfo(Instruction &I) {
2275SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
2276SmallVector<DbgVariableRecord *, 1> DPUsers;
2277findDbgUsers(DbgUsers, &I, &DPUsers);
2278salvageDebugInfoForDbgValues(I, DbgUsers, DPUsers);
2279}
2280
2281template <typename T>staticvoidsalvageDbgAssignAddress(T *Assign) {
2282Instruction *I = dyn_cast<Instruction>(Assign->getAddress());
2283// Only instructions can be salvaged at the moment.
2284if (!I)
2285return;
2286
2287assert(!Assign->getAddressExpression()->getFragmentInfo().has_value() &&
2288"address-expression shouldn't have fragment info");
2289
2290// The address component of a dbg.assign cannot be variadic.
2291uint64_t CurrentLocOps = 0;
2292SmallVector<Value *, 4> AdditionalValues;
2293SmallVector<uint64_t, 16> Ops;
2294Value *NewV =salvageDebugInfoImpl(*I, CurrentLocOps, Ops, AdditionalValues);
2295
2296// Check if the salvage failed.
2297if (!NewV)
2298return;
2299
2300DIExpression *SalvagedExpr =DIExpression::appendOpsToArg(
2301 Assign->getAddressExpression(), Ops, 0,/*StackValue=*/false);
2302assert(!SalvagedExpr->getFragmentInfo().has_value() &&
2303"address-expression shouldn't have fragment info");
2304
2305 SalvagedExpr = SalvagedExpr->foldConstantMath();
2306
2307// Salvage succeeds if no additional values are required.
2308if (AdditionalValues.empty()) {
2309 Assign->setAddress(NewV);
2310 Assign->setAddressExpression(SalvagedExpr);
2311 }else {
2312 Assign->setKillAddress();
2313 }
2314}
2315
2316voidllvm::salvageDebugInfoForDbgValues(
2317Instruction &I,ArrayRef<DbgVariableIntrinsic *> DbgUsers,
2318ArrayRef<DbgVariableRecord *> DPUsers) {
2319// These are arbitrary chosen limits on the maximum number of values and the
2320// maximum size of a debug expression we can salvage up to, used for
2321// performance reasons.
2322constunsigned MaxDebugArgs = 16;
2323constunsigned MaxExpressionSize = 128;
2324bool Salvaged =false;
2325
2326for (auto *DII : DbgUsers) {
2327if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DII)) {
2328if (DAI->getAddress() == &I) {
2329salvageDbgAssignAddress(DAI);
2330 Salvaged =true;
2331 }
2332if (DAI->getValue() != &I)
2333continue;
2334 }
2335
2336// Do not add DW_OP_stack_value for DbgDeclare, because they are implicitly
2337// pointing out the value as a DWARF memory location description.
2338bool StackValue = isa<DbgValueInst>(DII);
2339auto DIILocation = DII->location_ops();
2340assert(
2341is_contained(DIILocation, &I) &&
2342"DbgVariableIntrinsic must use salvaged instruction as its location");
2343SmallVector<Value *, 4> AdditionalValues;
2344// `I` may appear more than once in DII's location ops, and each use of `I`
2345// must be updated in the DIExpression and potentially have additional
2346// values added; thus we call salvageDebugInfoImpl for each `I` instance in
2347// DIILocation.
2348Value *Op0 =nullptr;
2349DIExpression *SalvagedExpr = DII->getExpression();
2350auto LocItr =find(DIILocation, &I);
2351while (SalvagedExpr && LocItr != DIILocation.end()) {
2352SmallVector<uint64_t, 16> Ops;
2353unsigned LocNo = std::distance(DIILocation.begin(), LocItr);
2354uint64_t CurrentLocOps = SalvagedExpr->getNumLocationOperands();
2355 Op0 =salvageDebugInfoImpl(I, CurrentLocOps, Ops, AdditionalValues);
2356if (!Op0)
2357break;
2358 SalvagedExpr =
2359DIExpression::appendOpsToArg(SalvagedExpr, Ops, LocNo, StackValue);
2360 LocItr = std::find(++LocItr, DIILocation.end(), &I);
2361 }
2362// salvageDebugInfoImpl should fail on examining the first element of
2363// DbgUsers, or none of them.
2364if (!Op0)
2365break;
2366
2367 SalvagedExpr = SalvagedExpr->foldConstantMath();
2368 DII->replaceVariableLocationOp(&I, Op0);
2369bool IsValidSalvageExpr = SalvagedExpr->getNumElements() <= MaxExpressionSize;
2370if (AdditionalValues.empty() && IsValidSalvageExpr) {
2371 DII->setExpression(SalvagedExpr);
2372 }elseif (isa<DbgValueInst>(DII) && IsValidSalvageExpr &&
2373 DII->getNumVariableLocationOps() + AdditionalValues.size() <=
2374 MaxDebugArgs) {
2375 DII->addVariableLocationOps(AdditionalValues, SalvagedExpr);
2376 }else {
2377// Do not salvage using DIArgList for dbg.declare, as it is not currently
2378// supported in those instructions. Also do not salvage if the resulting
2379// DIArgList would contain an unreasonably large number of values.
2380 DII->setKillLocation();
2381 }
2382LLVM_DEBUG(dbgs() <<"SALVAGE: " << *DII <<'\n');
2383 Salvaged =true;
2384 }
2385// Duplicate of above block for DbgVariableRecords.
2386for (auto *DVR : DPUsers) {
2387if (DVR->isDbgAssign()) {
2388if (DVR->getAddress() == &I) {
2389salvageDbgAssignAddress(DVR);
2390 Salvaged =true;
2391 }
2392if (DVR->getValue() != &I)
2393continue;
2394 }
2395
2396// Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
2397// are implicitly pointing out the value as a DWARF memory location
2398// description.
2399bool StackValue =
2400 DVR->getType() != DbgVariableRecord::LocationType::Declare;
2401auto DVRLocation = DVR->location_ops();
2402assert(
2403is_contained(DVRLocation, &I) &&
2404"DbgVariableIntrinsic must use salvaged instruction as its location");
2405SmallVector<Value *, 4> AdditionalValues;
2406// 'I' may appear more than once in DVR's location ops, and each use of 'I'
2407// must be updated in the DIExpression and potentially have additional
2408// values added; thus we call salvageDebugInfoImpl for each 'I' instance in
2409// DVRLocation.
2410Value *Op0 =nullptr;
2411DIExpression *SalvagedExpr = DVR->getExpression();
2412auto LocItr =find(DVRLocation, &I);
2413while (SalvagedExpr && LocItr != DVRLocation.end()) {
2414SmallVector<uint64_t, 16> Ops;
2415unsigned LocNo = std::distance(DVRLocation.begin(), LocItr);
2416uint64_t CurrentLocOps = SalvagedExpr->getNumLocationOperands();
2417 Op0 =salvageDebugInfoImpl(I, CurrentLocOps, Ops, AdditionalValues);
2418if (!Op0)
2419break;
2420 SalvagedExpr =
2421DIExpression::appendOpsToArg(SalvagedExpr, Ops, LocNo, StackValue);
2422 LocItr = std::find(++LocItr, DVRLocation.end(), &I);
2423 }
2424// salvageDebugInfoImpl should fail on examining the first element of
2425// DbgUsers, or none of them.
2426if (!Op0)
2427break;
2428
2429 SalvagedExpr = SalvagedExpr->foldConstantMath();
2430 DVR->replaceVariableLocationOp(&I, Op0);
2431bool IsValidSalvageExpr =
2432 SalvagedExpr->getNumElements() <= MaxExpressionSize;
2433if (AdditionalValues.empty() && IsValidSalvageExpr) {
2434 DVR->setExpression(SalvagedExpr);
2435 }elseif (DVR->getType() != DbgVariableRecord::LocationType::Declare &&
2436 IsValidSalvageExpr &&
2437 DVR->getNumVariableLocationOps() + AdditionalValues.size() <=
2438 MaxDebugArgs) {
2439 DVR->addVariableLocationOps(AdditionalValues, SalvagedExpr);
2440 }else {
2441// Do not salvage using DIArgList for dbg.addr/dbg.declare, as it is
2442// currently only valid for stack value expressions.
2443// Also do not salvage if the resulting DIArgList would contain an
2444// unreasonably large number of values.
2445 DVR->setKillLocation();
2446 }
2447LLVM_DEBUG(dbgs() <<"SALVAGE: " << DVR <<'\n');
2448 Salvaged =true;
2449 }
2450
2451if (Salvaged)
2452return;
2453
2454for (auto *DII : DbgUsers)
2455 DII->setKillLocation();
2456
2457for (auto *DVR : DPUsers)
2458 DVR->setKillLocation();
2459}
2460
2461Value *getSalvageOpsForGEP(GetElementPtrInst *GEP,constDataLayout &DL,
2462uint64_t CurrentLocOps,
2463SmallVectorImpl<uint64_t> &Opcodes,
2464SmallVectorImpl<Value *> &AdditionalValues) {
2465unsignedBitWidth =DL.getIndexSizeInBits(GEP->getPointerAddressSpace());
2466// Rewrite a GEP into a DIExpression.
2467SmallMapVector<Value *, APInt, 4> VariableOffsets;
2468APInt ConstantOffset(BitWidth, 0);
2469if (!GEP->collectOffset(DL,BitWidth, VariableOffsets, ConstantOffset))
2470returnnullptr;
2471if (!VariableOffsets.empty() && !CurrentLocOps) {
2472 Opcodes.insert(Opcodes.begin(), {dwarf::DW_OP_LLVM_arg, 0});
2473 CurrentLocOps = 1;
2474 }
2475for (constauto &Offset : VariableOffsets) {
2476 AdditionalValues.push_back(Offset.first);
2477assert(Offset.second.isStrictlyPositive() &&
2478"Expected strictly positive multiplier for offset.");
2479 Opcodes.append({dwarf::DW_OP_LLVM_arg, CurrentLocOps++, dwarf::DW_OP_constu,
2480Offset.second.getZExtValue(), dwarf::DW_OP_mul,
2481 dwarf::DW_OP_plus});
2482 }
2483DIExpression::appendOffset(Opcodes, ConstantOffset.getSExtValue());
2484returnGEP->getOperand(0);
2485}
2486
2487uint64_tgetDwarfOpForBinOp(Instruction::BinaryOps Opcode) {
2488switch (Opcode) {
2489case Instruction::Add:
2490return dwarf::DW_OP_plus;
2491case Instruction::Sub:
2492return dwarf::DW_OP_minus;
2493case Instruction::Mul:
2494return dwarf::DW_OP_mul;
2495case Instruction::SDiv:
2496return dwarf::DW_OP_div;
2497case Instruction::SRem:
2498return dwarf::DW_OP_mod;
2499case Instruction::Or:
2500return dwarf::DW_OP_or;
2501case Instruction::And:
2502return dwarf::DW_OP_and;
2503case Instruction::Xor:
2504return dwarf::DW_OP_xor;
2505case Instruction::Shl:
2506return dwarf::DW_OP_shl;
2507case Instruction::LShr:
2508return dwarf::DW_OP_shr;
2509case Instruction::AShr:
2510return dwarf::DW_OP_shra;
2511default:
2512// TODO: Salvage from each kind of binop we know about.
2513return 0;
2514 }
2515}
2516
2517staticvoidhandleSSAValueOperands(uint64_t CurrentLocOps,
2518SmallVectorImpl<uint64_t> &Opcodes,
2519SmallVectorImpl<Value *> &AdditionalValues,
2520Instruction *I) {
2521if (!CurrentLocOps) {
2522 Opcodes.append({dwarf::DW_OP_LLVM_arg, 0});
2523 CurrentLocOps = 1;
2524 }
2525 Opcodes.append({dwarf::DW_OP_LLVM_arg, CurrentLocOps});
2526 AdditionalValues.push_back(I->getOperand(1));
2527}
2528
2529Value *getSalvageOpsForBinOp(BinaryOperator *BI,uint64_t CurrentLocOps,
2530SmallVectorImpl<uint64_t> &Opcodes,
2531SmallVectorImpl<Value *> &AdditionalValues) {
2532// Handle binary operations with constant integer operands as a special case.
2533auto *ConstInt = dyn_cast<ConstantInt>(BI->getOperand(1));
2534// Values wider than 64 bits cannot be represented within a DIExpression.
2535if (ConstInt && ConstInt->getBitWidth() > 64)
2536returnnullptr;
2537
2538Instruction::BinaryOps BinOpcode = BI->getOpcode();
2539// Push any Constant Int operand onto the expression stack.
2540if (ConstInt) {
2541uint64_t Val = ConstInt->getSExtValue();
2542// Add or Sub Instructions with a constant operand can potentially be
2543// simplified.
2544if (BinOpcode == Instruction::Add || BinOpcode == Instruction::Sub) {
2545uint64_tOffset = BinOpcode == Instruction::Add ? Val : -int64_t(Val);
2546DIExpression::appendOffset(Opcodes,Offset);
2547return BI->getOperand(0);
2548 }
2549 Opcodes.append({dwarf::DW_OP_constu, Val});
2550 }else {
2551handleSSAValueOperands(CurrentLocOps, Opcodes, AdditionalValues, BI);
2552 }
2553
2554// Add salvaged binary operator to expression stack, if it has a valid
2555// representation in a DIExpression.
2556uint64_t DwarfBinOp =getDwarfOpForBinOp(BinOpcode);
2557if (!DwarfBinOp)
2558returnnullptr;
2559 Opcodes.push_back(DwarfBinOp);
2560return BI->getOperand(0);
2561}
2562
2563uint64_tgetDwarfOpForIcmpPred(CmpInst::Predicate Pred) {
2564// The signedness of the operation is implicit in the typed stack, signed and
2565// unsigned instructions map to the same DWARF opcode.
2566switch (Pred) {
2567caseCmpInst::ICMP_EQ:
2568return dwarf::DW_OP_eq;
2569caseCmpInst::ICMP_NE:
2570return dwarf::DW_OP_ne;
2571caseCmpInst::ICMP_UGT:
2572caseCmpInst::ICMP_SGT:
2573return dwarf::DW_OP_gt;
2574caseCmpInst::ICMP_UGE:
2575caseCmpInst::ICMP_SGE:
2576return dwarf::DW_OP_ge;
2577caseCmpInst::ICMP_ULT:
2578caseCmpInst::ICMP_SLT:
2579return dwarf::DW_OP_lt;
2580caseCmpInst::ICMP_ULE:
2581caseCmpInst::ICMP_SLE:
2582return dwarf::DW_OP_le;
2583default:
2584return 0;
2585 }
2586}
2587
2588Value *getSalvageOpsForIcmpOp(ICmpInst *Icmp,uint64_t CurrentLocOps,
2589SmallVectorImpl<uint64_t> &Opcodes,
2590SmallVectorImpl<Value *> &AdditionalValues) {
2591// Handle icmp operations with constant integer operands as a special case.
2592auto *ConstInt = dyn_cast<ConstantInt>(Icmp->getOperand(1));
2593// Values wider than 64 bits cannot be represented within a DIExpression.
2594if (ConstInt && ConstInt->getBitWidth() > 64)
2595returnnullptr;
2596// Push any Constant Int operand onto the expression stack.
2597if (ConstInt) {
2598if (Icmp->isSigned())
2599 Opcodes.push_back(dwarf::DW_OP_consts);
2600else
2601 Opcodes.push_back(dwarf::DW_OP_constu);
2602uint64_t Val = ConstInt->getSExtValue();
2603 Opcodes.push_back(Val);
2604 }else {
2605handleSSAValueOperands(CurrentLocOps, Opcodes, AdditionalValues, Icmp);
2606 }
2607
2608// Add salvaged binary operator to expression stack, if it has a valid
2609// representation in a DIExpression.
2610uint64_t DwarfIcmpOp =getDwarfOpForIcmpPred(Icmp->getPredicate());
2611if (!DwarfIcmpOp)
2612returnnullptr;
2613 Opcodes.push_back(DwarfIcmpOp);
2614return Icmp->getOperand(0);
2615}
2616
2617Value *llvm::salvageDebugInfoImpl(Instruction &I,uint64_t CurrentLocOps,
2618SmallVectorImpl<uint64_t> &Ops,
2619SmallVectorImpl<Value *> &AdditionalValues) {
2620auto &M = *I.getModule();
2621auto &DL = M.getDataLayout();
2622
2623if (auto *CI = dyn_cast<CastInst>(&I)) {
2624Value *FromValue = CI->getOperand(0);
2625// No-op casts are irrelevant for debug info.
2626if (CI->isNoopCast(DL)) {
2627return FromValue;
2628 }
2629
2630Type *Type = CI->getType();
2631if (Type->isPointerTy())
2632Type =DL.getIntPtrType(Type);
2633// Casts other than Trunc, SExt, or ZExt to scalar types cannot be salvaged.
2634if (Type->isVectorTy() ||
2635 !(isa<TruncInst>(&I) || isa<SExtInst>(&I) || isa<ZExtInst>(&I) ||
2636 isa<IntToPtrInst>(&I) || isa<PtrToIntInst>(&I)))
2637returnnullptr;
2638
2639llvm::Type *FromType = FromValue->getType();
2640if (FromType->isPointerTy())
2641 FromType =DL.getIntPtrType(FromType);
2642
2643unsigned FromTypeBitSize = FromType->getScalarSizeInBits();
2644unsigned ToTypeBitSize =Type->getScalarSizeInBits();
2645
2646auto ExtOps =DIExpression::getExtOps(FromTypeBitSize, ToTypeBitSize,
2647 isa<SExtInst>(&I));
2648 Ops.append(ExtOps.begin(), ExtOps.end());
2649return FromValue;
2650 }
2651
2652if (auto *GEP = dyn_cast<GetElementPtrInst>(&I))
2653returngetSalvageOpsForGEP(GEP,DL, CurrentLocOps, Ops, AdditionalValues);
2654if (auto *BI = dyn_cast<BinaryOperator>(&I))
2655returngetSalvageOpsForBinOp(BI, CurrentLocOps, Ops, AdditionalValues);
2656if (auto *IC = dyn_cast<ICmpInst>(&I))
2657returngetSalvageOpsForIcmpOp(IC, CurrentLocOps, Ops, AdditionalValues);
2658
2659// *Not* to do: we should not attempt to salvage load instructions,
2660// because the validity and lifetime of a dbg.value containing
2661// DW_OP_deref becomes difficult to analyze. See PR40628 for examples.
2662returnnullptr;
2663}
2664
2665/// A replacement for a dbg.value expression.
2666usingDbgValReplacement = std::optional<DIExpression *>;
2667
2668/// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
2669/// possibly moving/undefing users to prevent use-before-def. Returns true if
2670/// changes are made.
2671staticboolrewriteDebugUsers(
2672Instruction &From,Value &To,Instruction &DomPoint,DominatorTree &DT,
2673function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr,
2674function_ref<DbgValReplacement(DbgVariableRecord &DVR)> RewriteDVRExpr) {
2675// Find debug users of From.
2676SmallVector<DbgVariableIntrinsic *, 1>Users;
2677SmallVector<DbgVariableRecord *, 1> DPUsers;
2678findDbgUsers(Users, &From, &DPUsers);
2679if (Users.empty() && DPUsers.empty())
2680returnfalse;
2681
2682// Prevent use-before-def of To.
2683bool Changed =false;
2684
2685SmallPtrSet<DbgVariableIntrinsic *, 1> UndefOrSalvage;
2686SmallPtrSet<DbgVariableRecord *, 1> UndefOrSalvageDVR;
2687if (isa<Instruction>(&To)) {
2688bool DomPointAfterFrom =From.getNextNonDebugInstruction() == &DomPoint;
2689
2690for (auto *DII :Users) {
2691// It's common to see a debug user between From and DomPoint. Move it
2692// after DomPoint to preserve the variable update without any reordering.
2693if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
2694LLVM_DEBUG(dbgs() <<"MOVE: " << *DII <<'\n');
2695 DII->moveAfter(&DomPoint);
2696 Changed =true;
2697
2698// Users which otherwise aren't dominated by the replacement value must
2699// be salvaged or deleted.
2700 }elseif (!DT.dominates(&DomPoint, DII)) {
2701 UndefOrSalvage.insert(DII);
2702 }
2703 }
2704
2705// DbgVariableRecord implementation of the above.
2706for (auto *DVR : DPUsers) {
2707Instruction *MarkedInstr = DVR->getMarker()->MarkedInstr;
2708Instruction *NextNonDebug = MarkedInstr;
2709// The next instruction might still be a dbg.declare, skip over it.
2710if (isa<DbgVariableIntrinsic>(NextNonDebug))
2711 NextNonDebug = NextNonDebug->getNextNonDebugInstruction();
2712
2713if (DomPointAfterFrom && NextNonDebug == &DomPoint) {
2714LLVM_DEBUG(dbgs() <<"MOVE: " << *DVR <<'\n');
2715 DVR->removeFromParent();
2716// Ensure there's a marker.
2717 DomPoint.getParent()->insertDbgRecordAfter(DVR, &DomPoint);
2718 Changed =true;
2719 }elseif (!DT.dominates(&DomPoint, MarkedInstr)) {
2720 UndefOrSalvageDVR.insert(DVR);
2721 }
2722 }
2723 }
2724
2725// Update debug users without use-before-def risk.
2726for (auto *DII :Users) {
2727if (UndefOrSalvage.count(DII))
2728continue;
2729
2730DbgValReplacement DVRepl = RewriteExpr(*DII);
2731if (!DVRepl)
2732continue;
2733
2734 DII->replaceVariableLocationOp(&From, &To);
2735 DII->setExpression(*DVRepl);
2736LLVM_DEBUG(dbgs() <<"REWRITE: " << *DII <<'\n');
2737 Changed =true;
2738 }
2739for (auto *DVR : DPUsers) {
2740if (UndefOrSalvageDVR.count(DVR))
2741continue;
2742
2743DbgValReplacement DVRepl = RewriteDVRExpr(*DVR);
2744if (!DVRepl)
2745continue;
2746
2747 DVR->replaceVariableLocationOp(&From, &To);
2748 DVR->setExpression(*DVRepl);
2749LLVM_DEBUG(dbgs() <<"REWRITE: " << DVR <<'\n');
2750 Changed =true;
2751 }
2752
2753if (!UndefOrSalvage.empty() || !UndefOrSalvageDVR.empty()) {
2754// Try to salvage the remaining debug users.
2755salvageDebugInfo(From);
2756 Changed =true;
2757 }
2758
2759return Changed;
2760}
2761
2762/// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
2763/// losslessly preserve the bits and semantics of the value. This predicate is
2764/// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
2765///
2766/// Note that Type::canLosslesslyBitCastTo is not suitable here because it
2767/// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
2768/// and also does not allow lossless pointer <-> integer conversions.
2769staticboolisBitCastSemanticsPreserving(constDataLayout &DL,Type *FromTy,
2770Type *ToTy) {
2771// Trivially compatible types.
2772if (FromTy == ToTy)
2773returntrue;
2774
2775// Handle compatible pointer <-> integer conversions.
2776if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
2777bool SameSize =DL.getTypeSizeInBits(FromTy) ==DL.getTypeSizeInBits(ToTy);
2778bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
2779 !DL.isNonIntegralPointerType(ToTy);
2780return SameSize && LosslessConversion;
2781 }
2782
2783// TODO: This is not exhaustive.
2784returnfalse;
2785}
2786
2787boolllvm::replaceAllDbgUsesWith(Instruction &From,Value &To,
2788Instruction &DomPoint,DominatorTree &DT) {
2789// Exit early if From has no debug users.
2790if (!From.isUsedByMetadata())
2791returnfalse;
2792
2793assert(&From != &To &&"Can't replace something with itself");
2794
2795Type *FromTy =From.getType();
2796Type *ToTy = To.getType();
2797
2798auto Identity = [&](DbgVariableIntrinsic &DII) ->DbgValReplacement {
2799return DII.getExpression();
2800 };
2801auto IdentityDVR = [&](DbgVariableRecord &DVR) ->DbgValReplacement {
2802return DVR.getExpression();
2803 };
2804
2805// Handle no-op conversions.
2806Module &M = *From.getModule();
2807constDataLayout &DL = M.getDataLayout();
2808if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
2809returnrewriteDebugUsers(From, To, DomPoint, DT, Identity, IdentityDVR);
2810
2811// Handle integer-to-integer widening and narrowing.
2812// FIXME: Use DW_OP_convert when it's available everywhere.
2813if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
2814uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
2815uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
2816assert(FromBits != ToBits &&"Unexpected no-op conversion");
2817
2818// When the width of the result grows, assume that a debugger will only
2819// access the low `FromBits` bits when inspecting the source variable.
2820if (FromBits < ToBits)
2821returnrewriteDebugUsers(From, To, DomPoint, DT, Identity, IdentityDVR);
2822
2823// The width of the result has shrunk. Use sign/zero extension to describe
2824// the source variable's high bits.
2825auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) ->DbgValReplacement {
2826DILocalVariable *Var = DII.getVariable();
2827
2828// Without knowing signedness, sign/zero extension isn't possible.
2829auto Signedness = Var->getSignedness();
2830if (!Signedness)
2831return std::nullopt;
2832
2833boolSigned = *Signedness == DIBasicType::Signedness::Signed;
2834returnDIExpression::appendExt(DII.getExpression(), ToBits, FromBits,
2835Signed);
2836 };
2837// RemoveDIs: duplicate implementation working on DbgVariableRecords rather
2838// than on dbg.value intrinsics.
2839auto SignOrZeroExtDVR = [&](DbgVariableRecord &DVR) ->DbgValReplacement {
2840DILocalVariable *Var = DVR.getVariable();
2841
2842// Without knowing signedness, sign/zero extension isn't possible.
2843auto Signedness = Var->getSignedness();
2844if (!Signedness)
2845return std::nullopt;
2846
2847boolSigned = *Signedness == DIBasicType::Signedness::Signed;
2848returnDIExpression::appendExt(DVR.getExpression(), ToBits, FromBits,
2849Signed);
2850 };
2851returnrewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt,
2852 SignOrZeroExtDVR);
2853 }
2854
2855// TODO: Floating-point conversions, vectors.
2856returnfalse;
2857}
2858
2859boolllvm::handleUnreachableTerminator(
2860Instruction *I,SmallVectorImpl<Value *> &PoisonedValues) {
2861bool Changed =false;
2862// RemoveDIs: erase debug-info on this instruction manually.
2863I->dropDbgRecords();
2864for (Use &U :I->operands()) {
2865Value *Op = U.get();
2866if (isa<Instruction>(Op) && !Op->getType()->isTokenTy()) {
2867 U.set(PoisonValue::get(Op->getType()));
2868 PoisonedValues.push_back(Op);
2869 Changed =true;
2870 }
2871 }
2872
2873return Changed;
2874}
2875
2876std::pair<unsigned, unsigned>
2877llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
2878unsigned NumDeadInst = 0;
2879unsigned NumDeadDbgInst = 0;
2880// Delete the instructions backwards, as it has a reduced likelihood of
2881// having to update as many def-use and use-def chains.
2882Instruction *EndInst = BB->getTerminator();// Last not to be deleted.
2883SmallVector<Value *>Uses;
2884handleUnreachableTerminator(EndInst,Uses);
2885
2886while (EndInst != &BB->front()) {
2887// Delete the next to last instruction.
2888Instruction *Inst = &*--EndInst->getIterator();
2889if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
2890 Inst->replaceAllUsesWith(PoisonValue::get(Inst->getType()));
2891if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
2892// EHPads can't have DbgVariableRecords attached to them, but it might be
2893// possible for things with token type.
2894 Inst->dropDbgRecords();
2895 EndInst = Inst;
2896continue;
2897 }
2898if (isa<DbgInfoIntrinsic>(Inst))
2899 ++NumDeadDbgInst;
2900else
2901 ++NumDeadInst;
2902// RemoveDIs: erasing debug-info must be done manually.
2903 Inst->dropDbgRecords();
2904 Inst->eraseFromParent();
2905 }
2906return {NumDeadInst, NumDeadDbgInst};
2907}
2908
2909unsignedllvm::changeToUnreachable(Instruction *I,bool PreserveLCSSA,
2910DomTreeUpdater *DTU,
2911MemorySSAUpdater *MSSAU) {
2912BasicBlock *BB =I->getParent();
2913
2914if (MSSAU)
2915 MSSAU->changeToUnreachable(I);
2916
2917SmallSet<BasicBlock *, 8> UniqueSuccessors;
2918
2919// Loop over all of the successors, removing BB's entry from any PHI
2920// nodes.
2921for (BasicBlock *Successor :successors(BB)) {
2922Successor->removePredecessor(BB, PreserveLCSSA);
2923if (DTU)
2924 UniqueSuccessors.insert(Successor);
2925 }
2926auto *UI =newUnreachableInst(I->getContext(),I->getIterator());
2927 UI->setDebugLoc(I->getDebugLoc());
2928
2929// All instructions after this are dead.
2930unsigned NumInstrsRemoved = 0;
2931BasicBlock::iterator BBI =I->getIterator(), BBE = BB->end();
2932while (BBI != BBE) {
2933if (!BBI->use_empty())
2934 BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
2935 BBI++->eraseFromParent();
2936 ++NumInstrsRemoved;
2937 }
2938if (DTU) {
2939SmallVector<DominatorTree::UpdateType, 8> Updates;
2940 Updates.reserve(UniqueSuccessors.size());
2941for (BasicBlock *UniqueSuccessor : UniqueSuccessors)
2942 Updates.push_back({DominatorTree::Delete, BB, UniqueSuccessor});
2943 DTU->applyUpdates(Updates);
2944 }
2945 BB->flushTerminatorDbgRecords();
2946return NumInstrsRemoved;
2947}
2948
2949CallInst *llvm::createCallMatchingInvoke(InvokeInst *II) {
2950SmallVector<Value *, 8> Args(II->args());
2951SmallVector<OperandBundleDef, 1> OpBundles;
2952II->getOperandBundlesAsDefs(OpBundles);
2953CallInst *NewCall =CallInst::Create(II->getFunctionType(),
2954II->getCalledOperand(), Args, OpBundles);
2955 NewCall->setCallingConv(II->getCallingConv());
2956 NewCall->setAttributes(II->getAttributes());
2957 NewCall->setDebugLoc(II->getDebugLoc());
2958 NewCall->copyMetadata(*II);
2959
2960// If the invoke had profile metadata, try converting them for CallInst.
2961uint64_t TotalWeight;
2962if (NewCall->extractProfTotalWeight(TotalWeight)) {
2963// Set the total weight if it fits into i32, otherwise reset.
2964MDBuilder MDB(NewCall->getContext());
2965auto NewWeights =uint32_t(TotalWeight) != TotalWeight
2966 ? nullptr
2967 : MDB.createBranchWeights({uint32_t(TotalWeight)});
2968 NewCall->setMetadata(LLVMContext::MD_prof, NewWeights);
2969 }
2970
2971return NewCall;
2972}
2973
2974// changeToCall - Convert the specified invoke into a normal call.
2975CallInst *llvm::changeToCall(InvokeInst *II,DomTreeUpdater *DTU) {
2976CallInst *NewCall =createCallMatchingInvoke(II);
2977 NewCall->takeName(II);
2978 NewCall->insertBefore(II->getIterator());
2979II->replaceAllUsesWith(NewCall);
2980
2981// Follow the call by a branch to the normal destination.
2982BasicBlock *NormalDestBB =II->getNormalDest();
2983BranchInst::Create(NormalDestBB,II->getIterator());
2984
2985// Update PHI nodes in the unwind destination
2986BasicBlock *BB =II->getParent();
2987BasicBlock *UnwindDestBB =II->getUnwindDest();
2988 UnwindDestBB->removePredecessor(BB);
2989II->eraseFromParent();
2990if (DTU)
2991 DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});
2992return NewCall;
2993}
2994
2995BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
2996BasicBlock *UnwindEdge,
2997DomTreeUpdater *DTU) {
2998BasicBlock *BB = CI->getParent();
2999
3000// Convert this function call into an invoke instruction. First, split the
3001// basic block.
3002BasicBlock *Split =SplitBlock(BB, CI, DTU,/*LI=*/nullptr,/*MSSAU*/nullptr,
3003 CI->getName() +".noexc");
3004
3005// Delete the unconditional branch inserted by SplitBlock
3006 BB->back().eraseFromParent();
3007
3008// Create the new invoke instruction.
3009SmallVector<Value *, 8> InvokeArgs(CI->args());
3010SmallVector<OperandBundleDef, 1> OpBundles;
3011
3012 CI->getOperandBundlesAsDefs(OpBundles);
3013
3014// Note: we're round tripping operand bundles through memory here, and that
3015// can potentially be avoided with a cleverer API design that we do not have
3016// as of this time.
3017
3018InvokeInst *II =
3019InvokeInst::Create(CI->getFunctionType(), CI->getCalledOperand(), Split,
3020 UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);
3021II->setDebugLoc(CI->getDebugLoc());
3022II->setCallingConv(CI->getCallingConv());
3023II->setAttributes(CI->getAttributes());
3024II->setMetadata(LLVMContext::MD_prof, CI->getMetadata(LLVMContext::MD_prof));
3025
3026if (DTU)
3027 DTU->applyUpdates({{DominatorTree::Insert, BB, UnwindEdge}});
3028
3029// Make sure that anything using the call now uses the invoke! This also
3030// updates the CallGraph if present, because it uses a WeakTrackingVH.
3031 CI->replaceAllUsesWith(II);
3032
3033// Delete the original call
3034 Split->front().eraseFromParent();
3035return Split;
3036}
3037
3038staticboolmarkAliveBlocks(Function &F,
3039SmallPtrSetImpl<BasicBlock *> &Reachable,
3040DomTreeUpdater *DTU =nullptr) {
3041SmallVector<BasicBlock*, 128> Worklist;
3042BasicBlock *BB = &F.front();
3043 Worklist.push_back(BB);
3044 Reachable.insert(BB);
3045bool Changed =false;
3046do {
3047 BB = Worklist.pop_back_val();
3048
3049// Do a quick scan of the basic block, turning any obviously unreachable
3050// instructions into LLVM unreachable insts. The instruction combining pass
3051// canonicalizes unreachable insts into stores to null or undef.
3052for (Instruction &I : *BB) {
3053if (auto *CI = dyn_cast<CallInst>(&I)) {
3054Value *Callee = CI->getCalledOperand();
3055// Handle intrinsic calls.
3056if (Function *F = dyn_cast<Function>(Callee)) {
3057auto IntrinsicID =F->getIntrinsicID();
3058// Assumptions that are known to be false are equivalent to
3059// unreachable. Also, if the condition is undefined, then we make the
3060// choice most beneficial to the optimizer, and choose that to also be
3061// unreachable.
3062if (IntrinsicID == Intrinsic::assume) {
3063if (match(CI->getArgOperand(0),m_CombineOr(m_Zero(),m_Undef()))) {
3064// Don't insert a call to llvm.trap right before the unreachable.
3065changeToUnreachable(CI,false, DTU);
3066 Changed =true;
3067break;
3068 }
3069 }elseif (IntrinsicID == Intrinsic::experimental_guard) {
3070// A call to the guard intrinsic bails out of the current
3071// compilation unit if the predicate passed to it is false. If the
3072// predicate is a constant false, then we know the guard will bail
3073// out of the current compile unconditionally, so all code following
3074// it is dead.
3075//
3076// Note: unlike in llvm.assume, it is not "obviously profitable" for
3077// guards to treat `undef` as `false` since a guard on `undef` can
3078// still be useful for widening.
3079if (match(CI->getArgOperand(0),m_Zero()))
3080if (!isa<UnreachableInst>(CI->getNextNode())) {
3081changeToUnreachable(CI->getNextNode(),false, DTU);
3082 Changed =true;
3083break;
3084 }
3085 }
3086 }elseif ((isa<ConstantPointerNull>(Callee) &&
3087 !NullPointerIsDefined(CI->getFunction(),
3088 cast<PointerType>(Callee->getType())
3089 ->getAddressSpace())) ||
3090 isa<UndefValue>(Callee)) {
3091changeToUnreachable(CI,false, DTU);
3092 Changed =true;
3093break;
3094 }
3095if (CI->doesNotReturn() && !CI->isMustTailCall()) {
3096// If we found a call to a no-return function, insert an unreachable
3097// instruction after it. Make sure there isn't *already* one there
3098// though.
3099if (!isa<UnreachableInst>(CI->getNextNonDebugInstruction())) {
3100// Don't insert a call to llvm.trap right before the unreachable.
3101changeToUnreachable(CI->getNextNonDebugInstruction(),false, DTU);
3102 Changed =true;
3103 }
3104break;
3105 }
3106 }elseif (auto *SI = dyn_cast<StoreInst>(&I)) {
3107// Store to undef and store to null are undefined and used to signal
3108// that they should be changed to unreachable by passes that can't
3109// modify the CFG.
3110
3111// Don't touch volatile stores.
3112if (SI->isVolatile())continue;
3113
3114Value *Ptr = SI->getOperand(1);
3115
3116if (isa<UndefValue>(Ptr) ||
3117 (isa<ConstantPointerNull>(Ptr) &&
3118 !NullPointerIsDefined(SI->getFunction(),
3119 SI->getPointerAddressSpace()))) {
3120changeToUnreachable(SI,false, DTU);
3121 Changed =true;
3122break;
3123 }
3124 }
3125 }
3126
3127Instruction *Terminator = BB->getTerminator();
3128if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
3129// Turn invokes that call 'nounwind' functions into ordinary calls.
3130Value *Callee =II->getCalledOperand();
3131if ((isa<ConstantPointerNull>(Callee) &&
3132 !NullPointerIsDefined(BB->getParent())) ||
3133 isa<UndefValue>(Callee)) {
3134changeToUnreachable(II,false, DTU);
3135 Changed =true;
3136 }else {
3137if (II->doesNotReturn() &&
3138 !isa<UnreachableInst>(II->getNormalDest()->front())) {
3139// If we found an invoke of a no-return function,
3140// create a new empty basic block with an `unreachable` terminator,
3141// and set it as the normal destination for the invoke,
3142// unless that is already the case.
3143// Note that the original normal destination could have other uses.
3144BasicBlock *OrigNormalDest =II->getNormalDest();
3145 OrigNormalDest->removePredecessor(II->getParent());
3146LLVMContext &Ctx =II->getContext();
3147BasicBlock *UnreachableNormalDest =BasicBlock::Create(
3148 Ctx, OrigNormalDest->getName() +".unreachable",
3149II->getFunction(), OrigNormalDest);
3150newUnreachableInst(Ctx, UnreachableNormalDest);
3151II->setNormalDest(UnreachableNormalDest);
3152if (DTU)
3153 DTU->applyUpdates(
3154 {{DominatorTree::Delete, BB, OrigNormalDest},
3155 {DominatorTree::Insert, BB, UnreachableNormalDest}});
3156 Changed =true;
3157 }
3158if (II->doesNotThrow() &&canSimplifyInvokeNoUnwind(&F)) {
3159if (II->use_empty() && !II->mayHaveSideEffects()) {
3160// jump to the normal destination branch.
3161BasicBlock *NormalDestBB =II->getNormalDest();
3162BasicBlock *UnwindDestBB =II->getUnwindDest();
3163BranchInst::Create(NormalDestBB,II->getIterator());
3164 UnwindDestBB->removePredecessor(II->getParent());
3165II->eraseFromParent();
3166if (DTU)
3167 DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});
3168 }else
3169changeToCall(II, DTU);
3170 Changed =true;
3171 }
3172 }
3173 }elseif (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
3174// Remove catchpads which cannot be reached.
3175structCatchPadDenseMapInfo {
3176staticCatchPadInst *getEmptyKey() {
3177returnDenseMapInfo<CatchPadInst *>::getEmptyKey();
3178 }
3179
3180staticCatchPadInst *getTombstoneKey() {
3181returnDenseMapInfo<CatchPadInst *>::getTombstoneKey();
3182 }
3183
3184staticunsigned getHashValue(CatchPadInst *CatchPad) {
3185returnstatic_cast<unsigned>(hash_combine_range(
3186 CatchPad->value_op_begin(), CatchPad->value_op_end()));
3187 }
3188
3189staticboolisEqual(CatchPadInst *LHS,CatchPadInst *RHS) {
3190if (LHS == getEmptyKey() ||LHS == getTombstoneKey() ||
3191RHS == getEmptyKey() ||RHS == getTombstoneKey())
3192returnLHS ==RHS;
3193returnLHS->isIdenticalTo(RHS);
3194 }
3195 };
3196
3197SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
3198// Set of unique CatchPads.
3199SmallDenseMap<CatchPadInst *,detail::DenseSetEmpty, 4,
3200 CatchPadDenseMapInfo,detail::DenseSetPair<CatchPadInst *>>
3201 HandlerSet;
3202detail::DenseSetEmpty Empty;
3203for (CatchSwitchInst::handler_iteratorI = CatchSwitch->handler_begin(),
3204 E = CatchSwitch->handler_end();
3205I != E; ++I) {
3206BasicBlock *HandlerBB = *I;
3207if (DTU)
3208 ++NumPerSuccessorCases[HandlerBB];
3209auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHIIt());
3210if (!HandlerSet.insert({CatchPad, Empty}).second) {
3211if (DTU)
3212 --NumPerSuccessorCases[HandlerBB];
3213 CatchSwitch->removeHandler(I);
3214 --I;
3215 --E;
3216 Changed =true;
3217 }
3218 }
3219if (DTU) {
3220 std::vector<DominatorTree::UpdateType> Updates;
3221for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
3222if (I.second == 0)
3223 Updates.push_back({DominatorTree::Delete, BB,I.first});
3224 DTU->applyUpdates(Updates);
3225 }
3226 }
3227
3228 Changed |=ConstantFoldTerminator(BB,true,nullptr, DTU);
3229for (BasicBlock *Successor :successors(BB))
3230if (Reachable.insert(Successor).second)
3231 Worklist.push_back(Successor);
3232 }while (!Worklist.empty());
3233return Changed;
3234}
3235
3236Instruction *llvm::removeUnwindEdge(BasicBlock *BB,DomTreeUpdater *DTU) {
3237Instruction *TI = BB->getTerminator();
3238
3239if (auto *II = dyn_cast<InvokeInst>(TI))
3240returnchangeToCall(II, DTU);
3241
3242Instruction *NewTI;
3243BasicBlock *UnwindDest;
3244
3245if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
3246 NewTI =CleanupReturnInst::Create(CRI->getCleanupPad(),nullptr, CRI->getIterator());
3247 UnwindDest = CRI->getUnwindDest();
3248 }elseif (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
3249auto *NewCatchSwitch =CatchSwitchInst::Create(
3250 CatchSwitch->getParentPad(),nullptr, CatchSwitch->getNumHandlers(),
3251 CatchSwitch->getName(), CatchSwitch->getIterator());
3252for (BasicBlock *PadBB : CatchSwitch->handlers())
3253 NewCatchSwitch->addHandler(PadBB);
3254
3255 NewTI = NewCatchSwitch;
3256 UnwindDest = CatchSwitch->getUnwindDest();
3257 }else {
3258llvm_unreachable("Could not find unwind successor");
3259 }
3260
3261 NewTI->takeName(TI);
3262 NewTI->setDebugLoc(TI->getDebugLoc());
3263 UnwindDest->removePredecessor(BB);
3264 TI->replaceAllUsesWith(NewTI);
3265 TI->eraseFromParent();
3266if (DTU)
3267 DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDest}});
3268return NewTI;
3269}
3270
3271/// removeUnreachableBlocks - Remove blocks that are not reachable, even
3272/// if they are in a dead cycle. Return true if a change was made, false
3273/// otherwise.
3274boolllvm::removeUnreachableBlocks(Function &F,DomTreeUpdater *DTU,
3275MemorySSAUpdater *MSSAU) {
3276SmallPtrSet<BasicBlock *, 16> Reachable;
3277bool Changed =markAliveBlocks(F, Reachable, DTU);
3278
3279// If there are unreachable blocks in the CFG...
3280if (Reachable.size() ==F.size())
3281return Changed;
3282
3283assert(Reachable.size() <F.size());
3284
3285// Are there any blocks left to actually delete?
3286SmallSetVector<BasicBlock *, 8> BlocksToRemove;
3287for (BasicBlock &BB :F) {
3288// Skip reachable basic blocks
3289if (Reachable.count(&BB))
3290continue;
3291// Skip already-deleted blocks
3292if (DTU && DTU->isBBPendingDeletion(&BB))
3293continue;
3294 BlocksToRemove.insert(&BB);
3295 }
3296
3297if (BlocksToRemove.empty())
3298return Changed;
3299
3300 Changed =true;
3301 NumRemoved += BlocksToRemove.size();
3302
3303if (MSSAU)
3304 MSSAU->removeBlocks(BlocksToRemove);
3305
3306DeleteDeadBlocks(BlocksToRemove.takeVector(), DTU);
3307
3308return Changed;
3309}
3310
3311/// If AAOnly is set, only intersect alias analysis metadata and preserve other
3312/// known metadata. Unknown metadata is always dropped.
3313staticvoidcombineMetadata(Instruction *K,constInstruction *J,
3314bool DoesKMove,bool AAOnly =false) {
3315SmallVector<std::pair<unsigned, MDNode *>, 4>Metadata;
3316 K->getAllMetadataOtherThanDebugLoc(Metadata);
3317for (constauto &MD :Metadata) {
3318unsigned Kind = MD.first;
3319MDNode *JMD = J->getMetadata(Kind);
3320MDNode *KMD = MD.second;
3321
3322// TODO: Assert that this switch is exhaustive for fixed MD kinds.
3323switch (Kind) {
3324default:
3325 K->setMetadata(Kind,nullptr);// Remove unknown metadata
3326break;
3327case LLVMContext::MD_dbg:
3328llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
3329case LLVMContext::MD_DIAssignID:
3330if (!AAOnly)
3331 K->mergeDIAssignID(J);
3332break;
3333case LLVMContext::MD_tbaa:
3334if (DoesKMove)
3335 K->setMetadata(Kind,MDNode::getMostGenericTBAA(JMD, KMD));
3336break;
3337case LLVMContext::MD_alias_scope:
3338if (DoesKMove)
3339 K->setMetadata(Kind,MDNode::getMostGenericAliasScope(JMD, KMD));
3340break;
3341case LLVMContext::MD_noalias:
3342case LLVMContext::MD_mem_parallel_loop_access:
3343if (DoesKMove)
3344 K->setMetadata(Kind,MDNode::intersect(JMD, KMD));
3345break;
3346case LLVMContext::MD_access_group:
3347if (DoesKMove)
3348 K->setMetadata(LLVMContext::MD_access_group,
3349intersectAccessGroups(K, J));
3350break;
3351case LLVMContext::MD_range:
3352if (!AAOnly && (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef)))
3353 K->setMetadata(Kind,MDNode::getMostGenericRange(JMD, KMD));
3354break;
3355case LLVMContext::MD_fpmath:
3356if (!AAOnly)
3357 K->setMetadata(Kind,MDNode::getMostGenericFPMath(JMD, KMD));
3358break;
3359case LLVMContext::MD_invariant_load:
3360// If K moves, only set the !invariant.load if it is present in both
3361// instructions.
3362if (DoesKMove)
3363 K->setMetadata(Kind, JMD);
3364break;
3365case LLVMContext::MD_nonnull:
3366if (!AAOnly && (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef)))
3367 K->setMetadata(Kind, JMD);
3368break;
3369case LLVMContext::MD_invariant_group:
3370// Preserve !invariant.group in K.
3371break;
3372case LLVMContext::MD_mmra:
3373// Combine MMRAs
3374break;
3375case LLVMContext::MD_align:
3376if (!AAOnly && (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef)))
3377 K->setMetadata(
3378 Kind,MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
3379break;
3380case LLVMContext::MD_dereferenceable:
3381case LLVMContext::MD_dereferenceable_or_null:
3382if (!AAOnly && DoesKMove)
3383 K->setMetadata(Kind,
3384MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
3385break;
3386case LLVMContext::MD_memprof:
3387if (!AAOnly)
3388 K->setMetadata(Kind,MDNode::getMergedMemProfMetadata(KMD, JMD));
3389break;
3390case LLVMContext::MD_callsite:
3391if (!AAOnly)
3392 K->setMetadata(Kind,MDNode::getMergedCallsiteMetadata(KMD, JMD));
3393break;
3394case LLVMContext::MD_preserve_access_index:
3395// Preserve !preserve.access.index in K.
3396break;
3397case LLVMContext::MD_noundef:
3398// If K does move, keep noundef if it is present in both instructions.
3399if (!AAOnly && DoesKMove)
3400 K->setMetadata(Kind, JMD);
3401break;
3402case LLVMContext::MD_nontemporal:
3403// Preserve !nontemporal if it is present on both instructions.
3404if (!AAOnly)
3405 K->setMetadata(Kind, JMD);
3406break;
3407case LLVMContext::MD_prof:
3408if (!AAOnly && DoesKMove)
3409 K->setMetadata(Kind,MDNode::getMergedProfMetadata(KMD, JMD, K, J));
3410break;
3411case LLVMContext::MD_noalias_addrspace:
3412if (DoesKMove)
3413 K->setMetadata(Kind,
3414MDNode::getMostGenericNoaliasAddrspace(JMD, KMD));
3415break;
3416 }
3417 }
3418// Set !invariant.group from J if J has it. If both instructions have it
3419// then we will just pick it from J - even when they are different.
3420// Also make sure that K is load or store - f.e. combining bitcast with load
3421// could produce bitcast with invariant.group metadata, which is invalid.
3422// FIXME: we should try to preserve both invariant.group md if they are
3423// different, but right now instruction can only have one invariant.group.
3424if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
3425if (isa<LoadInst>(K) || isa<StoreInst>(K))
3426 K->setMetadata(LLVMContext::MD_invariant_group, JMD);
3427
3428// Merge MMRAs.
3429// This is handled separately because we also want to handle cases where K
3430// doesn't have tags but J does.
3431auto JMMRA = J->getMetadata(LLVMContext::MD_mmra);
3432auto KMMRA = K->getMetadata(LLVMContext::MD_mmra);
3433if (JMMRA || KMMRA) {
3434 K->setMetadata(LLVMContext::MD_mmra,
3435MMRAMetadata::combine(K->getContext(), JMMRA, KMMRA));
3436 }
3437}
3438
3439voidllvm::combineMetadataForCSE(Instruction *K,constInstruction *J,
3440bool DoesKMove) {
3441combineMetadata(K, J, DoesKMove);
3442}
3443
3444voidllvm::combineAAMetadata(Instruction *K,constInstruction *J) {
3445combineMetadata(K, J,/*DoesKMove=*/true,/*AAOnly=*/true);
3446}
3447
3448voidllvm::copyMetadataForLoad(LoadInst &Dest,constLoadInst &Source) {
3449SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
3450 Source.getAllMetadata(MD);
3451MDBuilder MDB(Dest.getContext());
3452Type *NewType = Dest.getType();
3453constDataLayout &DL = Source.getDataLayout();
3454for (constauto &MDPair : MD) {
3455unsignedID = MDPair.first;
3456MDNode *N = MDPair.second;
3457// Note, essentially every kind of metadata should be preserved here! This
3458// routine is supposed to clone a load instruction changing *only its type*.
3459// The only metadata it makes sense to drop is metadata which is invalidated
3460// when the pointer type changes. This should essentially never be the case
3461// in LLVM, but we explicitly switch over only known metadata to be
3462// conservatively correct. If you are adding metadata to LLVM which pertains
3463// to loads, you almost certainly want to add it here.
3464switch (ID) {
3465case LLVMContext::MD_dbg:
3466case LLVMContext::MD_tbaa:
3467case LLVMContext::MD_prof:
3468case LLVMContext::MD_fpmath:
3469case LLVMContext::MD_tbaa_struct:
3470case LLVMContext::MD_invariant_load:
3471case LLVMContext::MD_alias_scope:
3472case LLVMContext::MD_noalias:
3473case LLVMContext::MD_nontemporal:
3474case LLVMContext::MD_mem_parallel_loop_access:
3475case LLVMContext::MD_access_group:
3476case LLVMContext::MD_noundef:
3477// All of these directly apply.
3478 Dest.setMetadata(ID,N);
3479break;
3480
3481case LLVMContext::MD_nonnull:
3482copyNonnullMetadata(Source,N, Dest);
3483break;
3484
3485case LLVMContext::MD_align:
3486case LLVMContext::MD_dereferenceable:
3487case LLVMContext::MD_dereferenceable_or_null:
3488// These only directly apply if the new type is also a pointer.
3489if (NewType->isPointerTy())
3490 Dest.setMetadata(ID,N);
3491break;
3492
3493case LLVMContext::MD_range:
3494copyRangeMetadata(DL, Source,N, Dest);
3495break;
3496 }
3497 }
3498}
3499
3500voidllvm::patchReplacementInstruction(Instruction *I,Value *Repl) {
3501auto *ReplInst = dyn_cast<Instruction>(Repl);
3502if (!ReplInst)
3503return;
3504
3505// Patch the replacement so that it is not more restrictive than the value
3506// being replaced.
3507WithOverflowInst *UnusedWO;
3508// When replacing the result of a llvm.*.with.overflow intrinsic with a
3509// overflowing binary operator, nuw/nsw flags may no longer hold.
3510if (isa<OverflowingBinaryOperator>(ReplInst) &&
3511match(I, m_ExtractValue<0>(m_WithOverflowInst(UnusedWO))))
3512 ReplInst->dropPoisonGeneratingFlags();
3513// Note that if 'I' is a load being replaced by some operation,
3514// for example, by an arithmetic operation, then andIRFlags()
3515// would just erase all math flags from the original arithmetic
3516// operation, which is clearly not wanted and not needed.
3517elseif (!isa<LoadInst>(I))
3518 ReplInst->andIRFlags(I);
3519
3520// Handle attributes.
3521if (auto *CB1 = dyn_cast<CallBase>(ReplInst)) {
3522if (auto *CB2 = dyn_cast<CallBase>(I)) {
3523boolSuccess = CB1->tryIntersectAttributes(CB2);
3524assert(Success &&"We should not be trying to sink callbases "
3525"with non-intersectable attributes");
3526// For NDEBUG Compile.
3527 (void)Success;
3528 }
3529 }
3530
3531// FIXME: If both the original and replacement value are part of the
3532// same control-flow region (meaning that the execution of one
3533// guarantees the execution of the other), then we can combine the
3534// noalias scopes here and do better than the general conservative
3535// answer used in combineMetadata().
3536
3537// In general, GVN unifies expressions over different control-flow
3538// regions, and so we need a conservative combination of the noalias
3539// scopes.
3540combineMetadataForCSE(ReplInst,I,false);
3541}
3542
3543template <typename RootType,typename ShouldReplaceFn>
3544staticunsignedreplaceDominatedUsesWith(Value *From,Value *To,
3545const RootType &Root,
3546const ShouldReplaceFn &ShouldReplace) {
3547assert(From->getType() == To->getType());
3548
3549unsigned Count = 0;
3550for (Use &U :llvm::make_early_inc_range(From->uses())) {
3551auto *II = dyn_cast<IntrinsicInst>(U.getUser());
3552if (II &&II->getIntrinsicID() == Intrinsic::fake_use)
3553continue;
3554if (!ShouldReplace(Root, U))
3555continue;
3556LLVM_DEBUG(dbgs() <<"Replace dominated use of '";
3557From->printAsOperand(dbgs());
3558dbgs() <<"' with " << *To <<" in " << *U.getUser() <<"\n");
3559 U.set(To);
3560 ++Count;
3561 }
3562return Count;
3563}
3564
3565unsignedllvm::replaceNonLocalUsesWith(Instruction *From,Value *To) {
3566assert(From->getType() == To->getType());
3567auto *BB =From->getParent();
3568unsigned Count = 0;
3569
3570for (Use &U :llvm::make_early_inc_range(From->uses())) {
3571auto *I = cast<Instruction>(U.getUser());
3572if (I->getParent() == BB)
3573continue;
3574 U.set(To);
3575 ++Count;
3576 }
3577return Count;
3578}
3579
3580unsignedllvm::replaceDominatedUsesWith(Value *From,Value *To,
3581DominatorTree &DT,
3582constBasicBlockEdge &Root) {
3583auto Dominates = [&DT](constBasicBlockEdge &Root,constUse &U) {
3584return DT.dominates(Root, U);
3585 };
3586 return ::replaceDominatedUsesWith(From, To, Root, Dominates);
3587}
3588
3589unsignedllvm::replaceDominatedUsesWith(Value *From,Value *To,
3590DominatorTree &DT,
3591constBasicBlock *BB) {
3592auto Dominates = [&DT](constBasicBlock *BB,constUse &U) {
3593return DT.dominates(BB, U);
3594 };
3595 return ::replaceDominatedUsesWith(From, To, BB, Dominates);
3596}
3597
3598unsignedllvm::replaceDominatedUsesWithIf(
3599Value *From,Value *To,DominatorTree &DT,constBasicBlockEdge &Root,
3600function_ref<bool(constUse &U,constValue *To)> ShouldReplace) {
3601auto DominatesAndShouldReplace =
3602 [&DT, &ShouldReplace, To](constBasicBlockEdge &Root,constUse &U) {
3603return DT.dominates(Root, U) && ShouldReplace(U, To);
3604 };
3605 return ::replaceDominatedUsesWith(From, To, Root, DominatesAndShouldReplace);
3606}
3607
3608unsignedllvm::replaceDominatedUsesWithIf(
3609Value *From,Value *To,DominatorTree &DT,constBasicBlock *BB,
3610function_ref<bool(constUse &U,constValue *To)> ShouldReplace) {
3611auto DominatesAndShouldReplace = [&DT, &ShouldReplace,
3612 To](constBasicBlock *BB,constUse &U) {
3613return DT.dominates(BB, U) && ShouldReplace(U, To);
3614 };
3615 return ::replaceDominatedUsesWith(From, To, BB, DominatesAndShouldReplace);
3616}
3617
3618boolllvm::callsGCLeafFunction(constCallBase *Call,
3619constTargetLibraryInfo &TLI) {
3620// Check if the function is specifically marked as a gc leaf function.
3621if (Call->hasFnAttr("gc-leaf-function"))
3622returntrue;
3623if (constFunction *F = Call->getCalledFunction()) {
3624if (F->hasFnAttribute("gc-leaf-function"))
3625returntrue;
3626
3627if (auto IID =F->getIntrinsicID()) {
3628// Most LLVM intrinsics do not take safepoints.
3629return IID != Intrinsic::experimental_gc_statepoint &&
3630 IID != Intrinsic::experimental_deoptimize &&
3631 IID != Intrinsic::memcpy_element_unordered_atomic &&
3632 IID != Intrinsic::memmove_element_unordered_atomic;
3633 }
3634 }
3635
3636// Lib calls can be materialized by some passes, and won't be
3637// marked as 'gc-leaf-function.' All available Libcalls are
3638// GC-leaf.
3639LibFunc LF;
3640if (TLI.getLibFunc(*Call, LF)) {
3641return TLI.has(LF);
3642 }
3643
3644returnfalse;
3645}
3646
3647voidllvm::copyNonnullMetadata(constLoadInst &OldLI,MDNode *N,
3648LoadInst &NewLI) {
3649auto *NewTy = NewLI.getType();
3650
3651// This only directly applies if the new type is also a pointer.
3652if (NewTy->isPointerTy()) {
3653 NewLI.setMetadata(LLVMContext::MD_nonnull,N);
3654return;
3655 }
3656
3657// The only other translation we can do is to integral loads with !range
3658// metadata.
3659if (!NewTy->isIntegerTy())
3660return;
3661
3662MDBuilder MDB(NewLI.getContext());
3663constValue *Ptr = OldLI.getPointerOperand();
3664auto *ITy = cast<IntegerType>(NewTy);
3665auto *NullInt =ConstantExpr::getPtrToInt(
3666ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
3667auto *NonNullInt =ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
3668 NewLI.setMetadata(LLVMContext::MD_range,
3669 MDB.createRange(NonNullInt, NullInt));
3670}
3671
3672voidllvm::copyRangeMetadata(constDataLayout &DL,constLoadInst &OldLI,
3673MDNode *N,LoadInst &NewLI) {
3674auto *NewTy = NewLI.getType();
3675// Simply copy the metadata if the type did not change.
3676if (NewTy == OldLI.getType()) {
3677 NewLI.setMetadata(LLVMContext::MD_range,N);
3678return;
3679 }
3680
3681// Give up unless it is converted to a pointer where there is a single very
3682// valuable mapping we can do reliably.
3683// FIXME: It would be nice to propagate this in more ways, but the type
3684// conversions make it hard.
3685if (!NewTy->isPointerTy())
3686return;
3687
3688unsignedBitWidth =DL.getPointerTypeSizeInBits(NewTy);
3689if (BitWidth == OldLI.getType()->getScalarSizeInBits() &&
3690 !getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
3691MDNode *NN =MDNode::get(OldLI.getContext(), {});
3692 NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
3693 }
3694}
3695
3696voidllvm::dropDebugUsers(Instruction &I) {
3697SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
3698SmallVector<DbgVariableRecord *, 1> DPUsers;
3699findDbgUsers(DbgUsers, &I, &DPUsers);
3700for (auto *DII : DbgUsers)
3701 DII->eraseFromParent();
3702for (auto *DVR : DPUsers)
3703 DVR->eraseFromParent();
3704}
3705
3706voidllvm::hoistAllInstructionsInto(BasicBlock *DomBlock,Instruction *InsertPt,
3707BasicBlock *BB) {
3708// Since we are moving the instructions out of its basic block, we do not
3709// retain their original debug locations (DILocations) and debug intrinsic
3710// instructions.
3711//
3712// Doing so would degrade the debugging experience and adversely affect the
3713// accuracy of profiling information.
3714//
3715// Currently, when hoisting the instructions, we take the following actions:
3716// - Remove their debug intrinsic instructions.
3717// - Set their debug locations to the values from the insertion point.
3718//
3719// As per PR39141 (comment #8), the more fundamental reason why the dbg.values
3720// need to be deleted, is because there will not be any instructions with a
3721// DILocation in either branch left after performing the transformation. We
3722// can only insert a dbg.value after the two branches are joined again.
3723//
3724// See PR38762, PR39243 for more details.
3725//
3726// TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
3727// encode predicated DIExpressions that yield different results on different
3728// code paths.
3729
3730for (BasicBlock::iteratorII = BB->begin(), IE = BB->end();II != IE;) {
3731Instruction *I = &*II;
3732I->dropUBImplyingAttrsAndMetadata();
3733if (I->isUsedByMetadata())
3734dropDebugUsers(*I);
3735// RemoveDIs: drop debug-info too as the following code does.
3736I->dropDbgRecords();
3737if (I->isDebugOrPseudoInst()) {
3738// Remove DbgInfo and pseudo probe Intrinsics.
3739II =I->eraseFromParent();
3740continue;
3741 }
3742I->setDebugLoc(InsertPt->getDebugLoc());
3743 ++II;
3744 }
3745 DomBlock->splice(InsertPt->getIterator(), BB, BB->begin(),
3746 BB->getTerminator()->getIterator());
3747}
3748
3749DIExpression *llvm::getExpressionForConstant(DIBuilder &DIB,constConstant &C,
3750Type &Ty) {
3751// Create integer constant expression.
3752auto createIntegerExpression = [&DIB](constConstant &CV) ->DIExpression * {
3753constAPInt &API = cast<ConstantInt>(&CV)->getValue();
3754 std::optional<int64_t> InitIntOpt = API.trySExtValue();
3755return InitIntOpt ? DIB.createConstantValueExpression(
3756static_cast<uint64_t>(*InitIntOpt))
3757 :nullptr;
3758 };
3759
3760if (isa<ConstantInt>(C))
3761return createIntegerExpression(C);
3762
3763auto *FP = dyn_cast<ConstantFP>(&C);
3764if (FP && Ty.isFloatingPointTy() && Ty.getScalarSizeInBits() <= 64) {
3765constAPFloat &APF =FP->getValueAPF();
3766APIntconst &API = APF.bitcastToAPInt();
3767if (auto Temp = API.getZExtValue())
3768return DIB.createConstantValueExpression(static_cast<uint64_t>(Temp));
3769return DIB.createConstantValueExpression(*API.getRawData());
3770 }
3771
3772if (!Ty.isPointerTy())
3773returnnullptr;
3774
3775if (isa<ConstantPointerNull>(C))
3776return DIB.createConstantValueExpression(0);
3777
3778if (constConstantExpr *CE = dyn_cast<ConstantExpr>(&C))
3779if (CE->getOpcode() == Instruction::IntToPtr) {
3780constValue *V = CE->getOperand(0);
3781if (auto CI = dyn_cast_or_null<ConstantInt>(V))
3782return createIntegerExpression(*CI);
3783 }
3784returnnullptr;
3785}
3786
3787voidllvm::remapDebugVariable(ValueToValueMapTy &Mapping,Instruction *Inst) {
3788auto RemapDebugOperands = [&Mapping](auto *DV,auto Set) {
3789for (auto *Op : Set) {
3790autoI = Mapping.find(Op);
3791if (I != Mapping.end())
3792 DV->replaceVariableLocationOp(Op,I->second,/*AllowEmpty=*/true);
3793 }
3794 };
3795auto RemapAssignAddress = [&Mapping](auto *DA) {
3796autoI = Mapping.find(DA->getAddress());
3797if (I != Mapping.end())
3798 DA->setAddress(I->second);
3799 };
3800if (auto DVI = dyn_cast<DbgVariableIntrinsic>(Inst))
3801 RemapDebugOperands(DVI, DVI->location_ops());
3802if (auto DAI = dyn_cast<DbgAssignIntrinsic>(Inst))
3803 RemapAssignAddress(DAI);
3804for (DbgVariableRecord &DVR :filterDbgVars(Inst->getDbgRecordRange())) {
3805 RemapDebugOperands(&DVR, DVR.location_ops());
3806if (DVR.isDbgAssign())
3807 RemapAssignAddress(&DVR);
3808 }
3809}
3810
3811namespace{
3812
3813/// A potential constituent of a bitreverse or bswap expression. See
3814/// collectBitParts for a fuller explanation.
3815structBitPart {
3816 BitPart(Value *P,unsigned BW) : Provider(P) {
3817Provenance.resize(BW);
3818 }
3819
3820 /// The Value that this is a bitreverse/bswap of.
3821Value *Provider;
3822
3823 /// The "provenance" of each bit. Provenance[A] = B means that bit A
3824 /// in Provider becomes bit B in the result of this expression.
3825SmallVector<int8_t, 32>Provenance;// int8_t means max size is i128.
3826
3827enum { Unset = -1 };
3828};
3829
3830}// end anonymous namespace
3831
3832/// Analyze the specified subexpression and see if it is capable of providing
3833/// pieces of a bswap or bitreverse. The subexpression provides a potential
3834/// piece of a bswap or bitreverse if it can be proved that each non-zero bit in
3835/// the output of the expression came from a corresponding bit in some other
3836/// value. This function is recursive, and the end result is a mapping of
3837/// bitnumber to bitnumber. It is the caller's responsibility to validate that
3838/// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
3839///
3840/// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
3841/// that the expression deposits the low byte of %X into the high byte of the
3842/// result and that all other bits are zero. This expression is accepted and a
3843/// BitPart is returned with Provider set to %X and Provenance[24-31] set to
3844/// [0-7].
3845///
3846/// For vector types, all analysis is performed at the per-element level. No
3847/// cross-element analysis is supported (shuffle/insertion/reduction), and all
3848/// constant masks must be splatted across all elements.
3849///
3850/// To avoid revisiting values, the BitPart results are memoized into the
3851/// provided map. To avoid unnecessary copying of BitParts, BitParts are
3852/// constructed in-place in the \c BPS map. Because of this \c BPS needs to
3853/// store BitParts objects, not pointers. As we need the concept of a nullptr
3854/// BitParts (Value has been analyzed and the analysis failed), we an Optional
3855/// type instead to provide the same functionality.
3856///
3857/// Because we pass around references into \c BPS, we must use a container that
3858/// does not invalidate internal references (std::map instead of DenseMap).
3859staticconst std::optional<BitPart> &
3860collectBitParts(Value *V,bool MatchBSwaps,bool MatchBitReversals,
3861 std::map<Value *, std::optional<BitPart>> &BPS,intDepth,
3862bool &FoundRoot) {
3863auto [I, Inserted] = BPS.try_emplace(V);
3864if (!Inserted)
3865returnI->second;
3866
3867auto &Result =I->second;
3868autoBitWidth = V->getType()->getScalarSizeInBits();
3869
3870// Can't do integer/elements > 128 bits.
3871if (BitWidth > 128)
3872return Result;
3873
3874// Prevent stack overflow by limiting the recursion depth
3875if (Depth ==BitPartRecursionMaxDepth) {
3876LLVM_DEBUG(dbgs() <<"collectBitParts max recursion depth reached.\n");
3877return Result;
3878 }
3879
3880if (auto *I = dyn_cast<Instruction>(V)) {
3881Value *X, *Y;
3882constAPInt *C;
3883
3884// If this is an or instruction, it may be an inner node of the bswap.
3885if (match(V,m_Or(m_Value(X),m_Value(Y)))) {
3886// Check we have both sources and they are from the same provider.
3887constauto &A =collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3888Depth + 1, FoundRoot);
3889if (!A || !A->Provider)
3890return Result;
3891
3892constauto &B =collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS,
3893Depth + 1, FoundRoot);
3894if (!B ||A->Provider !=B->Provider)
3895return Result;
3896
3897// Try and merge the two together.
3898 Result = BitPart(A->Provider,BitWidth);
3899for (unsigned BitIdx = 0; BitIdx <BitWidth; ++BitIdx) {
3900if (A->Provenance[BitIdx] != BitPart::Unset &&
3901B->Provenance[BitIdx] != BitPart::Unset &&
3902A->Provenance[BitIdx] !=B->Provenance[BitIdx])
3903return Result = std::nullopt;
3904
3905if (A->Provenance[BitIdx] == BitPart::Unset)
3906 Result->Provenance[BitIdx] =B->Provenance[BitIdx];
3907else
3908 Result->Provenance[BitIdx] =A->Provenance[BitIdx];
3909 }
3910
3911return Result;
3912 }
3913
3914// If this is a logical shift by a constant, recurse then shift the result.
3915if (match(V,m_LogicalShift(m_Value(X),m_APInt(C)))) {
3916constAPInt &BitShift = *C;
3917
3918// Ensure the shift amount is defined.
3919if (BitShift.uge(BitWidth))
3920return Result;
3921
3922// For bswap-only, limit shift amounts to whole bytes, for an early exit.
3923if (!MatchBitReversals && (BitShift.getZExtValue() % 8) != 0)
3924return Result;
3925
3926constauto &Res =collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3927Depth + 1, FoundRoot);
3928if (!Res)
3929return Result;
3930 Result = Res;
3931
3932// Perform the "shift" on BitProvenance.
3933auto &P = Result->Provenance;
3934if (I->getOpcode() == Instruction::Shl) {
3935P.erase(std::prev(P.end(), BitShift.getZExtValue()),P.end());
3936P.insert(P.begin(), BitShift.getZExtValue(), BitPart::Unset);
3937 }else {
3938P.erase(P.begin(), std::next(P.begin(), BitShift.getZExtValue()));
3939P.insert(P.end(), BitShift.getZExtValue(), BitPart::Unset);
3940 }
3941
3942return Result;
3943 }
3944
3945// If this is a logical 'and' with a mask that clears bits, recurse then
3946// unset the appropriate bits.
3947if (match(V,m_And(m_Value(X),m_APInt(C)))) {
3948constAPInt &AndMask = *C;
3949
3950// Check that the mask allows a multiple of 8 bits for a bswap, for an
3951// early exit.
3952unsigned NumMaskedBits = AndMask.popcount();
3953if (!MatchBitReversals && (NumMaskedBits % 8) != 0)
3954return Result;
3955
3956constauto &Res =collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3957Depth + 1, FoundRoot);
3958if (!Res)
3959return Result;
3960 Result = Res;
3961
3962for (unsigned BitIdx = 0; BitIdx <BitWidth; ++BitIdx)
3963// If the AndMask is zero for this bit, clear the bit.
3964if (AndMask[BitIdx] == 0)
3965 Result->Provenance[BitIdx] = BitPart::Unset;
3966return Result;
3967 }
3968
3969// If this is a zext instruction zero extend the result.
3970if (match(V,m_ZExt(m_Value(X)))) {
3971constauto &Res =collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3972Depth + 1, FoundRoot);
3973if (!Res)
3974return Result;
3975
3976 Result = BitPart(Res->Provider,BitWidth);
3977auto NarrowBitWidth =X->getType()->getScalarSizeInBits();
3978for (unsigned BitIdx = 0; BitIdx < NarrowBitWidth; ++BitIdx)
3979 Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3980for (unsigned BitIdx = NarrowBitWidth; BitIdx <BitWidth; ++BitIdx)
3981 Result->Provenance[BitIdx] = BitPart::Unset;
3982return Result;
3983 }
3984
3985// If this is a truncate instruction, extract the lower bits.
3986if (match(V,m_Trunc(m_Value(X)))) {
3987constauto &Res =collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3988Depth + 1, FoundRoot);
3989if (!Res)
3990return Result;
3991
3992 Result = BitPart(Res->Provider,BitWidth);
3993for (unsigned BitIdx = 0; BitIdx <BitWidth; ++BitIdx)
3994 Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3995return Result;
3996 }
3997
3998// BITREVERSE - most likely due to us previous matching a partial
3999// bitreverse.
4000if (match(V,m_BitReverse(m_Value(X)))) {
4001constauto &Res =collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
4002Depth + 1, FoundRoot);
4003if (!Res)
4004return Result;
4005
4006 Result = BitPart(Res->Provider,BitWidth);
4007for (unsigned BitIdx = 0; BitIdx <BitWidth; ++BitIdx)
4008 Result->Provenance[(BitWidth - 1) - BitIdx] = Res->Provenance[BitIdx];
4009return Result;
4010 }
4011
4012// BSWAP - most likely due to us previous matching a partial bswap.
4013if (match(V,m_BSwap(m_Value(X)))) {
4014constauto &Res =collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
4015Depth + 1, FoundRoot);
4016if (!Res)
4017return Result;
4018
4019unsigned ByteWidth =BitWidth / 8;
4020 Result = BitPart(Res->Provider,BitWidth);
4021for (unsigned ByteIdx = 0; ByteIdx < ByteWidth; ++ByteIdx) {
4022unsigned ByteBitOfs = ByteIdx * 8;
4023for (unsigned BitIdx = 0; BitIdx < 8; ++BitIdx)
4024 Result->Provenance[(BitWidth - 8 - ByteBitOfs) + BitIdx] =
4025 Res->Provenance[ByteBitOfs + BitIdx];
4026 }
4027return Result;
4028 }
4029
4030// Funnel 'double' shifts take 3 operands, 2 inputs and the shift
4031// amount (modulo).
4032// fshl(X,Y,Z): (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
4033// fshr(X,Y,Z): (X << (BW - (Z % BW))) | (Y >> (Z % BW))
4034if (match(V,m_FShl(m_Value(X),m_Value(Y),m_APInt(C))) ||
4035match(V,m_FShr(m_Value(X),m_Value(Y),m_APInt(C)))) {
4036// We can treat fshr as a fshl by flipping the modulo amount.
4037unsigned ModAmt =C->urem(BitWidth);
4038if (cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::fshr)
4039 ModAmt =BitWidth - ModAmt;
4040
4041// For bswap-only, limit shift amounts to whole bytes, for an early exit.
4042if (!MatchBitReversals && (ModAmt % 8) != 0)
4043return Result;
4044
4045// Check we have both sources and they are from the same provider.
4046constauto &LHS =collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
4047Depth + 1, FoundRoot);
4048if (!LHS || !LHS->Provider)
4049return Result;
4050
4051constauto &RHS =collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS,
4052Depth + 1, FoundRoot);
4053if (!RHS ||LHS->Provider !=RHS->Provider)
4054return Result;
4055
4056unsigned StartBitRHS =BitWidth - ModAmt;
4057 Result = BitPart(LHS->Provider,BitWidth);
4058for (unsigned BitIdx = 0; BitIdx < StartBitRHS; ++BitIdx)
4059 Result->Provenance[BitIdx + ModAmt] =LHS->Provenance[BitIdx];
4060for (unsigned BitIdx = 0; BitIdx < ModAmt; ++BitIdx)
4061 Result->Provenance[BitIdx] =RHS->Provenance[BitIdx + StartBitRHS];
4062return Result;
4063 }
4064 }
4065
4066// If we've already found a root input value then we're never going to merge
4067// these back together.
4068if (FoundRoot)
4069return Result;
4070
4071// Okay, we got to something that isn't a shift, 'or', 'and', etc. This must
4072// be the root input value to the bswap/bitreverse.
4073 FoundRoot =true;
4074 Result = BitPart(V,BitWidth);
4075for (unsigned BitIdx = 0; BitIdx <BitWidth; ++BitIdx)
4076 Result->Provenance[BitIdx] = BitIdx;
4077return Result;
4078}
4079
4080staticboolbitTransformIsCorrectForBSwap(unsignedFrom,unsigned To,
4081unsignedBitWidth) {
4082if (From % 8 != To % 8)
4083returnfalse;
4084// Convert from bit indices to byte indices and check for a byte reversal.
4085From >>= 3;
4086 To >>= 3;
4087BitWidth >>= 3;
4088returnFrom ==BitWidth - To - 1;
4089}
4090
4091staticboolbitTransformIsCorrectForBitReverse(unsignedFrom,unsigned To,
4092unsignedBitWidth) {
4093returnFrom ==BitWidth - To - 1;
4094}
4095
4096boolllvm::recognizeBSwapOrBitReverseIdiom(
4097Instruction *I,bool MatchBSwaps,bool MatchBitReversals,
4098SmallVectorImpl<Instruction *> &InsertedInsts) {
4099if (!match(I,m_Or(m_Value(),m_Value())) &&
4100 !match(I,m_FShl(m_Value(),m_Value(),m_Value())) &&
4101 !match(I,m_FShr(m_Value(),m_Value(),m_Value())) &&
4102 !match(I,m_BSwap(m_Value())))
4103returnfalse;
4104if (!MatchBSwaps && !MatchBitReversals)
4105returnfalse;
4106Type *ITy =I->getType();
4107if (!ITy->isIntOrIntVectorTy() || ITy->getScalarSizeInBits() > 128)
4108returnfalse;// Can't do integer/elements > 128 bits.
4109
4110// Try to find all the pieces corresponding to the bswap.
4111bool FoundRoot =false;
4112 std::map<Value *, std::optional<BitPart>> BPS;
4113constauto &Res =
4114collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0, FoundRoot);
4115if (!Res)
4116returnfalse;
4117ArrayRef<int8_t> BitProvenance = Res->Provenance;
4118assert(all_of(BitProvenance,
4119 [](int8_tI) {returnI == BitPart::Unset || 0 <=I; }) &&
4120"Illegal bit provenance index");
4121
4122// If the upper bits are zero, then attempt to perform as a truncated op.
4123Type *DemandedTy = ITy;
4124if (BitProvenance.back() == BitPart::Unset) {
4125while (!BitProvenance.empty() && BitProvenance.back() == BitPart::Unset)
4126 BitProvenance = BitProvenance.drop_back();
4127if (BitProvenance.empty())
4128returnfalse;// TODO - handle null value?
4129 DemandedTy =Type::getIntNTy(I->getContext(), BitProvenance.size());
4130if (auto *IVecTy = dyn_cast<VectorType>(ITy))
4131 DemandedTy = VectorType::get(DemandedTy, IVecTy);
4132 }
4133
4134// Check BitProvenance hasn't found a source larger than the result type.
4135unsigned DemandedBW = DemandedTy->getScalarSizeInBits();
4136if (DemandedBW > ITy->getScalarSizeInBits())
4137returnfalse;
4138
4139// Now, is the bit permutation correct for a bswap or a bitreverse? We can
4140// only byteswap values with an even number of bytes.
4141APInt DemandedMask =APInt::getAllOnes(DemandedBW);
4142bool OKForBSwap = MatchBSwaps && (DemandedBW % 16) == 0;
4143bool OKForBitReverse = MatchBitReversals;
4144for (unsigned BitIdx = 0;
4145 (BitIdx < DemandedBW) && (OKForBSwap || OKForBitReverse); ++BitIdx) {
4146if (BitProvenance[BitIdx] == BitPart::Unset) {
4147 DemandedMask.clearBit(BitIdx);
4148continue;
4149 }
4150 OKForBSwap &=bitTransformIsCorrectForBSwap(BitProvenance[BitIdx], BitIdx,
4151 DemandedBW);
4152 OKForBitReverse &=bitTransformIsCorrectForBitReverse(BitProvenance[BitIdx],
4153 BitIdx, DemandedBW);
4154 }
4155
4156Intrinsic::ID Intrin;
4157if (OKForBSwap)
4158 Intrin = Intrinsic::bswap;
4159elseif (OKForBitReverse)
4160 Intrin = Intrinsic::bitreverse;
4161else
4162returnfalse;
4163
4164Function *F =
4165Intrinsic::getOrInsertDeclaration(I->getModule(), Intrin, DemandedTy);
4166Value *Provider = Res->Provider;
4167
4168// We may need to truncate the provider.
4169if (DemandedTy != Provider->getType()) {
4170auto *Trunc =
4171CastInst::CreateIntegerCast(Provider, DemandedTy,false,"trunc",I->getIterator());
4172 InsertedInsts.push_back(Trunc);
4173 Provider = Trunc;
4174 }
4175
4176Instruction *Result =CallInst::Create(F, Provider,"rev",I->getIterator());
4177 InsertedInsts.push_back(Result);
4178
4179if (!DemandedMask.isAllOnes()) {
4180auto *Mask = ConstantInt::get(DemandedTy, DemandedMask);
4181 Result =BinaryOperator::Create(Instruction::And, Result, Mask,"mask",I->getIterator());
4182 InsertedInsts.push_back(Result);
4183 }
4184
4185// We may need to zeroextend back to the result type.
4186if (ITy != Result->getType()) {
4187auto *ExtInst =CastInst::CreateIntegerCast(Result, ITy,false,"zext",I->getIterator());
4188 InsertedInsts.push_back(ExtInst);
4189 }
4190
4191returntrue;
4192}
4193
4194// CodeGen has special handling for some string functions that may replace
4195// them with target-specific intrinsics. Since that'd skip our interceptors
4196// in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
4197// we mark affected calls as NoBuiltin, which will disable optimization
4198// in CodeGen.
4199voidllvm::maybeMarkSanitizerLibraryCallNoBuiltin(
4200CallInst *CI,constTargetLibraryInfo *TLI) {
4201Function *F = CI->getCalledFunction();
4202LibFunc Func;
4203if (F && !F->hasLocalLinkage() &&F->hasName() &&
4204 TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
4205 !F->doesNotAccessMemory())
4206 CI->addFnAttr(Attribute::NoBuiltin);
4207}
4208
4209boolllvm::canReplaceOperandWithVariable(constInstruction *I,unsigned OpIdx) {
4210// We can't have a PHI with a metadata type.
4211if (I->getOperand(OpIdx)->getType()->isMetadataTy())
4212returnfalse;
4213
4214// Early exit.
4215if (!isa<Constant>(I->getOperand(OpIdx)))
4216returntrue;
4217
4218switch (I->getOpcode()) {
4219default:
4220returntrue;
4221case Instruction::Call:
4222case Instruction::Invoke: {
4223constauto &CB = cast<CallBase>(*I);
4224
4225// Can't handle inline asm. Skip it.
4226if (CB.isInlineAsm())
4227returnfalse;
4228
4229// Constant bundle operands may need to retain their constant-ness for
4230// correctness.
4231if (CB.isBundleOperand(OpIdx))
4232returnfalse;
4233
4234if (OpIdx < CB.arg_size()) {
4235// Some variadic intrinsics require constants in the variadic arguments,
4236// which currently aren't markable as immarg.
4237if (isa<IntrinsicInst>(CB) &&
4238 OpIdx >= CB.getFunctionType()->getNumParams()) {
4239// This is known to be OK for stackmap.
4240return CB.getIntrinsicID() == Intrinsic::experimental_stackmap;
4241 }
4242
4243// gcroot is a special case, since it requires a constant argument which
4244// isn't also required to be a simple ConstantInt.
4245if (CB.getIntrinsicID() == Intrinsic::gcroot)
4246returnfalse;
4247
4248// Some intrinsic operands are required to be immediates.
4249return !CB.paramHasAttr(OpIdx, Attribute::ImmArg);
4250 }
4251
4252// It is never allowed to replace the call argument to an intrinsic, but it
4253// may be possible for a call.
4254return !isa<IntrinsicInst>(CB);
4255 }
4256case Instruction::ShuffleVector:
4257// Shufflevector masks are constant.
4258return OpIdx != 2;
4259case Instruction::Switch:
4260case Instruction::ExtractValue:
4261// All operands apart from the first are constant.
4262return OpIdx == 0;
4263case Instruction::InsertValue:
4264// All operands apart from the first and the second are constant.
4265return OpIdx < 2;
4266case Instruction::Alloca:
4267// Static allocas (constant size in the entry block) are handled by
4268// prologue/epilogue insertion so they're free anyway. We definitely don't
4269// want to make them non-constant.
4270return !cast<AllocaInst>(I)->isStaticAlloca();
4271case Instruction::GetElementPtr:
4272if (OpIdx == 0)
4273returntrue;
4274gep_type_iterator It =gep_type_begin(I);
4275for (auto E = std::next(It, OpIdx); It != E; ++It)
4276if (It.isStruct())
4277returnfalse;
4278returntrue;
4279 }
4280}
4281
4282Value *llvm::invertCondition(Value *Condition) {
4283// First: Check if it's a constant
4284if (Constant *C = dyn_cast<Constant>(Condition))
4285returnConstantExpr::getNot(C);
4286
4287// Second: If the condition is already inverted, return the original value
4288Value *NotCondition;
4289if (match(Condition,m_Not(m_Value(NotCondition))))
4290return NotCondition;
4291
4292BasicBlock *Parent =nullptr;
4293Instruction *Inst = dyn_cast<Instruction>(Condition);
4294if (Inst)
4295 Parent = Inst->getParent();
4296elseif (Argument *Arg = dyn_cast<Argument>(Condition))
4297 Parent = &Arg->getParent()->getEntryBlock();
4298assert(Parent &&"Unsupported condition to invert");
4299
4300// Third: Check all the users for an invert
4301for (User *U : Condition->users())
4302if (Instruction *I = dyn_cast<Instruction>(U))
4303if (I->getParent() == Parent &&match(I,m_Not(m_Specific(Condition))))
4304returnI;
4305
4306// Last option: Create a new instruction
4307auto *Inverted =
4308BinaryOperator::CreateNot(Condition, Condition->getName() +".inv");
4309if (Inst && !isa<PHINode>(Inst))
4310 Inverted->insertAfter(Inst->getIterator());
4311else
4312 Inverted->insertBefore(Parent->getFirstInsertionPt());
4313return Inverted;
4314}
4315
4316boolllvm::inferAttributesFromOthers(Function &F) {
4317// Note: We explicitly check for attributes rather than using cover functions
4318// because some of the cover functions include the logic being implemented.
4319
4320bool Changed =false;
4321// readnone + not convergent implies nosync
4322if (!F.hasFnAttribute(Attribute::NoSync) &&
4323F.doesNotAccessMemory() && !F.isConvergent()) {
4324F.setNoSync();
4325 Changed =true;
4326 }
4327
4328// readonly implies nofree
4329if (!F.hasFnAttribute(Attribute::NoFree) &&F.onlyReadsMemory()) {
4330F.setDoesNotFreeMemory();
4331 Changed =true;
4332 }
4333
4334// willreturn implies mustprogress
4335if (!F.hasFnAttribute(Attribute::MustProgress) &&F.willReturn()) {
4336F.setMustProgress();
4337 Changed =true;
4338 }
4339
4340// TODO: There are a bunch of cases of restrictive memory effects we
4341// can infer by inspecting arguments of argmemonly-ish functions.
4342
4343return Changed;
4344}
Success
#define Success
Definition:AArch64Disassembler.cpp:220
for
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
Definition:AArch64ExpandPseudoInsts.cpp:115
SelectTypeKind::FP
@ FP
getIntrinsicID
static unsigned getIntrinsicID(const SDNode *N)
Definition:AArch64ISelLowering.cpp:7713
PHI
Rewrite undef for PHI
Definition:AMDGPURewriteUndefForPHI.cpp:100
APInt.h
This file implements a class to represent arbitrary precision integral constant values and operations...
ToRemove
ReachingDefAnalysis InstSet & ToRemove
Definition:ARMLowOverheadLoops.cpp:531
DL
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Definition:ARMSLSHardening.cpp:73
AssumeBundleQueries.h
isEqual
static bool isEqual(const Function &Caller, const Function &Callee)
Definition:Attributes.cpp:2469
Attributes.h
This file contains the simple types necessary to represent the attributes associated with functions a...
getParent
static const Function * getParent(const Value *V)
Definition:BasicAliasAnalysis.cpp:863
BasicBlockUtils.h
From
BlockVerifier::State From
Definition:BlockVerifier.cpp:57
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
A
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Casting.h
CommandLine.h
ConstantFolding.h
ConstantRange.h
Constants.h
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DIBuilder.h
isSentinel
static bool isSentinel(const DWARFDebugNames::AttributeEncoding &AE)
Definition:DWARFAcceleratorTable.cpp:491
DataLayout.h
Idx
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Definition:DeadArgumentElimination.cpp:353
DebugInfoMetadata.h
DebugLoc.h
Debug.h
LLVM_DEBUG
#define LLVM_DEBUG(...)
Definition:Debug.h:106
DenseMapInfo.h
This file defines DenseMapInfo traits for DenseMap.
DenseMap.h
This file defines the DenseMap class.
DenseSet.h
This file defines the DenseSet and SmallDenseSet classes.
DerivedTypes.h
DomTreeUpdater.h
Dominators.h
Dwarf.h
This file contains constants used for implementing Dwarf debug support.
EHPersonalities.h
End
bool End
Definition:ELF_riscv.cpp:480
getHashValueImpl
static unsigned getHashValueImpl(SimpleValue Val)
Definition:EarlyCSE.cpp:235
isEqualImpl
static bool isEqualImpl(SimpleValue LHS, SimpleValue RHS)
Definition:EarlyCSE.cpp:358
X
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
GetElementPtrTypeIterator.h
GlobalObject.h
Hashing.h
GEP
Hexagon Common GEP
Definition:HexagonCommonGEP.cpp:170
IRBuilder.h
Argument.h
BasicBlock.h
CFG.h
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Constant.h
Function.h
Instruction.h
IntrinsicInst.h
Module.h
Module.h This file contains the declarations for the Module class.
Type.h
Use.h
This defines the Use class.
User.h
Value.h
Users
iv Induction Variable Users
Definition:IVUsers.cpp:48
InstrTypes.h
InstructionSimplify.h
Instructions.h
Intrinsics.h
KnownBits.h
LLVMContext.h
F
#define F(x, y, z)
Definition:MD5.cpp:55
I
#define I(x, y, z)
Definition:MD5.cpp:58
MDBuilder.h
MemoryBuiltins.h
MemoryModelRelaxationAnnotations.h
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
MemorySSAUpdater.h
Metadata.h
This file contains the declarations for metadata subclasses.
Signed
@ Signed
Definition:NVPTXISelLowering.cpp:4789
II
uint64_t IntrinsicInst * II
Definition:NVVMIntrRange.cpp:51
Y
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
P
#define P(N)
PatternMatch.h
ProfDataUtils.h
This file contains the declarations for profiling metadata utility functions.
Cond
const SmallVectorImpl< MachineOperand > & Cond
Definition:RISCVRedundantCopyElimination.cpp:75
Uses
Remove Loads Into Fake Uses
Definition:RemoveLoadsIntoFakeUses.cpp:74
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Address
@ Address
Definition:SPIRVEmitNonSemanticDI.cpp:68
STLExtras.h
This file contains some templates that are useful if you are working with the STL at all.
SetVector.h
This file implements a set that has insertion order iteration characteristics.
SmallPtrSet.h
This file defines the SmallPtrSet class.
SmallVector.h
This file defines the SmallVector class.
Statistic.h
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
STATISTIC
#define STATISTIC(VARNAME, DESC)
Definition:Statistic.h:166
Ptr
@ Ptr
Definition:TargetLibraryInfo.cpp:77
TargetLibraryInfo.h
markAliveBlocks
static bool markAliveBlocks(Function &F, SmallPtrSetImpl< BasicBlock * > &Reachable, DomTreeUpdater *DTU=nullptr)
Definition:Local.cpp:3038
valueCoversEntireFragment
static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII)
Check if the alloc size of ValTy is large enough to cover the variable (or fragment of the variable) ...
Definition:Local.cpp:1641
isBitCastSemanticsPreserving
static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy, Type *ToTy)
Check if a bitcast between a value of type FromTy to type ToTy would losslessly preserve the bits and...
Definition:Local.cpp:2769
isStructure
static bool isStructure(AllocaInst *AI)
Determine whether this alloca is a structure.
Definition:Local.cpp:1953
getDwarfOpForBinOp
uint64_t getDwarfOpForBinOp(Instruction::BinaryOps Opcode)
Definition:Local.cpp:2487
PhiHasDebugValue
static bool PhiHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr, PHINode *APN)
===------------------------------------------------------------------—===// Dbg Intrinsic utilities
Definition:Local.cpp:1611
gatherIncomingValuesToPhi
static void gatherIncomingValuesToPhi(PHINode *PN, IncomingValueMap &IncomingValues)
Create a map from block to value for the operands of a given phi.
Definition:Local.cpp:967
combineMetadata
static void combineMetadata(Instruction *K, const Instruction *J, bool DoesKMove, bool AAOnly=false)
If AAOnly is set, only intersect alias analysis metadata and preserve other known metadata.
Definition:Local.cpp:3313
handleSSAValueOperands
static void handleSSAValueOperands(uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Opcodes, SmallVectorImpl< Value * > &AdditionalValues, Instruction *I)
Definition:Local.cpp:2517
DbgValReplacement
std::optional< DIExpression * > DbgValReplacement
A replacement for a dbg.value expression.
Definition:Local.cpp:2666
insertDbgValueOrDbgVariableRecordAfter
static void insertDbgValueOrDbgVariableRecordAfter(DIBuilder &Builder, Value *DV, DILocalVariable *DIVar, DIExpression *DIExpr, const DebugLoc &NewLoc, BasicBlock::iterator Instr)
Definition:Local.cpp:1712
getSalvageOpsForBinOp
Value * getSalvageOpsForBinOp(BinaryOperator *BI, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Opcodes, SmallVectorImpl< Value * > &AdditionalValues)
Definition:Local.cpp:2529
dropInitialDeref
static DIExpression * dropInitialDeref(const DIExpression *DIExpr)
Definition:Local.cpp:1774
replaceUndefValuesInPhi
static void replaceUndefValuesInPhi(PHINode *PN, const IncomingValueMap &IncomingValues)
Replace the incoming undef values to a phi with the values from a block-to-value map.
Definition:Local.cpp:983
getSalvageOpsForGEP
Value * getSalvageOpsForGEP(GetElementPtrInst *GEP, const DataLayout &DL, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Opcodes, SmallVectorImpl< Value * > &AdditionalValues)
Definition:Local.cpp:2461
CanRedirectPredsOfEmptyBBToSucc
static bool CanRedirectPredsOfEmptyBBToSucc(BasicBlock *BB, BasicBlock *Succ, const SmallPtrSetImpl< BasicBlock * > &BBPreds, BasicBlock *&CommonPred)
Definition:Local.cpp:1024
getSalvageOpsForIcmpOp
Value * getSalvageOpsForIcmpOp(ICmpInst *Icmp, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Opcodes, SmallVectorImpl< Value * > &AdditionalValues)
Definition:Local.cpp:2588
CanMergeValues
static bool CanMergeValues(Value *First, Value *Second)
Return true if we can choose one of these values to use in place of the other.
Definition:Local.cpp:862
simplifyAndDCEInstruction
static bool simplifyAndDCEInstruction(Instruction *I, SmallSetVector< Instruction *, 16 > &WorkList, const DataLayout &DL, const TargetLibraryInfo *TLI)
Definition:Local.cpp:679
isArray
static bool isArray(AllocaInst *AI)
Determine whether this alloca is either a VLA or an array.
Definition:Local.cpp:1947
areAllUsesEqual
static bool areAllUsesEqual(Instruction *I)
areAllUsesEqual - Check whether the uses of a value are all the same.
Definition:Local.cpp:638
PHICSEDebugHash
static cl::opt< bool > PHICSEDebugHash("phicse-debug-hash", cl::init(false), cl::Hidden, cl::desc("Perform extra assertion checking to verify that PHINodes's hash " "function is well-behaved w.r.t. its isEqual predicate"))
replaceDominatedUsesWith
static unsigned replaceDominatedUsesWith(Value *From, Value *To, const RootType &Root, const ShouldReplaceFn &ShouldReplace)
Definition:Local.cpp:3544
getDwarfOpForIcmpPred
uint64_t getDwarfOpForIcmpPred(CmpInst::Predicate Pred)
Definition:Local.cpp:2563
bitTransformIsCorrectForBSwap
static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To, unsigned BitWidth)
Definition:Local.cpp:4080
collectBitParts
static const std::optional< BitPart > & collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals, std::map< Value *, std::optional< BitPart > > &BPS, int Depth, bool &FoundRoot)
Analyze the specified subexpression and see if it is capable of providing pieces of a bswap or bitrev...
Definition:Local.cpp:3860
EliminateDuplicatePHINodesNaiveImpl
static bool EliminateDuplicatePHINodesNaiveImpl(BasicBlock *BB, SmallPtrSetImpl< PHINode * > &ToRemove)
Definition:Local.cpp:1392
CanPropagatePredecessorsForPHIs
static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ, const SmallPtrSetImpl< BasicBlock * > &BBPreds)
Return true if we can fold BB, an almost-empty BB ending in an unconditional branch to Succ,...
Definition:Local.cpp:871
PHICSENumPHISmallSize
static cl::opt< unsigned > PHICSENumPHISmallSize("phicse-num-phi-smallsize", cl::init(32), cl::Hidden, cl::desc("When the basic block contains not more than this number of PHI nodes, " "perform a (faster!) exhaustive search instead of set-driven one."))
EliminateDuplicatePHINodesSetBasedImpl
static bool EliminateDuplicatePHINodesSetBasedImpl(BasicBlock *BB, SmallPtrSetImpl< PHINode * > &ToRemove)
Definition:Local.cpp:1428
rewriteDebugUsers
static bool rewriteDebugUsers(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT, function_ref< DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr, function_ref< DbgValReplacement(DbgVariableRecord &DVR)> RewriteDVRExpr)
Point debug users of From to To using exprs given by RewriteExpr, possibly moving/undefing users to p...
Definition:Local.cpp:2671
insertDbgValueOrDbgVariableRecord
static void insertDbgValueOrDbgVariableRecord(DIBuilder &Builder, Value *DV, DILocalVariable *DIVar, DIExpression *DIExpr, const DebugLoc &NewLoc, BasicBlock::iterator Instr)
Definition:Local.cpp:1693
introduceTooManyPhiEntries
static bool introduceTooManyPhiEntries(BasicBlock *BB, BasicBlock *Succ)
Check whether removing BB will make the phis in its Succ have too many incoming entries.
Definition:Local.cpp:1057
selectIncomingValueForBlock
static Value * selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB, IncomingValueMap &IncomingValues)
Determines the value to use as the phi node input for a block.
Definition:Local.cpp:942
updateOneDbgValueForAlloca
static void updateOneDbgValueForAlloca(const DebugLoc &Loc, DILocalVariable *DIVar, DIExpression *DIExpr, Value *NewAddress, DbgValueInst *DVI, DbgVariableRecord *DVR, DIBuilder &Builder, int Offset)
Definition:Local.cpp:2224
insertDbgVariableRecordsForPHIs
static void insertDbgVariableRecordsForPHIs(BasicBlock *BB, SmallVectorImpl< PHINode * > &InsertedPHIs)
Definition:Local.cpp:2078
BitPartRecursionMaxDepth
static const unsigned BitPartRecursionMaxDepth
Definition:Local.cpp:123
redirectValuesFromPredecessorsToPhi
static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB, const PredBlockVector &BBPreds, PHINode *PN, BasicBlock *CommonPred)
Replace a value flowing from a block to a phi with potentially multiple instances of that value flowi...
Definition:Local.cpp:1089
MaxPhiEntriesIncreaseAfterRemovingEmptyBlock
static cl::opt< unsigned > MaxPhiEntriesIncreaseAfterRemovingEmptyBlock("max-phi-entries-increase-after-removing-empty-block", cl::init(1000), cl::Hidden, cl::desc("Stop removing an empty block if removing it will introduce more " "than this number of phi entries in its successor"))
UseNewDbgInfoFormat
cl::opt< bool > UseNewDbgInfoFormat
bitTransformIsCorrectForBitReverse
static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To, unsigned BitWidth)
Definition:Local.cpp:4091
salvageDbgAssignAddress
static void salvageDbgAssignAddress(T *Assign)
Definition:Local.cpp:2281
Local.h
ValueHandle.h
ValueMapper.h
ValueTracking.h
VectorUtils.h
RHS
Value * RHS
Definition:X86PartialReduction.cpp:74
LHS
Value * LHS
Definition:X86PartialReduction.cpp:73
T
llvm::APFloat
Definition:APFloat.h:904
llvm::APFloat::bitcastToAPInt
APInt bitcastToAPInt() const
Definition:APFloat.h:1351
llvm::APInt
Class for arbitrary precision integers.
Definition:APInt.h:78
llvm::APInt::getAllOnes
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition:APInt.h:234
llvm::APInt::clearBit
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition:APInt.h:1407
llvm::APInt::getZExtValue
uint64_t getZExtValue() const
Get zero extended value.
Definition:APInt.h:1520
llvm::APInt::popcount
unsigned popcount() const
Count the number of bits set.
Definition:APInt.h:1649
llvm::APInt::isAllOnes
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition:APInt.h:371
llvm::APInt::getRawData
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition:APInt.h:569
llvm::APInt::trySExtValue
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
Definition:APInt.h:1554
llvm::APInt::getSExtValue
int64_t getSExtValue() const
Get sign extended value.
Definition:APInt.h:1542
llvm::APInt::uge
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition:APInt.h:1221
llvm::AllocaInst
an instruction to allocate memory on the stack
Definition:Instructions.h:63
llvm::AllocaInst::getAllocatedType
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition:Instructions.h:117
llvm::AllocaInst::isArrayAllocation
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
Definition:Instructions.cpp:1225
llvm::Argument
This class represents an incoming formal argument to a Function.
Definition:Argument.h:31
llvm::ArrayRef
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition:ArrayRef.h:41
llvm::ArrayRef::back
const T & back() const
back - Get the last element.
Definition:ArrayRef.h:177
llvm::ArrayRef::drop_front
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition:ArrayRef.h:207
llvm::ArrayRef::size
size_t size() const
size - Get the array size.
Definition:ArrayRef.h:168
llvm::ArrayRef::drop_back
ArrayRef< T > drop_back(size_t N=1) const
Drop the last N elements of the array.
Definition:ArrayRef.h:213
llvm::ArrayRef::empty
bool empty() const
empty - Check if the array is empty.
Definition:ArrayRef.h:163
llvm::AssertingVH
Value handle that asserts if the Value is deleted.
Definition:ValueHandle.h:264
llvm::AssumptionCache
A cache of @llvm.assume calls within a function.
Definition:AssumptionCache.h:42
llvm::BasicBlockEdge
Definition:Dominators.h:94
llvm::BasicBlock
LLVM Basic Block Representation.
Definition:BasicBlock.h:61
llvm::BasicBlock::end
iterator end()
Definition:BasicBlock.h:464
llvm::BasicBlock::begin
iterator begin()
Instruction iterator methods.
Definition:BasicBlock.h:451
llvm::BasicBlock::phis
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition:BasicBlock.h:520
llvm::BasicBlock::getFirstInsertionPt
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition:BasicBlock.cpp:426
llvm::BasicBlock::hasAddressTaken
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition:BasicBlock.h:661
llvm::BasicBlock::getFirstNonPHIIt
InstListType::const_iterator getFirstNonPHIIt() const
Iterator returning form of getFirstNonPHI.
Definition:BasicBlock.cpp:374
llvm::BasicBlock::insertDbgRecordBefore
void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
Definition:BasicBlock.cpp:1078
llvm::BasicBlock::front
const Instruction & front() const
Definition:BasicBlock.h:474
llvm::BasicBlock::Create
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition:BasicBlock.h:213
llvm::BasicBlock::isEntryBlock
bool isEntryBlock() const
Return true if this is the entry block of the containing function.
Definition:BasicBlock.cpp:583
llvm::BasicBlock::moveAfter
void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
Definition:BasicBlock.cpp:287
llvm::BasicBlock::getFirstNonPHIOrDbg
InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
Definition:BasicBlock.cpp:387
llvm::BasicBlock::hasNPredecessors
bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
Definition:BasicBlock.cpp:493
llvm::BasicBlock::getSinglePredecessor
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition:BasicBlock.cpp:471
llvm::BasicBlock::flushTerminatorDbgRecords
void flushTerminatorDbgRecords()
Eject any debug-info trailing at the end of a block.
Definition:BasicBlock.cpp:729
llvm::BasicBlock::getParent
const Function * getParent() const
Return the enclosing method, or null if none.
Definition:BasicBlock.h:220
llvm::BasicBlock::getDataLayout
const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
Definition:BasicBlock.cpp:296
llvm::BasicBlock::eraseFromParent
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
Definition:BasicBlock.cpp:279
llvm::BasicBlock::iterator
InstListType::iterator iterator
Instruction iterators...
Definition:BasicBlock.h:177
llvm::BasicBlock::getContext
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition:BasicBlock.cpp:168
llvm::BasicBlock::size
size_t size() const
Definition:BasicBlock.h:472
llvm::BasicBlock::getTerminator
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition:BasicBlock.h:240
llvm::BasicBlock::hasNPredecessorsOrMore
bool hasNPredecessorsOrMore(unsigned N) const
Return true if this block has N predecessors or more.
Definition:BasicBlock.cpp:497
llvm::BasicBlock::splice
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition:BasicBlock.h:634
llvm::BasicBlock::back
const Instruction & back() const
Definition:BasicBlock.h:476
llvm::BasicBlock::removePredecessor
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
Definition:BasicBlock.cpp:528
llvm::BinaryOperator
Definition:InstrTypes.h:170
llvm::BinaryOperator::getOpcode
BinaryOps getOpcode() const
Definition:InstrTypes.h:370
llvm::BinaryOperator::CreateNot
static BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition:Instructions.cpp:2660
llvm::BinaryOperator::Create
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Definition:Instructions.cpp:2639
llvm::BitCastInst
This class represents a no-op cast from one type to another.
Definition:Instructions.h:4894
llvm::BlockAddress
The address of a basic block.
Definition:Constants.h:893
llvm::BlockAddress::get
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition:Constants.cpp:1897
llvm::BranchInst
Conditional or Unconditional Branch instruction.
Definition:Instructions.h:3016
llvm::BranchInst::Create
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
Definition:Instructions.h:3072
llvm::CallBase
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition:InstrTypes.h:1112
llvm::CallBase::setCallingConv
void setCallingConv(CallingConv::ID CC)
Definition:InstrTypes.h:1403
llvm::CallBase::addFnAttr
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
Definition:InstrTypes.h:1474
llvm::CallBase::getOperandBundlesAsDefs
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
Definition:Instructions.cpp:483
llvm::CallBase::getCalledFunction
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Definition:InstrTypes.h:1341
llvm::CallBase::getCallingConv
CallingConv::ID getCallingConv() const
Definition:InstrTypes.h:1399
llvm::CallBase::getCalledOperand
Value * getCalledOperand() const
Definition:InstrTypes.h:1334
llvm::CallBase::setAttributes
void setAttributes(AttributeList A)
Set the attributes for this call.
Definition:InstrTypes.h:1420
llvm::CallBase::getFunctionType
FunctionType * getFunctionType() const
Definition:InstrTypes.h:1199
llvm::CallBase::args
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
Definition:InstrTypes.h:1277
llvm::CallBase::getAttributes
AttributeList getAttributes() const
Return the attributes for this call.
Definition:InstrTypes.h:1417
llvm::CallInst
This class represents a function call, abstracting a target machine's calling convention.
Definition:Instructions.h:1479
llvm::CallInst::Create
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Definition:Instructions.h:1514
llvm::CastInst::CreateIntegerCast
static CastInst * CreateIntegerCast(Value *S, Type *Ty, bool isSigned, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt, BitCast, or Trunc for int -> int casts.
Definition:Instructions.cpp:3058
llvm::CatchPadInst
Definition:Instructions.h:4250
llvm::CatchSwitchInst::Create
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Definition:Instructions.h:4093
llvm::CleanupReturnInst::Create
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Definition:Instructions.h:4381
llvm::CmpInst::Predicate
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition:InstrTypes.h:673
llvm::CmpInst::ICMP_SLT
@ ICMP_SLT
signed less than
Definition:InstrTypes.h:702
llvm::CmpInst::ICMP_SLE
@ ICMP_SLE
signed less or equal
Definition:InstrTypes.h:703
llvm::CmpInst::ICMP_UGE
@ ICMP_UGE
unsigned greater or equal
Definition:InstrTypes.h:697
llvm::CmpInst::ICMP_UGT
@ ICMP_UGT
unsigned greater than
Definition:InstrTypes.h:696
llvm::CmpInst::ICMP_SGT
@ ICMP_SGT
signed greater than
Definition:InstrTypes.h:700
llvm::CmpInst::ICMP_ULT
@ ICMP_ULT
unsigned less than
Definition:InstrTypes.h:698
llvm::CmpInst::ICMP_EQ
@ ICMP_EQ
equal
Definition:InstrTypes.h:694
llvm::CmpInst::ICMP_NE
@ ICMP_NE
not equal
Definition:InstrTypes.h:695
llvm::CmpInst::ICMP_SGE
@ ICMP_SGE
signed greater or equal
Definition:InstrTypes.h:701
llvm::CmpInst::ICMP_ULE
@ ICMP_ULE
unsigned less or equal
Definition:InstrTypes.h:699
llvm::CmpInst::isSigned
bool isSigned() const
Definition:InstrTypes.h:928
llvm::CmpInst::getPredicate
Predicate getPredicate() const
Return the predicate for this instruction.
Definition:InstrTypes.h:763
llvm::ConstantExpr
A constant value that is initialized with an expression using other constant values.
Definition:Constants.h:1108
llvm::ConstantExpr::getIntToPtr
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition:Constants.cpp:2307
llvm::ConstantExpr::getNot
static Constant * getNot(Constant *C)
Definition:Constants.cpp:2632
llvm::ConstantExpr::getPtrToInt
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition:Constants.cpp:2293
llvm::ConstantExpr::getAdd
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition:Constants.cpp:2638
llvm::ConstantInt
This is the shared class of boolean and integer constants.
Definition:Constants.h:83
llvm::ConstantPointerNull::get
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition:Constants.cpp:1826
llvm::ConstantRange::contains
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
Definition:ConstantRange.cpp:507
llvm::Constant
This is an important base class in LLVM.
Definition:Constant.h:42
llvm::Constant::destroyConstant
void destroyConstant()
Called if some element of this constant is no longer valid.
Definition:Constants.cpp:489
llvm::DIBuilder
Definition:DIBuilder.h:45
llvm::DIBuilder::createConstantValueExpression
DIExpression * createConstantValueExpression(uint64_t Val)
Create an expression for a variable that does not have an address, but does have a constant value.
Definition:DIBuilder.h:789
llvm::DIExpression
DWARF expression.
Definition:DebugInfoMetadata.h:2763
llvm::DIExpression::append
static DIExpression * append(const DIExpression *Expr, ArrayRef< uint64_t > Ops)
Append the opcodes Ops to DIExpr.
Definition:DebugInfoMetadata.cpp:1948
llvm::DIExpression::getNumElements
unsigned getNumElements() const
Definition:DebugInfoMetadata.h:2789
llvm::DIExpression::getExtOps
static ExtOps getExtOps(unsigned FromSize, unsigned ToSize, bool Signed)
Returns the ops for a zero- or sign-extension in a DIExpression.
Definition:DebugInfoMetadata.cpp:2243
llvm::DIExpression::appendOffset
static void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
Definition:DebugInfoMetadata.cpp:1721
llvm::DIExpression::appendOpsToArg
static DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
Definition:DebugInfoMetadata.cpp:1858
llvm::DIExpression::getFragmentInfo
static std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
Definition:DebugInfoMetadata.cpp:1677
llvm::DIExpression::foldConstantMath
DIExpression * foldConstantMath()
Try to shorten an expression with constant math operations that can be evaluated at compile time.
Definition:DIExpressionOptimizer.cpp:288
llvm::DIExpression::getNumLocationOperands
uint64_t getNumLocationOperands() const
Return the number of unique location operands referred to (via DW_OP_LLVM_arg) in this expression; th...
Definition:DebugInfoMetadata.cpp:2206
llvm::DIExpression::getElements
ArrayRef< uint64_t > getElements() const
Definition:DebugInfoMetadata.h:2787
llvm::DIExpression::getActiveBits
std::optional< uint64_t > getActiveBits(DIVariable *Var)
Return the number of bits that have an active value, i.e.
Definition:DebugInfoMetadata.cpp:1686
llvm::DIExpression::getElement
uint64_t getElement(unsigned I) const
Definition:DebugInfoMetadata.h:2791
llvm::DIExpression::prepend
static DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
Definition:DebugInfoMetadata.cpp:1842
llvm::DIExpression::appendExt
static DIExpression * appendExt(const DIExpression *Expr, unsigned FromSize, unsigned ToSize, bool Signed)
Append a zero- or sign-extension to Expr.
Definition:DebugInfoMetadata.cpp:2251
llvm::DILocalVariable
Local variable.
Definition:DebugInfoMetadata.h:3460
llvm::DIVariable::getSignedness
std::optional< DIBasicType::Signedness > getSignedness() const
Return the signedness of this variable's type, or std::nullopt if this type is neither signed nor uns...
Definition:DebugInfoMetadata.h:2719
llvm::DWARFExpression::Operation
This class represents an Operation in the Expression.
Definition:DWARFExpression.h:32
llvm::DataLayout
A parsed version of the target data layout string in and methods for querying it.
Definition:DataLayout.h:63
llvm::DbgLabelInst
This represents the llvm.dbg.label instruction.
Definition:IntrinsicInst.h:543
llvm::DbgMarker::MarkedInstr
Instruction * MarkedInstr
Link back to the Instruction that owns this marker.
Definition:DebugProgramInstruction.h:588
llvm::DbgRecord::removeFromParent
void removeFromParent()
Definition:DebugProgramInstruction.cpp:674
llvm::DbgRecord::getModule
Module * getModule()
Definition:DebugProgramInstruction.cpp:523
llvm::DbgRecord::getMarker
DbgMarker * getMarker()
Definition:DebugProgramInstruction.h:171
llvm::DbgValueInst
This represents the llvm.dbg.value instruction.
Definition:IntrinsicInst.h:468
llvm::DbgVariableIntrinsic
This is the common base class for debug info intrinsics for variables.
Definition:IntrinsicInst.h:308
llvm::DbgVariableIntrinsic::location_ops
iterator_range< location_op_iterator > location_ops() const
Get the locations corresponding to the variable referenced by the debug info intrinsic.
Definition:IntrinsicInst.cpp:91
llvm::DbgVariableIntrinsic::replaceVariableLocationOp
void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
Definition:IntrinsicInst.cpp:121
llvm::DbgVariableIntrinsic::getVariableLocationOp
Value * getVariableLocationOp(unsigned OpIdx) const
Definition:IntrinsicInst.cpp:95
llvm::DbgVariableIntrinsic::setExpression
void setExpression(DIExpression *NewExpr)
Definition:IntrinsicInst.h:330
llvm::DbgVariableIntrinsic::getVariable
DILocalVariable * getVariable() const
Definition:IntrinsicInst.h:371
llvm::DbgVariableIntrinsic::getNumVariableLocationOps
unsigned getNumVariableLocationOps() const
Definition:IntrinsicInst.h:334
llvm::DbgVariableIntrinsic::isAddressOfVariable
bool isAddressOfVariable() const
Does this describe the address of a local variable.
Definition:IntrinsicInst.h:343
llvm::DbgVariableIntrinsic::getExpression
DIExpression * getExpression() const
Definition:IntrinsicInst.h:375
llvm::DbgVariableRecord
Record of a variable value-assignment, aka a non instruction representation of the dbg....
Definition:DebugProgramInstruction.h:270
llvm::DbgVariableRecord::isAddressOfVariable
bool isAddressOfVariable() const
Does this describe the address of a local variable.
Definition:DebugProgramInstruction.h:437
llvm::DbgVariableRecord::clone
DbgVariableRecord * clone() const
Definition:DebugProgramInstruction.cpp:394
llvm::DbgVariableRecord::isDbgAssign
bool isDbgAssign() const
Definition:DebugProgramInstruction.h:506
llvm::DbgVariableRecord::setExpression
void setExpression(DIExpression *NewExpr)
Definition:DebugProgramInstruction.h:452
llvm::DbgVariableRecord::getExpression
DIExpression * getExpression() const
Definition:DebugProgramInstruction.h:453
llvm::DbgVariableRecord::getVariableLocationOp
Value * getVariableLocationOp(unsigned OpIdx) const
Definition:DebugProgramInstruction.cpp:263
llvm::DbgVariableRecord::getVariable
DILocalVariable * getVariable() const
Definition:DebugProgramInstruction.h:449
llvm::DbgVariableRecord::getNumVariableLocationOps
unsigned getNumVariableLocationOps() const
Definition:DebugProgramInstruction.cpp:257
llvm::DbgVariableRecord::replaceVariableLocationOp
void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
Definition:DebugProgramInstruction.cpp:286
llvm::DbgVariableRecord::location_ops
iterator_range< location_op_iterator > location_ops() const
Get the locations corresponding to the variable referenced by the debug info intrinsic.
Definition:DebugProgramInstruction.cpp:234
llvm::DebugLoc
A debug info location.
Definition:DebugLoc.h:33
llvm::DebugLoc::get
DILocation * get() const
Get the underlying DILocation.
Definition:DebugLoc.cpp:20
llvm::DenseMapBase::find
iterator find(const_arg_type_t< KeyT > Val)
Definition:DenseMap.h:156
llvm::DenseMapBase::size
unsigned size() const
Definition:DenseMap.h:99
llvm::DenseMapBase::count
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:152
llvm::DenseMapBase::end
iterator end()
Definition:DenseMap.h:84
llvm::DenseMapBase::insert
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition:DenseMap.h:211
llvm::DenseMapIterator
Definition:DenseMap.h:1189
llvm::DenseMap
Definition:DenseMap.h:727
llvm::DenseSet
Implements a dense probed hash-table based set.
Definition:DenseSet.h:278
llvm::DomTreeUpdater
Definition:DomTreeUpdater.h:30
llvm::DomTreeUpdater::deleteBB
void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Definition:DomTreeUpdater.cpp:62
llvm::DominatorTree
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition:Dominators.h:162
llvm::DominatorTree::dominates
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Definition:Dominators.cpp:122
llvm::Function
Definition:Function.h:63
llvm::Function::getEntryBlock
const BasicBlock & getEntryBlock() const
Definition:Function.h:809
llvm::GenericDomTreeUpdater::applyUpdatesPermissive
void applyUpdatesPermissive(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
Definition:GenericDomTreeUpdaterImpl.h:81
llvm::GenericDomTreeUpdater::applyUpdates
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
Definition:GenericDomTreeUpdaterImpl.h:59
llvm::GenericDomTreeUpdater::hasDomTree
bool hasDomTree() const
Returns true if it holds a DomTreeT.
Definition:GenericDomTreeUpdater.h:65
llvm::GenericDomTreeUpdater::isBBPendingDeletion
bool isBBPendingDeletion(BasicBlockT *DelBB) const
Returns true if DelBB is awaiting deletion.
Definition:GenericDomTreeUpdater.h:78
llvm::GenericDomTreeUpdater::recalculate
void recalculate(FuncT &F)
Notify DTU that the entry block was replaced.
Definition:GenericDomTreeUpdaterImpl.h:28
llvm::GetElementPtrInst
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition:Instructions.h:933
llvm::ICmpInst
This instruction compares its operands according to the predicate given to the constructor.
Definition:Instructions.h:1158
llvm::IRBuilderBase::CreateICmpEQ
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition:IRBuilder.h:2270
llvm::IRBuilderBase::CreateCondBr
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition:IRBuilder.h:1164
llvm::IRBuilderBase::CreateBr
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition:IRBuilder.h:1158
llvm::IRBuilder
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition:IRBuilder.h:2705
llvm::Instruction
Definition:Instruction.h:68
llvm::Instruction::getDbgRecordRange
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange() const
Return a range over the DbgRecords attached to this instruction.
Definition:Instruction.h:104
llvm::Instruction::insertBefore
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
Definition:Instruction.cpp:99
llvm::Instruction::getDebugLoc
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition:Instruction.h:492
llvm::Instruction::extractProfTotalWeight
bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
Definition:Metadata.cpp:1788
llvm::Instruction::moveAfter
void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Definition:Instruction.cpp:191
llvm::Instruction::isEHPad
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
Definition:Instruction.h:850
llvm::Instruction::eraseFromParent
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition:Instruction.cpp:94
llvm::Instruction::isIdenticalToWhenDefined
bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
Definition:Instruction.cpp:919
llvm::Instruction::getMetadata
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition:Instruction.h:407
llvm::Instruction::getNextNonDebugInstruction
const Instruction * getNextNonDebugInstruction(bool SkipPseudoOp=false) const
Return a pointer to the next non-debug instruction in the same basic block as 'this',...
Definition:Instruction.cpp:1226
llvm::Instruction::setMetadata
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition:Metadata.cpp:1679
llvm::Instruction::BinaryOps
BinaryOps
Definition:Instruction.h:989
llvm::Instruction::dropPoisonGeneratingFlags
void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
Definition:Instruction.cpp:426
llvm::Instruction::setDebugLoc
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition:Instruction.h:489
llvm::Instruction::copyMetadata
void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
Definition:Instruction.cpp:1345
llvm::Instruction::dropDbgRecords
void dropDbgRecords()
Erase any DbgRecords attached to this instruction.
Definition:Instruction.cpp:325
llvm::Instruction::getDataLayout
const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Definition:Instruction.cpp:76
llvm::IntrinsicInst
A wrapper class for inspecting calls to intrinsic functions.
Definition:IntrinsicInst.h:48
llvm::InvokeInst
Invoke instruction.
Definition:Instructions.h:3670
llvm::InvokeInst::Create
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
Definition:Instructions.h:3710
llvm::LLVMContext
This is an important class for using LLVM in a threaded context.
Definition:LLVMContext.h:67
llvm::LoadInst
An instruction for reading from memory.
Definition:Instructions.h:176
llvm::LoadInst::getPointerOperand
Value * getPointerOperand()
Definition:Instructions.h:255
llvm::MDBuilder
Definition:MDBuilder.h:36
llvm::MDBuilder::createBranchWeights
MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition:MDBuilder.cpp:37
llvm::MDBuilder::createRange
MDNode * createRange(const APInt &Lo, const APInt &Hi)
Return metadata describing the range [Lo, Hi).
Definition:MDBuilder.cpp:95
llvm::MDNode
Metadata node.
Definition:Metadata.h:1073
llvm::MDNode::getMostGenericAliasScope
static MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
Definition:Metadata.cpp:1141
llvm::MDNode::getMergedCallsiteMetadata
static MDNode * getMergedCallsiteMetadata(MDNode *A, MDNode *B)
Definition:MemoryProfileInfo.cpp:391
llvm::MDNode::getMostGenericTBAA
static MDNode * getMostGenericTBAA(MDNode *A, MDNode *B)
Definition:TypeBasedAliasAnalysis.cpp:477
llvm::MDNode::getMostGenericNoaliasAddrspace
static MDNode * getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B)
Definition:Metadata.cpp:1357
llvm::MDNode::get
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition:Metadata.h:1549
llvm::MDNode::getMergedProfMetadata
static MDNode * getMergedProfMetadata(MDNode *A, MDNode *B, const Instruction *AInstr, const Instruction *BInstr)
Merge !prof metadata from two instructions.
Definition:Metadata.cpp:1222
llvm::MDNode::getMostGenericFPMath
static MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
Definition:Metadata.cpp:1173
llvm::MDNode::getMostGenericRange
static MDNode * getMostGenericRange(MDNode *A, MDNode *B)
Definition:Metadata.cpp:1284
llvm::MDNode::getMergedMemProfMetadata
static MDNode * getMergedMemProfMetadata(MDNode *A, MDNode *B)
Definition:MemoryProfileInfo.cpp:382
llvm::MDNode::intersect
static MDNode * intersect(MDNode *A, MDNode *B)
Definition:Metadata.cpp:1128
llvm::MDNode::getContext
LLVMContext & getContext() const
Definition:Metadata.h:1237
llvm::MDNode::getMostGenericAlignmentOrDereferenceable
static MDNode * getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B)
Definition:Metadata.cpp:1394
llvm::MMRAMetadata::combine
static MDNode * combine(LLVMContext &Ctx, const MMRAMetadata &A, const MMRAMetadata &B)
Combines A and B according to MMRA semantics.
Definition:MemoryModelRelaxationAnnotations.cpp:78
llvm::MapVector
This class implements a map that also provides access to all stored values in a deterministic order.
Definition:MapVector.h:36
llvm::MapVector::end
iterator end()
Definition:MapVector.h:71
llvm::MapVector::find
iterator find(const KeyT &Key)
Definition:MapVector.h:167
llvm::MapVector::empty
bool empty() const
Definition:MapVector.h:79
llvm::MapVector::try_emplace
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
Definition:MapVector.h:118
llvm::MapVector::insert
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition:MapVector.h:141
llvm::MemorySSAUpdater
Definition:MemorySSAUpdater.h:54
llvm::MemorySSAUpdater::changeToUnreachable
void changeToUnreachable(const Instruction *I)
Instruction I will be changed to an unreachable.
Definition:MemorySSAUpdater.cpp:1393
llvm::MemorySSAUpdater::removeBlocks
void removeBlocks(const SmallSetVector< BasicBlock *, 8 > &DeadBlocks)
Remove all MemoryAcceses in a set of BasicBlocks about to be deleted.
Definition:MemorySSAUpdater.cpp:1357
llvm::MemorySSAUpdater::removeMemoryAccess
void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
Definition:MemorySSAUpdater.cpp:1290
llvm::Metadata
Root of the metadata hierarchy.
Definition:Metadata.h:62
llvm::Module
A Module instance is used to store all the information related to an LLVM module.
Definition:Module.h:65
llvm::Module::getDataLayout
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition:Module.h:294
llvm::PHINode
Definition:Instructions.h:2600
llvm::PHINode::addIncoming
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Definition:Instructions.h:2735
llvm::PHINode::block_begin
const_block_iterator block_begin() const
Definition:Instructions.h:2653
llvm::PHINode::removeIncomingValue
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
Definition:Instructions.cpp:137
llvm::PHINode::setIncomingValue
void setIncomingValue(unsigned i, Value *V)
Definition:Instructions.h:2678
llvm::PHINode::block_end
const_block_iterator block_end() const
Definition:Instructions.h:2657
llvm::PHINode::getIncomingValueForBlock
Value * getIncomingValueForBlock(const BasicBlock *BB) const
Definition:Instructions.h:2775
llvm::PHINode::getIncomingBlock
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Definition:Instructions.h:2695
llvm::PHINode::getIncomingValue
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
Definition:Instructions.h:2675
llvm::PHINode::getNumIncomingValues
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Definition:Instructions.h:2671
llvm::PoisonValue::get
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition:Constants.cpp:1878
llvm::SetVector::size
size_type size() const
Determine the number of elements in the SetVector.
Definition:SetVector.h:98
llvm::SetVector::takeVector
Vector takeVector()
Clear the SetVector and return the underlying vector.
Definition:SetVector.h:87
llvm::SetVector::count
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Definition:SetVector.h:264
llvm::SetVector::empty
bool empty() const
Determine if the SetVector is empty or not.
Definition:SetVector.h:93
llvm::SetVector::insert
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition:SetVector.h:162
llvm::SetVector::pop_back_val
value_type pop_back_val()
Definition:SetVector.h:285
llvm::SmallDenseMap
Definition:DenseMap.h:883
llvm::SmallPtrSetImplBase::size
size_type size() const
Definition:SmallPtrSet.h:94
llvm::SmallPtrSetImplBase::clear
void clear()
Definition:SmallPtrSet.h:97
llvm::SmallPtrSetImplBase::empty
bool empty() const
Definition:SmallPtrSet.h:93
llvm::SmallPtrSetImpl
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition:SmallPtrSet.h:363
llvm::SmallPtrSetImpl::count
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition:SmallPtrSet.h:452
llvm::SmallPtrSetImpl::insert
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition:SmallPtrSet.h:384
llvm::SmallPtrSetImpl::contains
bool contains(ConstPtrType Ptr) const
Definition:SmallPtrSet.h:458
llvm::SmallPtrSet
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition:SmallPtrSet.h:519
llvm::SmallSetVector
A SetVector that performs no allocations if smaller than a certain size.
Definition:SetVector.h:370
llvm::SmallSet
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition:SmallSet.h:132
llvm::SmallSet::insert
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition:SmallSet.h:181
llvm::SmallSet::size
size_type size() const
Definition:SmallSet.h:170
llvm::SmallVectorBase::empty
bool empty() const
Definition:SmallVector.h:81
llvm::SmallVectorBase::size
size_t size() const
Definition:SmallVector.h:78
llvm::SmallVectorImpl
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition:SmallVector.h:573
llvm::SmallVectorImpl::pop_back_val
T pop_back_val()
Definition:SmallVector.h:673
llvm::SmallVectorImpl::reserve
void reserve(size_type N)
Definition:SmallVector.h:663
llvm::SmallVectorImpl::append
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition:SmallVector.h:683
llvm::SmallVectorImpl::insert
iterator insert(iterator I, T &&Elt)
Definition:SmallVector.h:805
llvm::SmallVectorTemplateBase::pop_back
void pop_back()
Definition:SmallVector.h:425
llvm::SmallVectorTemplateBase::push_back
void push_back(const T &Elt)
Definition:SmallVector.h:413
llvm::SmallVectorTemplateCommon::begin
iterator begin()
Definition:SmallVector.h:267
llvm::SmallVectorTemplateCommon::back
reference back()
Definition:SmallVector.h:308
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition:SmallVector.h:1196
llvm::StoreInst
An instruction for storing to memory.
Definition:Instructions.h:292
llvm::TargetLibraryInfo
Provides information about what library functions are available for the current target.
Definition:TargetLibraryInfo.h:280
llvm::TargetLibraryInfo::hasOptimizedCodeGen
bool hasOptimizedCodeGen(LibFunc F) const
Tests if the function is both available and a candidate for optimized code generation.
Definition:TargetLibraryInfo.h:407
llvm::TargetLibraryInfo::has
bool has(LibFunc F) const
Tests whether a library function is available.
Definition:TargetLibraryInfo.h:387
llvm::TargetLibraryInfo::getLibFunc
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
Definition:TargetLibraryInfo.h:345
llvm::TinyPtrVector
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
Definition:TinyPtrVector.h:29
llvm::TinyPtrVector::empty
bool empty() const
Definition:TinyPtrVector.h:162
llvm::TypeSize
Definition:TypeSize.h:334
llvm::TypeSize::getFixed
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition:TypeSize.h:345
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition:Type.h:45
llvm::Type::isVectorTy
bool isVectorTy() const
True if this is an instance of VectorType.
Definition:Type.h:270
llvm::Type::isArrayTy
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition:Type.h:261
llvm::Type::isIntOrIntVectorTy
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition:Type.h:243
llvm::Type::isPointerTy
bool isPointerTy() const
True if this is an instance of PointerType.
Definition:Type.h:264
llvm::Type::getIntNTy
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
llvm::Type::getScalarSizeInBits
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
llvm::Type::isStructTy
bool isStructTy() const
True if this is an instance of StructType.
Definition:Type.h:258
llvm::Type::isFloatingPointTy
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition:Type.h:184
llvm::Type::isIntOrPtrTy
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition:Type.h:252
llvm::Type::getInt32Ty
static IntegerType * getInt32Ty(LLVMContext &C)
llvm::Type::isIntegerTy
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition:Type.h:237
llvm::Type::isTokenTy
bool isTokenTy() const
Return true if this is 'token'.
Definition:Type.h:234
llvm::Type::getPrimitiveSizeInBits
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
llvm::UndefValue::get
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition:Constants.cpp:1859
llvm::UnreachableInst
This function has undefined behavior.
Definition:Instructions.h:4461
llvm::Use
A Use represents the edge between a Value definition and its users.
Definition:Use.h:43
llvm::User
Definition:User.h:44
llvm::User::value_op_end
value_op_iterator value_op_end()
Definition:User.h:309
llvm::User::getOperand
Value * getOperand(unsigned i) const
Definition:User.h:228
llvm::User::value_op_begin
value_op_iterator value_op_begin()
Definition:User.h:306
llvm::ValueAsMetadata
Value wrapper in the Metadata hierarchy.
Definition:Metadata.h:454
llvm::ValueAsMetadata::get
static ValueAsMetadata * get(Value *V)
Definition:Metadata.cpp:501
llvm::ValueMap< const Value *, WeakTrackingVH >
llvm::ValueMap::find
iterator find(const KeyT &Val)
Definition:ValueMap.h:155
llvm::ValueMap::insert
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition:ValueMap.h:172
llvm::ValueMap::size
size_type size() const
Definition:ValueMap.h:140
llvm::ValueMap::end
iterator end()
Definition:ValueMap.h:135
llvm::Value
LLVM Value Representation.
Definition:Value.h:74
llvm::Value::getType
Type * getType() const
All values are typed, get the type of this value.
Definition:Value.h:255
llvm::Value::replaceAllUsesWith
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition:Value.cpp:534
llvm::Value::users
iterator_range< user_iterator > users()
Definition:Value.h:421
llvm::Value::replaceUsesWithIf
void replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
Definition:Value.cpp:542
llvm::Value::use_empty
bool use_empty() const
Definition:Value.h:344
llvm::Value::getContext
LLVMContext & getContext() const
All values hold a context through their type.
Definition:Value.cpp:1075
llvm::Value::MaxAlignmentExponent
static constexpr unsigned MaxAlignmentExponent
The maximum alignment for instructions.
Definition:Value.h:810
llvm::Value::user_iterator
user_iterator_impl< User > user_iterator
Definition:Value.h:390
llvm::Value::hasName
bool hasName() const
Definition:Value.h:261
llvm::Value::getName
StringRef getName() const
Return a constant reference to the value's name.
Definition:Value.cpp:309
llvm::Value::takeName
void takeName(Value *V)
Transfer the name from V to this value.
Definition:Value.cpp:383
llvm::WithOverflowInst
Represents an op.with.overflow intrinsic.
Definition:IntrinsicInst.h:927
llvm::cl::opt
Definition:CommandLine.h:1423
llvm::detail::DenseSetImpl::insert
std::pair< iterator, bool > insert(const ValueT &V)
Definition:DenseSet.h:213
llvm::detail::DenseSetImpl::clear
void clear()
Definition:DenseSet.h:92
llvm::detail::DenseSetImpl::reserve
void reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
Definition:DenseSet.h:90
llvm::detail::DenseSetPair
Definition:DenseSet.h:34
llvm::function_ref
An efficient, type-erasing, non-owning reference to a callable.
Definition:STLFunctionalExtras.h:37
llvm::generic_gep_type_iterator
Definition:GetElementPtrTypeIterator.h:31
llvm::generic_gep_type_iterator::isStruct
bool isStruct() const
Definition:GetElementPtrTypeIterator.h:145
llvm::ilist_detail::node_parent_access::getParent
const ParentTy * getParent() const
Definition:ilist_node.h:32
llvm::ilist_node_impl::getIterator
self_iterator getIterator()
Definition:ilist_node.h:132
llvm::mapped_iterator
Definition:STLExtras.h:353
uint32_t
uint64_t
uint8_t
unsigned
DebugInfo.h
ErrorHandling.h
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition:ErrorHandling.h:143
llvm::CallingConv::C
@ C
The default llvm calling convention, compatible with C.
Definition:CallingConv.h:34
llvm::Intrinsic::getOrInsertDeclaration
Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
Definition:Intrinsics.cpp:732
llvm::PatternMatch
Definition:PatternMatch.h:47
llvm::PatternMatch::m_And
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
Definition:PatternMatch.h:1216
llvm::PatternMatch::m_BitReverse
m_Intrinsic_Ty< Opnd0 >::Ty m_BitReverse(const Opnd0 &Op0)
Definition:PatternMatch.h:2692
llvm::PatternMatch::m_Trunc
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
Definition:PatternMatch.h:2075
llvm::PatternMatch::match
bool match(Val *V, const Pattern &P)
Definition:PatternMatch.h:49
llvm::PatternMatch::m_Specific
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition:PatternMatch.h:885
llvm::PatternMatch::m_LogicalShift
BinOpPred_match< LHS, RHS, is_logical_shift_op > m_LogicalShift(const LHS &L, const RHS &R)
Matches logical shift operations.
Definition:PatternMatch.h:1533
llvm::PatternMatch::m_WithOverflowInst
bind_ty< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
Definition:PatternMatch.h:832
llvm::PatternMatch::m_ZExt
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
Definition:PatternMatch.h:2107
llvm::PatternMatch::m_FShl
m_Intrinsic_Ty< Opnd0, Opnd1, Opnd2 >::Ty m_FShl(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
Definition:PatternMatch.h:2725
llvm::PatternMatch::m_APInt
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition:PatternMatch.h:299
llvm::PatternMatch::m_Value
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition:PatternMatch.h:92
llvm::PatternMatch::m_FShr
m_Intrinsic_Ty< Opnd0, Opnd1, Opnd2 >::Ty m_FShr(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
Definition:PatternMatch.h:2731
llvm::PatternMatch::m_Undef
auto m_Undef()
Match an arbitrary undef constant.
Definition:PatternMatch.h:152
llvm::PatternMatch::m_Not
BinaryOp_match< cst_pred_ty< is_all_ones >, ValTy, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
Definition:PatternMatch.h:2467
llvm::PatternMatch::m_Or
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
Definition:PatternMatch.h:1222
llvm::PatternMatch::m_BSwap
m_Intrinsic_Ty< Opnd0 >::Ty m_BSwap(const Opnd0 &Op0)
Definition:PatternMatch.h:2697
llvm::PatternMatch::m_Zero
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
Definition:PatternMatch.h:612
llvm::PatternMatch::m_CombineOr
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
Definition:PatternMatch.h:239
llvm::cl::Hidden
@ Hidden
Definition:CommandLine.h:137
llvm::cl::init
initializer< Ty > init(const Ty &Val)
Definition:CommandLine.h:443
llvm::dwarf::DW_OP_LLVM_arg
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
Definition:Dwarf.h:147
llvm::fp::ebStrict
@ ebStrict
This corresponds to "fpexcept.strict".
Definition:FPEnv.h:41
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition:AddressRanges.h:18
llvm::Offset
@ Offset
Definition:DWP.cpp:480
llvm::find
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition:STLExtras.h:1759
llvm::RemoveRedundantDbgInstrs
bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
Definition:BasicBlockUtils.cpp:685
llvm::for_each
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:1732
llvm::all_of
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition:STLExtras.h:1739
llvm::RecursivelyDeleteTriviallyDeadInstructions
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition:Local.cpp:546
llvm::succ_empty
bool succ_empty(const Instruction *I)
Definition:CFG.h:255
llvm::changeToInvokeAndSplitBasicBlock
BasicBlock * changeToInvokeAndSplitBasicBlock(CallInst *CI, BasicBlock *UnwindEdge, DomTreeUpdater *DTU=nullptr)
Convert the CallInst to InvokeInst with the specified unwind edge basic block.
Definition:Local.cpp:2995
llvm::ConstantFoldTerminator
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Definition:Local.cpp:136
llvm::replaceDominatedUsesWithIf
unsigned replaceDominatedUsesWithIf(Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge, function_ref< bool(const Use &U, const Value *To)> ShouldReplace)
Replace each use of 'From' with 'To' if that use is dominated by the given edge and the callback Shou...
Definition:Local.cpp:3598
llvm::findDbgDeclares
TinyPtrVector< DbgDeclareInst * > findDbgDeclares(Value *V)
Finds dbg.declare intrinsics declaring local variables as living in the memory that 'V' points to.
Definition:DebugInfo.cpp:47
llvm::removeAllNonTerminatorAndEHPadInstructions
std::pair< unsigned, unsigned > removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB)
Remove all instructions from a basic block other than its terminator and any present EH pad instructi...
Definition:Local.cpp:2877
llvm::Successor
@ Successor
Definition:SIMachineScheduler.h:35
llvm::Depth
@ Depth
Definition:SIMachineScheduler.h:36
llvm::pred_end
auto pred_end(const MachineBasicBlock *BB)
Definition:MachineBasicBlock.h:1385
llvm::replaceNonLocalUsesWith
unsigned replaceNonLocalUsesWith(Instruction *From, Value *To)
Definition:Local.cpp:3565
llvm::salvageDebugInfoForDbgValues
void salvageDebugInfoForDbgValues(Instruction &I, ArrayRef< DbgVariableIntrinsic * > Insns, ArrayRef< DbgVariableRecord * > DPInsns)
Implementation of salvageDebugInfo, applying only to instructions in Insns, rather than all debug use...
Definition:Local.cpp:2316
llvm::LibFunc
LibFunc
Definition:TargetLibraryInfo.h:68
llvm::findDbgUsers
void findDbgUsers(SmallVectorImpl< DbgVariableIntrinsic * > &DbgInsts, Value *V, SmallVectorImpl< DbgVariableRecord * > *DbgVariableRecords=nullptr)
Finds the debug info intrinsics describing a value.
Definition:DebugInfo.cpp:162
llvm::salvageDebugInfo
void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition:Utils.cpp:1683
llvm::successors
auto successors(const MachineBasicBlock *BB)
Definition:MachineBasicBlock.h:1376
llvm::isRemovableAlloc
bool isRemovableAlloc(const CallBase *V, const TargetLibraryInfo *TLI)
Return true if this is a call to an allocation function that does not have side effects that we are r...
Definition:MemoryBuiltins.cpp:330
llvm::changeToCall
CallInst * changeToCall(InvokeInst *II, DomTreeUpdater *DTU=nullptr)
This function converts the specified invoke into a normal call.
Definition:Local.cpp:2975
llvm::isMathLibCallNoop
bool isMathLibCallNoop(const CallBase *Call, const TargetLibraryInfo *TLI)
Check whether the given call has no side-effects.
Definition:ConstantFolding.cpp:3914
llvm::copyMetadataForLoad
void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source)
Copy the metadata from the source instruction to the destination (the replacement for the source inst...
Definition:Local.cpp:3448
llvm::InsertDebugValueAtStoreLoc
void InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
===------------------------------------------------------------------—===// Dbg Intrinsic utilities
Definition:Local.cpp:1868
llvm::hasNItemsOrLess
bool hasNItemsOrLess(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;})
Returns true if the sequence [Begin, End) has N or less items.
Definition:STLExtras.h:2553
llvm::remapDebugVariable
void remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst)
Remap the operands of the debug records attached to Inst, and the operands of Inst itself if it's a d...
Definition:Local.cpp:3787
llvm::make_early_inc_range
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:657
llvm::pred_size
auto pred_size(const MachineBasicBlock *BB)
Definition:MachineBasicBlock.h:1381
llvm::SimplifyInstructionsInBlock
bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Scan the specified basic block and try to simplify any instructions in it and recursively delete dead...
Definition:Local.cpp:737
llvm::isAssumeWithEmptyBundle
bool isAssumeWithEmptyBundle(const AssumeInst &Assume)
Return true iff the operand bundles of the provided llvm.assume doesn't contain any valuable informat...
Definition:AssumeBundleQueries.cpp:128
llvm::DeleteDeadBlock
void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
Definition:BasicBlockUtils.cpp:96
llvm::hasBranchWeightOrigin
bool hasBranchWeightOrigin(const Instruction &I)
Check if Branch Weight Metadata has an "expected" field from an llvm.expect* intrinsic.
Definition:ProfDataUtils.cpp:122
llvm::findDbgValues
void findDbgValues(SmallVectorImpl< DbgValueInst * > &DbgValues, Value *V, SmallVectorImpl< DbgVariableRecord * > *DbgVariableRecords=nullptr)
Finds the llvm.dbg.value intrinsics describing a value.
Definition:DebugInfo.cpp:155
llvm::insertDebugValuesForPHIs
void insertDebugValuesForPHIs(BasicBlock *BB, SmallVectorImpl< PHINode * > &InsertedPHIs)
Propagate dbg.value intrinsics through the newly inserted PHIs.
Definition:Local.cpp:2142
llvm::getConstantRangeFromMetadata
ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
Definition:ConstantRange.cpp:2264
llvm::intersectAccessGroups
MDNode * intersectAccessGroups(const Instruction *Inst1, const Instruction *Inst2)
Compute the access-group list of access groups that Inst1 and Inst2 are both in.
Definition:VectorUtils.cpp:895
llvm::handleUnreachableTerminator
bool handleUnreachableTerminator(Instruction *I, SmallVectorImpl< Value * > &PoisonedValues)
If a terminator in an unreachable basic block has an operand of type Instruction, transform it into p...
Definition:Local.cpp:2859
llvm::canSimplifyInvokeNoUnwind
bool canSimplifyInvokeNoUnwind(const Function *F)
Definition:EHPersonalities.cpp:93
llvm::simplifyInstruction
Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
Definition:InstructionSimplify.cpp:7234
llvm::any_of
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:1746
llvm::isInstructionTriviallyDead
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition:Local.cpp:406
llvm::TryToSimplifyUncondBranchFromEmptyBlock
bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes,...
Definition:Local.cpp:1156
llvm::recognizeBSwapOrBitReverseIdiom
bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction * > &InsertedInsts)
Try to match a bswap or bitreverse idiom.
Definition:Local.cpp:4096
llvm::setBranchWeights
void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
Definition:ProfDataUtils.cpp:235
llvm::getValidBranchWeightMDNode
MDNode * getValidBranchWeightMDNode(const Instruction &I)
Get the valid branch weights metadata node.
Definition:ProfDataUtils.cpp:153
llvm::getOrEnforceKnownAlignment
Align getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
Definition:Local.cpp:1581
llvm::wouldInstructionBeTriviallyDeadOnUnusedPaths
bool wouldInstructionBeTriviallyDeadOnUnusedPaths(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction has no side effects on any paths other than whe...
Definition:Local.cpp:413
llvm::LowerDbgDeclare
bool LowerDbgDeclare(Function &F)
Lowers llvm.dbg.declare intrinsics into appropriate set of llvm.dbg.value intrinsics.
Definition:Local.cpp:1990
llvm::NullPointerIsDefined
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
Definition:Function.cpp:1187
llvm::getExpressionForConstant
DIExpression * getExpressionForConstant(DIBuilder &DIB, const Constant &C, Type &Ty)
Given a constant, create a debug information expression.
Definition:Local.cpp:3749
llvm::createCallMatchingInvoke
CallInst * createCallMatchingInvoke(InvokeInst *II)
Create a call that matches the invoke II in terms of arguments, attributes, debug information,...
Definition:Local.cpp:2949
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition:Debug.cpp:163
llvm::removeUnwindEdge
Instruction * removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
Replace 'BB's terminator with one that does not have an unwind successor block.
Definition:Local.cpp:3236
llvm::wouldInstructionBeTriviallyDead
bool wouldInstructionBeTriviallyDead(const Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used.
Definition:Local.cpp:425
llvm::patchReplacementInstruction
void patchReplacementInstruction(Instruction *I, Value *Repl)
Patch the replacement so that it is not more restrictive than the value being replaced.
Definition:Local.cpp:3500
llvm::getDebugValueLoc
DebugLoc getDebugValueLoc(DbgVariableIntrinsic *DII)
Produce a DebugLoc to use for each dbg.declare that is promoted to a dbg.value.
Definition:DebugInfo.cpp:175
llvm::ConvertDebugDeclareToDebugValue
void ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII, StoreInst *SI, DIBuilder &Builder)
Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value that has an associated llvm....
Definition:Local.cpp:1731
llvm::replaceDominatedUsesWith
unsigned replaceDominatedUsesWith(Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge)
Replace each use of 'From' with 'To' if that use is dominated by the given edge.
Definition:Local.cpp:3580
llvm::CaptureComponents::Provenance
@ Provenance
llvm::changeToUnreachable
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:2909
llvm::replaceAllDbgUsesWith
bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
Definition:Local.cpp:2787
llvm::salvageDebugInfoImpl
Value * salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Ops, SmallVectorImpl< Value * > &AdditionalValues)
Definition:Local.cpp:2617
llvm::succ_begin
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
Definition:RegionIterator.h:249
llvm::combineMetadataForCSE
void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition:Local.cpp:3439
llvm::dropDebugUsers
void dropDebugUsers(Instruction &I)
Remove the debug intrinsic instructions for the given instruction.
Definition:Local.cpp:3696
llvm::IRMemLocation::First
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
llvm::MergeBasicBlockIntoOnlyPred
void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is a block with one predecessor and its predecessor is known to have one successor (BB!...
Definition:Local.cpp:777
llvm::replaceDbgUsesWithUndef
bool replaceDbgUsesWithUndef(Instruction *I)
Replace all the uses of an SSA value in @llvm.dbg intrinsics with undef.
Definition:Local.cpp:623
llvm::hoistAllInstructionsInto
void hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt, BasicBlock *BB)
Hoist all of the instructions in the IfBlock to the dominant block DomBlock, by moving its instructio...
Definition:Local.cpp:3706
llvm::copyRangeMetadata
void copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI, MDNode *N, LoadInst &NewLI)
Copy a range metadata node to a new load instruction.
Definition:Local.cpp:3672
llvm::copyNonnullMetadata
void copyNonnullMetadata(const LoadInst &OldLI, MDNode *N, LoadInst &NewLI)
Copy a nonnull metadata node to a new load instruction.
Definition:Local.cpp:3647
llvm::computeKnownBits
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
Definition:ValueTracking.cpp:164
llvm::canReplaceOperandWithVariable
bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant value?
Definition:Local.cpp:4209
llvm::replaceDbgValueForAlloca
void replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, int Offset=0)
Replaces multiple llvm.dbg.value instructions when the alloca it describes is replaced with a new val...
Definition:Local.cpp:2253
llvm::tryEnforceAlignment
Align tryEnforceAlignment(Value *V, Align PrefAlign, const DataLayout &DL)
If the specified pointer points to an object that we control, try to modify the object's alignment to...
Definition:Local.cpp:1532
llvm::getFreedOperand
Value * getFreedOperand(const CallBase *CB, const TargetLibraryInfo *TLI)
If this if a call to a free function, return the freed operand.
Definition:MemoryBuiltins.cpp:545
llvm::RecursivelyDeleteTriviallyDeadInstructionsPermissive
bool RecursivelyDeleteTriviallyDeadInstructionsPermissive(SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
Same functionality as RecursivelyDeleteTriviallyDeadInstructions, but allow instructions that are not...
Definition:Local.cpp:561
llvm::BitWidth
constexpr unsigned BitWidth
Definition:BitmaskEnum.h:217
llvm::extractBranchWeights
bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
Definition:ProfDataUtils.cpp:170
llvm::count_if
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:1945
llvm::pred_begin
auto pred_begin(const MachineBasicBlock *BB)
Definition:MachineBasicBlock.h:1383
llvm::SplitBlock
BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
Definition:BasicBlockUtils.cpp:1084
llvm::gep_type_begin
gep_type_iterator gep_type_begin(const User *GEP)
Definition:GetElementPtrTypeIterator.h:173
llvm::findDVRDeclares
TinyPtrVector< DbgVariableRecord * > findDVRDeclares(Value *V)
As above, for DVRDeclares.
Definition:DebugInfo.cpp:66
llvm::predecessors
auto predecessors(const MachineBasicBlock *BB)
Definition:MachineBasicBlock.h:1377
llvm::is_contained
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition:STLExtras.h:1903
llvm::combineAAMetadata
void combineAAMetadata(Instruction *K, const Instruction *J)
Combine metadata of two instructions, where instruction J is a memory access that has been merged int...
Definition:Local.cpp:3444
llvm::RecursivelyDeleteDeadPHINode
bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
Definition:Local.cpp:657
llvm::inferAttributesFromOthers
bool inferAttributesFromOthers(Function &F)
If we can infer one attribute from another on the declaration of a function, explicitly materialize t...
Definition:Local.cpp:4316
llvm::invertCondition
Value * invertCondition(Value *Condition)
Invert the given true/false value, possibly reusing an existing copy.
Definition:Local.cpp:4282
llvm::hash_combine
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition:Hashing.h:590
llvm::DeleteDeadBlocks
void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
Definition:BasicBlockUtils.cpp:101
llvm::maybeMarkSanitizerLibraryCallNoBuiltin
void maybeMarkSanitizerLibraryCallNoBuiltin(CallInst *CI, const TargetLibraryInfo *TLI)
Given a CallInst, check if it calls a string function known to CodeGen, and mark it with NoBuiltin if...
Definition:Local.cpp:4199
llvm::filterDbgVars
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
Definition:DebugProgramInstruction.h:555
llvm::removeUnreachableBlocks
bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Remove all blocks that can not be reached from the function's entry.
Definition:Local.cpp:3274
llvm::EliminateDuplicatePHINodes
bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
Definition:Local.cpp:1524
llvm::callsGCLeafFunction
bool callsGCLeafFunction(const CallBase *Call, const TargetLibraryInfo &TLI)
Return true if this call calls a gc leaf function.
Definition:Local.cpp:3618
llvm::hash_combine_range
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition:Hashing.h:468
llvm::replaceDbgDeclare
bool replaceDbgDeclare(Value *Address, Value *NewAddress, DIBuilder &Builder, uint8_t DIExprFlags, int Offset)
Replaces llvm.dbg.declare instruction when the address it describes is replaced with a new value.
Definition:Local.cpp:2204
std::swap
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition:BitVector.h:860
raw_ostream.h
N
#define N
NDEBUG
#define NDEBUG
Definition:regutils.h:48
llvm::Align
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition:Alignment.h:39
llvm::DenseMapInfo
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition:DenseMapInfo.h:52
llvm::KnownBits
Definition:KnownBits.h:23
llvm::KnownBits::countMinTrailingZeros
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition:KnownBits.h:234
llvm::KnownBits::getBitWidth
unsigned getBitWidth() const
Get the bit width of this value.
Definition:KnownBits.h:43
llvm::MaybeAlign
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition:Alignment.h:117
llvm::SmallMapVector
A MapVector that performs no allocations if smaller than a certain size.
Definition:MapVector.h:254
llvm::cl::desc
Definition:CommandLine.h:409
llvm::detail::DenseSetEmpty
Definition:DenseSet.h:30

Generated on Thu Jul 17 2025 17:41:08 for LLVM by doxygen 1.9.6
[8]ページ先頭

©2009-2025 Movatter.jp