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