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