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