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