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