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