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