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