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