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   TypeSize ValueSize = DL.getTypeAllocSizeInBits(ValTy);
1344   if (Optional<uint64_t> FragmentSize = DII->getFragmentSizeInBits()) {
1345     assert(!ValueSize.isScalable() &&
1346            "Fragments don't work on scalable types.");
1347     return ValueSize.getFixedSize() >= *FragmentSize;
1348   }
1349   // We can't always calculate the size of the DI variable (e.g. if it is a
1350   // VLA). Try to use the size of the alloca that the dbg intrinsic describes
1351   // intead.
1352   if (DII->isAddressOfVariable())
1353     if (auto *AI = dyn_cast_or_null<AllocaInst>(DII->getVariableLocation()))
1354       if (Optional<TypeSize> FragmentSize = AI->getAllocationSizeInBits(DL)) {
1355         assert(ValueSize.isScalable() == FragmentSize->isScalable() &&
1356                "Both sizes should agree on the scalable flag.");
1357         return TypeSize::isKnownGE(ValueSize, *FragmentSize);
1358       }
1359   // Could not determine size of variable. Conservatively return false.
1360   return false;
1361 }
1362 
1363 /// Produce a DebugLoc to use for each dbg.declare/inst pair that are promoted
1364 /// to a dbg.value. Because no machine insts can come from debug intrinsics,
1365 /// only the scope and inlinedAt is significant. Zero line numbers are used in
1366 /// case this DebugLoc leaks into any adjacent instructions.
1367 static DebugLoc getDebugValueLoc(DbgVariableIntrinsic *DII, Instruction *Src) {
1368   // Original dbg.declare must have a location.
1369   DebugLoc DeclareLoc = DII->getDebugLoc();
1370   MDNode *Scope = DeclareLoc.getScope();
1371   DILocation *InlinedAt = DeclareLoc.getInlinedAt();
1372   // Produce an unknown location with the correct scope / inlinedAt fields.
1373   return DILocation::get(DII->getContext(), 0, 0, Scope, InlinedAt);
1374 }
1375 
1376 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
1377 /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
1378 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1379                                            StoreInst *SI, DIBuilder &Builder) {
1380   assert(DII->isAddressOfVariable());
1381   auto *DIVar = DII->getVariable();
1382   assert(DIVar && "Missing variable");
1383   auto *DIExpr = DII->getExpression();
1384   Value *DV = SI->getValueOperand();
1385 
1386   DebugLoc NewLoc = getDebugValueLoc(DII, SI);
1387 
1388   if (!valueCoversEntireFragment(DV->getType(), DII)) {
1389     // FIXME: If storing to a part of the variable described by the dbg.declare,
1390     // then we want to insert a dbg.value for the corresponding fragment.
1391     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1392                       << *DII << '\n');
1393     // For now, when there is a store to parts of the variable (but we do not
1394     // know which part) we insert an dbg.value instrinsic to indicate that we
1395     // know nothing about the variable's content.
1396     DV = UndefValue::get(DV->getType());
1397     Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
1398     return;
1399   }
1400 
1401   Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
1402 }
1403 
1404 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
1405 /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
1406 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1407                                            LoadInst *LI, DIBuilder &Builder) {
1408   auto *DIVar = DII->getVariable();
1409   auto *DIExpr = DII->getExpression();
1410   assert(DIVar && "Missing variable");
1411 
1412   if (!valueCoversEntireFragment(LI->getType(), DII)) {
1413     // FIXME: If only referring to a part of the variable described by the
1414     // dbg.declare, then we want to insert a dbg.value for the corresponding
1415     // fragment.
1416     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1417                       << *DII << '\n');
1418     return;
1419   }
1420 
1421   DebugLoc NewLoc = getDebugValueLoc(DII, nullptr);
1422 
1423   // We are now tracking the loaded value instead of the address. In the
1424   // future if multi-location support is added to the IR, it might be
1425   // preferable to keep tracking both the loaded value and the original
1426   // address in case the alloca can not be elided.
1427   Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
1428       LI, DIVar, DIExpr, NewLoc, (Instruction *)nullptr);
1429   DbgValue->insertAfter(LI);
1430 }
1431 
1432 /// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
1433 /// llvm.dbg.declare or llvm.dbg.addr intrinsic.
1434 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1435                                            PHINode *APN, DIBuilder &Builder) {
1436   auto *DIVar = DII->getVariable();
1437   auto *DIExpr = DII->getExpression();
1438   assert(DIVar && "Missing variable");
1439 
1440   if (PhiHasDebugValue(DIVar, DIExpr, APN))
1441     return;
1442 
1443   if (!valueCoversEntireFragment(APN->getType(), DII)) {
1444     // FIXME: If only referring to a part of the variable described by the
1445     // dbg.declare, then we want to insert a dbg.value for the corresponding
1446     // fragment.
1447     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1448                       << *DII << '\n');
1449     return;
1450   }
1451 
1452   BasicBlock *BB = APN->getParent();
1453   auto InsertionPt = BB->getFirstInsertionPt();
1454 
1455   DebugLoc NewLoc = getDebugValueLoc(DII, nullptr);
1456 
1457   // The block may be a catchswitch block, which does not have a valid
1458   // insertion point.
1459   // FIXME: Insert dbg.value markers in the successors when appropriate.
1460   if (InsertionPt != BB->end())
1461     Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, NewLoc, &*InsertionPt);
1462 }
1463 
1464 /// Determine whether this alloca is either a VLA or an array.
1465 static bool isArray(AllocaInst *AI) {
1466   return AI->isArrayAllocation() ||
1467          (AI->getAllocatedType() && AI->getAllocatedType()->isArrayTy());
1468 }
1469 
1470 /// Determine whether this alloca is a structure.
1471 static bool isStructure(AllocaInst *AI) {
1472   return AI->getAllocatedType() && AI->getAllocatedType()->isStructTy();
1473 }
1474 
1475 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1476 /// of llvm.dbg.value intrinsics.
1477 bool llvm::LowerDbgDeclare(Function &F) {
1478   bool Changed = false;
1479   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
1480   SmallVector<DbgDeclareInst *, 4> Dbgs;
1481   for (auto &FI : F)
1482     for (Instruction &BI : FI)
1483       if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1484         Dbgs.push_back(DDI);
1485 
1486   if (Dbgs.empty())
1487     return Changed;
1488 
1489   for (auto &I : Dbgs) {
1490     DbgDeclareInst *DDI = I;
1491     AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1492     // If this is an alloca for a scalar variable, insert a dbg.value
1493     // at each load and store to the alloca and erase the dbg.declare.
1494     // The dbg.values allow tracking a variable even if it is not
1495     // stored on the stack, while the dbg.declare can only describe
1496     // the stack slot (and at a lexical-scope granularity). Later
1497     // passes will attempt to elide the stack slot.
1498     if (!AI || isArray(AI) || isStructure(AI))
1499       continue;
1500 
1501     // A volatile load/store means that the alloca can't be elided anyway.
1502     if (llvm::any_of(AI->users(), [](User *U) -> bool {
1503           if (LoadInst *LI = dyn_cast<LoadInst>(U))
1504             return LI->isVolatile();
1505           if (StoreInst *SI = dyn_cast<StoreInst>(U))
1506             return SI->isVolatile();
1507           return false;
1508         }))
1509       continue;
1510 
1511     SmallVector<const Value *, 8> WorkList;
1512     WorkList.push_back(AI);
1513     while (!WorkList.empty()) {
1514       const Value *V = WorkList.pop_back_val();
1515       for (auto &AIUse : V->uses()) {
1516         User *U = AIUse.getUser();
1517         if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1518           if (AIUse.getOperandNo() == 1)
1519             ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1520         } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1521           ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1522         } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
1523           // This is a call by-value or some other instruction that takes a
1524           // pointer to the variable. Insert a *value* intrinsic that describes
1525           // the variable by dereferencing the alloca.
1526           if (!CI->isLifetimeStartOrEnd()) {
1527             DebugLoc NewLoc = getDebugValueLoc(DDI, nullptr);
1528             auto *DerefExpr =
1529                 DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
1530             DIB.insertDbgValueIntrinsic(AI, DDI->getVariable(), DerefExpr,
1531                                         NewLoc, CI);
1532           }
1533         } else if (BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
1534           if (BI->getType()->isPointerTy())
1535             WorkList.push_back(BI);
1536         }
1537       }
1538     }
1539     DDI->eraseFromParent();
1540     Changed = true;
1541   }
1542 
1543   if (Changed)
1544   for (BasicBlock &BB : F)
1545     RemoveRedundantDbgInstrs(&BB);
1546 
1547   return Changed;
1548 }
1549 
1550 /// Propagate dbg.value intrinsics through the newly inserted PHIs.
1551 void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
1552                                     SmallVectorImpl<PHINode *> &InsertedPHIs) {
1553   assert(BB && "No BasicBlock to clone dbg.value(s) from.");
1554   if (InsertedPHIs.size() == 0)
1555     return;
1556 
1557   // Map existing PHI nodes to their dbg.values.
1558   ValueToValueMapTy DbgValueMap;
1559   for (auto &I : *BB) {
1560     if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
1561       if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
1562         DbgValueMap.insert({Loc, DbgII});
1563     }
1564   }
1565   if (DbgValueMap.size() == 0)
1566     return;
1567 
1568   // Then iterate through the new PHIs and look to see if they use one of the
1569   // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
1570   // propagate the info through the new PHI.
1571   LLVMContext &C = BB->getContext();
1572   for (auto PHI : InsertedPHIs) {
1573     BasicBlock *Parent = PHI->getParent();
1574     // Avoid inserting an intrinsic into an EH block.
1575     if (Parent->getFirstNonPHI()->isEHPad())
1576       continue;
1577     auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
1578     for (auto VI : PHI->operand_values()) {
1579       auto V = DbgValueMap.find(VI);
1580       if (V != DbgValueMap.end()) {
1581         auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
1582         Instruction *NewDbgII = DbgII->clone();
1583         NewDbgII->setOperand(0, PhiMAV);
1584         auto InsertionPt = Parent->getFirstInsertionPt();
1585         assert(InsertionPt != Parent->end() && "Ill-formed basic block");
1586         NewDbgII->insertBefore(&*InsertionPt);
1587       }
1588     }
1589   }
1590 }
1591 
1592 /// Finds all intrinsics declaring local variables as living in the memory that
1593 /// 'V' points to. This may include a mix of dbg.declare and
1594 /// dbg.addr intrinsics.
1595 TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
1596   // This function is hot. Check whether the value has any metadata to avoid a
1597   // DenseMap lookup.
1598   if (!V->isUsedByMetadata())
1599     return {};
1600   auto *L = LocalAsMetadata::getIfExists(V);
1601   if (!L)
1602     return {};
1603   auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
1604   if (!MDV)
1605     return {};
1606 
1607   TinyPtrVector<DbgVariableIntrinsic *> Declares;
1608   for (User *U : MDV->users()) {
1609     if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
1610       if (DII->isAddressOfVariable())
1611         Declares.push_back(DII);
1612   }
1613 
1614   return Declares;
1615 }
1616 
1617 TinyPtrVector<DbgDeclareInst *> llvm::FindDbgDeclareUses(Value *V) {
1618   TinyPtrVector<DbgDeclareInst *> DDIs;
1619   for (DbgVariableIntrinsic *DVI : FindDbgAddrUses(V))
1620     if (auto *DDI = dyn_cast<DbgDeclareInst>(DVI))
1621       DDIs.push_back(DDI);
1622   return DDIs;
1623 }
1624 
1625 void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
1626   // This function is hot. Check whether the value has any metadata to avoid a
1627   // DenseMap lookup.
1628   if (!V->isUsedByMetadata())
1629     return;
1630   if (auto *L = LocalAsMetadata::getIfExists(V))
1631     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1632       for (User *U : MDV->users())
1633         if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
1634           DbgValues.push_back(DVI);
1635 }
1636 
1637 void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
1638                         Value *V) {
1639   // This function is hot. Check whether the value has any metadata to avoid a
1640   // DenseMap lookup.
1641   if (!V->isUsedByMetadata())
1642     return;
1643   if (auto *L = LocalAsMetadata::getIfExists(V))
1644     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1645       for (User *U : MDV->users())
1646         if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
1647           DbgUsers.push_back(DII);
1648 }
1649 
1650 bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
1651                              DIBuilder &Builder, uint8_t DIExprFlags,
1652                              int Offset) {
1653   auto DbgAddrs = FindDbgAddrUses(Address);
1654   for (DbgVariableIntrinsic *DII : DbgAddrs) {
1655     DebugLoc Loc = DII->getDebugLoc();
1656     auto *DIVar = DII->getVariable();
1657     auto *DIExpr = DII->getExpression();
1658     assert(DIVar && "Missing variable");
1659     DIExpr = DIExpression::prepend(DIExpr, DIExprFlags, Offset);
1660     // Insert llvm.dbg.declare immediately before DII, and remove old
1661     // llvm.dbg.declare.
1662     Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, DII);
1663     DII->eraseFromParent();
1664   }
1665   return !DbgAddrs.empty();
1666 }
1667 
1668 static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
1669                                         DIBuilder &Builder, int Offset) {
1670   DebugLoc Loc = DVI->getDebugLoc();
1671   auto *DIVar = DVI->getVariable();
1672   auto *DIExpr = DVI->getExpression();
1673   assert(DIVar && "Missing variable");
1674 
1675   // This is an alloca-based llvm.dbg.value. The first thing it should do with
1676   // the alloca pointer is dereference it. Otherwise we don't know how to handle
1677   // it and give up.
1678   if (!DIExpr || DIExpr->getNumElements() < 1 ||
1679       DIExpr->getElement(0) != dwarf::DW_OP_deref)
1680     return;
1681 
1682   // Insert the offset before the first deref.
1683   // We could just change the offset argument of dbg.value, but it's unsigned...
1684   if (Offset)
1685     DIExpr = DIExpression::prepend(DIExpr, 0, Offset);
1686 
1687   Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI);
1688   DVI->eraseFromParent();
1689 }
1690 
1691 void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1692                                     DIBuilder &Builder, int Offset) {
1693   if (auto *L = LocalAsMetadata::getIfExists(AI))
1694     if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
1695       for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
1696         Use &U = *UI++;
1697         if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
1698           replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
1699       }
1700 }
1701 
1702 /// Wrap \p V in a ValueAsMetadata instance.
1703 static MetadataAsValue *wrapValueInMetadata(LLVMContext &C, Value *V) {
1704   return MetadataAsValue::get(C, ValueAsMetadata::get(V));
1705 }
1706 
1707 /// Where possible to salvage debug information for \p I do so
1708 /// and return True. If not possible mark undef and return False.
1709 void llvm::salvageDebugInfo(Instruction &I) {
1710   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
1711   findDbgUsers(DbgUsers, &I);
1712   salvageDebugInfoForDbgValues(I, DbgUsers);
1713 }
1714 
1715 void llvm::salvageDebugInfoForDbgValues(
1716     Instruction &I, ArrayRef<DbgVariableIntrinsic *> DbgUsers) {
1717   auto &Ctx = I.getContext();
1718   bool Salvaged = false;
1719   auto wrapMD = [&](Value *V) { return wrapValueInMetadata(Ctx, V); };
1720 
1721   for (auto *DII : DbgUsers) {
1722     // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
1723     // are implicitly pointing out the value as a DWARF memory location
1724     // description.
1725     bool StackValue = isa<DbgValueInst>(DII);
1726 
1727     DIExpression *DIExpr =
1728         salvageDebugInfoImpl(I, DII->getExpression(), StackValue);
1729 
1730     // salvageDebugInfoImpl should fail on examining the first element of
1731     // DbgUsers, or none of them.
1732     if (!DIExpr)
1733       break;
1734 
1735     DII->setOperand(0, wrapMD(I.getOperand(0)));
1736     DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr));
1737     LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
1738     Salvaged = true;
1739   }
1740 
1741   if (Salvaged)
1742     return;
1743 
1744   for (auto *DII : DbgUsers) {
1745     Value *Undef = UndefValue::get(I.getType());
1746     DII->setOperand(0, MetadataAsValue::get(DII->getContext(),
1747                                             ValueAsMetadata::get(Undef)));
1748   }
1749 }
1750 
1751 DIExpression *llvm::salvageDebugInfoImpl(Instruction &I,
1752                                          DIExpression *SrcDIExpr,
1753                                          bool WithStackValue) {
1754   auto &M = *I.getModule();
1755   auto &DL = M.getDataLayout();
1756 
1757   // Apply a vector of opcodes to the source DIExpression.
1758   auto doSalvage = [&](SmallVectorImpl<uint64_t> &Ops) -> DIExpression * {
1759     DIExpression *DIExpr = SrcDIExpr;
1760     if (!Ops.empty()) {
1761       DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
1762     }
1763     return DIExpr;
1764   };
1765 
1766   // Apply the given offset to the source DIExpression.
1767   auto applyOffset = [&](uint64_t Offset) -> DIExpression * {
1768     SmallVector<uint64_t, 8> Ops;
1769     DIExpression::appendOffset(Ops, Offset);
1770     return doSalvage(Ops);
1771   };
1772 
1773   // initializer-list helper for applying operators to the source DIExpression.
1774   auto applyOps = [&](ArrayRef<uint64_t> Opcodes) -> DIExpression * {
1775     SmallVector<uint64_t, 8> Ops(Opcodes.begin(), Opcodes.end());
1776     return doSalvage(Ops);
1777   };
1778 
1779   if (auto *CI = dyn_cast<CastInst>(&I)) {
1780     // No-op casts are irrelevant for debug info.
1781     if (CI->isNoopCast(DL))
1782       return SrcDIExpr;
1783 
1784     Type *Type = CI->getType();
1785     // Casts other than Trunc, SExt, or ZExt to scalar types cannot be salvaged.
1786     if (Type->isVectorTy() ||
1787         !(isa<TruncInst>(&I) || isa<SExtInst>(&I) || isa<ZExtInst>(&I)))
1788       return nullptr;
1789 
1790     Value *FromValue = CI->getOperand(0);
1791     unsigned FromTypeBitSize = FromValue->getType()->getScalarSizeInBits();
1792     unsigned ToTypeBitSize = Type->getScalarSizeInBits();
1793 
1794     return applyOps(DIExpression::getExtOps(FromTypeBitSize, ToTypeBitSize,
1795                                             isa<SExtInst>(&I)));
1796   }
1797 
1798   if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1799     unsigned BitWidth =
1800         M.getDataLayout().getIndexSizeInBits(GEP->getPointerAddressSpace());
1801     // Rewrite a constant GEP into a DIExpression.
1802     APInt Offset(BitWidth, 0);
1803     if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset)) {
1804       return applyOffset(Offset.getSExtValue());
1805     } else {
1806       return nullptr;
1807     }
1808   } else if (auto *BI = dyn_cast<BinaryOperator>(&I)) {
1809     // Rewrite binary operations with constant integer operands.
1810     auto *ConstInt = dyn_cast<ConstantInt>(I.getOperand(1));
1811     if (!ConstInt || ConstInt->getBitWidth() > 64)
1812       return nullptr;
1813 
1814     uint64_t Val = ConstInt->getSExtValue();
1815     switch (BI->getOpcode()) {
1816     case Instruction::Add:
1817       return applyOffset(Val);
1818     case Instruction::Sub:
1819       return applyOffset(-int64_t(Val));
1820     case Instruction::Mul:
1821       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mul});
1822     case Instruction::SDiv:
1823       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_div});
1824     case Instruction::SRem:
1825       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mod});
1826     case Instruction::Or:
1827       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_or});
1828     case Instruction::And:
1829       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_and});
1830     case Instruction::Xor:
1831       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_xor});
1832     case Instruction::Shl:
1833       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shl});
1834     case Instruction::LShr:
1835       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shr});
1836     case Instruction::AShr:
1837       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shra});
1838     default:
1839       // TODO: Salvage constants from each kind of binop we know about.
1840       return nullptr;
1841     }
1842     // *Not* to do: we should not attempt to salvage load instructions,
1843     // because the validity and lifetime of a dbg.value containing
1844     // DW_OP_deref becomes difficult to analyze. See PR40628 for examples.
1845   }
1846   return nullptr;
1847 }
1848 
1849 /// A replacement for a dbg.value expression.
1850 using DbgValReplacement = Optional<DIExpression *>;
1851 
1852 /// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
1853 /// possibly moving/undefing users to prevent use-before-def. Returns true if
1854 /// changes are made.
1855 static bool rewriteDebugUsers(
1856     Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
1857     function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr) {
1858   // Find debug users of From.
1859   SmallVector<DbgVariableIntrinsic *, 1> Users;
1860   findDbgUsers(Users, &From);
1861   if (Users.empty())
1862     return false;
1863 
1864   // Prevent use-before-def of To.
1865   bool Changed = false;
1866   SmallPtrSet<DbgVariableIntrinsic *, 1> UndefOrSalvage;
1867   if (isa<Instruction>(&To)) {
1868     bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
1869 
1870     for (auto *DII : Users) {
1871       // It's common to see a debug user between From and DomPoint. Move it
1872       // after DomPoint to preserve the variable update without any reordering.
1873       if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
1874         LLVM_DEBUG(dbgs() << "MOVE:  " << *DII << '\n');
1875         DII->moveAfter(&DomPoint);
1876         Changed = true;
1877 
1878       // Users which otherwise aren't dominated by the replacement value must
1879       // be salvaged or deleted.
1880       } else if (!DT.dominates(&DomPoint, DII)) {
1881         UndefOrSalvage.insert(DII);
1882       }
1883     }
1884   }
1885 
1886   // Update debug users without use-before-def risk.
1887   for (auto *DII : Users) {
1888     if (UndefOrSalvage.count(DII))
1889       continue;
1890 
1891     LLVMContext &Ctx = DII->getContext();
1892     DbgValReplacement DVR = RewriteExpr(*DII);
1893     if (!DVR)
1894       continue;
1895 
1896     DII->setOperand(0, wrapValueInMetadata(Ctx, &To));
1897     DII->setOperand(2, MetadataAsValue::get(Ctx, *DVR));
1898     LLVM_DEBUG(dbgs() << "REWRITE:  " << *DII << '\n');
1899     Changed = true;
1900   }
1901 
1902   if (!UndefOrSalvage.empty()) {
1903     // Try to salvage the remaining debug users.
1904     salvageDebugInfo(From);
1905     Changed = true;
1906   }
1907 
1908   return Changed;
1909 }
1910 
1911 /// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
1912 /// losslessly preserve the bits and semantics of the value. This predicate is
1913 /// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
1914 ///
1915 /// Note that Type::canLosslesslyBitCastTo is not suitable here because it
1916 /// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
1917 /// and also does not allow lossless pointer <-> integer conversions.
1918 static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
1919                                          Type *ToTy) {
1920   // Trivially compatible types.
1921   if (FromTy == ToTy)
1922     return true;
1923 
1924   // Handle compatible pointer <-> integer conversions.
1925   if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
1926     bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
1927     bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
1928                               !DL.isNonIntegralPointerType(ToTy);
1929     return SameSize && LosslessConversion;
1930   }
1931 
1932   // TODO: This is not exhaustive.
1933   return false;
1934 }
1935 
1936 bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
1937                                  Instruction &DomPoint, DominatorTree &DT) {
1938   // Exit early if From has no debug users.
1939   if (!From.isUsedByMetadata())
1940     return false;
1941 
1942   assert(&From != &To && "Can't replace something with itself");
1943 
1944   Type *FromTy = From.getType();
1945   Type *ToTy = To.getType();
1946 
1947   auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
1948     return DII.getExpression();
1949   };
1950 
1951   // Handle no-op conversions.
1952   Module &M = *From.getModule();
1953   const DataLayout &DL = M.getDataLayout();
1954   if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
1955     return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
1956 
1957   // Handle integer-to-integer widening and narrowing.
1958   // FIXME: Use DW_OP_convert when it's available everywhere.
1959   if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
1960     uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
1961     uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
1962     assert(FromBits != ToBits && "Unexpected no-op conversion");
1963 
1964     // When the width of the result grows, assume that a debugger will only
1965     // access the low `FromBits` bits when inspecting the source variable.
1966     if (FromBits < ToBits)
1967       return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
1968 
1969     // The width of the result has shrunk. Use sign/zero extension to describe
1970     // the source variable's high bits.
1971     auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
1972       DILocalVariable *Var = DII.getVariable();
1973 
1974       // Without knowing signedness, sign/zero extension isn't possible.
1975       auto Signedness = Var->getSignedness();
1976       if (!Signedness)
1977         return None;
1978 
1979       bool Signed = *Signedness == DIBasicType::Signedness::Signed;
1980       return DIExpression::appendExt(DII.getExpression(), ToBits, FromBits,
1981                                      Signed);
1982     };
1983     return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt);
1984   }
1985 
1986   // TODO: Floating-point conversions, vectors.
1987   return false;
1988 }
1989 
1990 std::pair<unsigned, unsigned>
1991 llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
1992   unsigned NumDeadInst = 0;
1993   unsigned NumDeadDbgInst = 0;
1994   // Delete the instructions backwards, as it has a reduced likelihood of
1995   // having to update as many def-use and use-def chains.
1996   Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1997   while (EndInst != &BB->front()) {
1998     // Delete the next to last instruction.
1999     Instruction *Inst = &*--EndInst->getIterator();
2000     if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
2001       Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
2002     if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
2003       EndInst = Inst;
2004       continue;
2005     }
2006     if (isa<DbgInfoIntrinsic>(Inst))
2007       ++NumDeadDbgInst;
2008     else
2009       ++NumDeadInst;
2010     Inst->eraseFromParent();
2011   }
2012   return {NumDeadInst, NumDeadDbgInst};
2013 }
2014 
2015 unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
2016                                    bool PreserveLCSSA, DomTreeUpdater *DTU,
2017                                    MemorySSAUpdater *MSSAU) {
2018   BasicBlock *BB = I->getParent();
2019   std::vector <DominatorTree::UpdateType> Updates;
2020 
2021   if (MSSAU)
2022     MSSAU->changeToUnreachable(I);
2023 
2024   // Loop over all of the successors, removing BB's entry from any PHI
2025   // nodes.
2026   if (DTU)
2027     Updates.reserve(BB->getTerminator()->getNumSuccessors());
2028   for (BasicBlock *Successor : successors(BB)) {
2029     Successor->removePredecessor(BB, PreserveLCSSA);
2030     if (DTU)
2031       Updates.push_back({DominatorTree::Delete, BB, Successor});
2032   }
2033   // Insert a call to llvm.trap right before this.  This turns the undefined
2034   // behavior into a hard fail instead of falling through into random code.
2035   if (UseLLVMTrap) {
2036     Function *TrapFn =
2037       Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
2038     CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
2039     CallTrap->setDebugLoc(I->getDebugLoc());
2040   }
2041   auto *UI = new UnreachableInst(I->getContext(), I);
2042   UI->setDebugLoc(I->getDebugLoc());
2043 
2044   // All instructions after this are dead.
2045   unsigned NumInstrsRemoved = 0;
2046   BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
2047   while (BBI != BBE) {
2048     if (!BBI->use_empty())
2049       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
2050     BB->getInstList().erase(BBI++);
2051     ++NumInstrsRemoved;
2052   }
2053   if (DTU)
2054     DTU->applyUpdatesPermissive(Updates);
2055   return NumInstrsRemoved;
2056 }
2057 
2058 CallInst *llvm::createCallMatchingInvoke(InvokeInst *II) {
2059   SmallVector<Value *, 8> Args(II->args());
2060   SmallVector<OperandBundleDef, 1> OpBundles;
2061   II->getOperandBundlesAsDefs(OpBundles);
2062   CallInst *NewCall = CallInst::Create(II->getFunctionType(),
2063                                        II->getCalledOperand(), Args, OpBundles);
2064   NewCall->setCallingConv(II->getCallingConv());
2065   NewCall->setAttributes(II->getAttributes());
2066   NewCall->setDebugLoc(II->getDebugLoc());
2067   NewCall->copyMetadata(*II);
2068 
2069   // If the invoke had profile metadata, try converting them for CallInst.
2070   uint64_t TotalWeight;
2071   if (NewCall->extractProfTotalWeight(TotalWeight)) {
2072     // Set the total weight if it fits into i32, otherwise reset.
2073     MDBuilder MDB(NewCall->getContext());
2074     auto NewWeights = uint32_t(TotalWeight) != TotalWeight
2075                           ? nullptr
2076                           : MDB.createBranchWeights({uint32_t(TotalWeight)});
2077     NewCall->setMetadata(LLVMContext::MD_prof, NewWeights);
2078   }
2079 
2080   return NewCall;
2081 }
2082 
2083 /// changeToCall - Convert the specified invoke into a normal call.
2084 void llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) {
2085   CallInst *NewCall = createCallMatchingInvoke(II);
2086   NewCall->takeName(II);
2087   NewCall->insertBefore(II);
2088   II->replaceAllUsesWith(NewCall);
2089 
2090   // Follow the call by a branch to the normal destination.
2091   BasicBlock *NormalDestBB = II->getNormalDest();
2092   BranchInst::Create(NormalDestBB, II);
2093 
2094   // Update PHI nodes in the unwind destination
2095   BasicBlock *BB = II->getParent();
2096   BasicBlock *UnwindDestBB = II->getUnwindDest();
2097   UnwindDestBB->removePredecessor(BB);
2098   II->eraseFromParent();
2099   if (DTU)
2100     DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDestBB}});
2101 }
2102 
2103 BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
2104                                                    BasicBlock *UnwindEdge) {
2105   BasicBlock *BB = CI->getParent();
2106 
2107   // Convert this function call into an invoke instruction.  First, split the
2108   // basic block.
2109   BasicBlock *Split =
2110       BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
2111 
2112   // Delete the unconditional branch inserted by splitBasicBlock
2113   BB->getInstList().pop_back();
2114 
2115   // Create the new invoke instruction.
2116   SmallVector<Value *, 8> InvokeArgs(CI->args());
2117   SmallVector<OperandBundleDef, 1> OpBundles;
2118 
2119   CI->getOperandBundlesAsDefs(OpBundles);
2120 
2121   // Note: we're round tripping operand bundles through memory here, and that
2122   // can potentially be avoided with a cleverer API design that we do not have
2123   // as of this time.
2124 
2125   InvokeInst *II =
2126       InvokeInst::Create(CI->getFunctionType(), CI->getCalledOperand(), Split,
2127                          UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);
2128   II->setDebugLoc(CI->getDebugLoc());
2129   II->setCallingConv(CI->getCallingConv());
2130   II->setAttributes(CI->getAttributes());
2131 
2132   // Make sure that anything using the call now uses the invoke!  This also
2133   // updates the CallGraph if present, because it uses a WeakTrackingVH.
2134   CI->replaceAllUsesWith(II);
2135 
2136   // Delete the original call
2137   Split->getInstList().pop_front();
2138   return Split;
2139 }
2140 
2141 static bool markAliveBlocks(Function &F,
2142                             SmallPtrSetImpl<BasicBlock *> &Reachable,
2143                             DomTreeUpdater *DTU = nullptr) {
2144   SmallVector<BasicBlock*, 128> Worklist;
2145   BasicBlock *BB = &F.front();
2146   Worklist.push_back(BB);
2147   Reachable.insert(BB);
2148   bool Changed = false;
2149   do {
2150     BB = Worklist.pop_back_val();
2151 
2152     // Do a quick scan of the basic block, turning any obviously unreachable
2153     // instructions into LLVM unreachable insts.  The instruction combining pass
2154     // canonicalizes unreachable insts into stores to null or undef.
2155     for (Instruction &I : *BB) {
2156       if (auto *CI = dyn_cast<CallInst>(&I)) {
2157         Value *Callee = CI->getCalledOperand();
2158         // Handle intrinsic calls.
2159         if (Function *F = dyn_cast<Function>(Callee)) {
2160           auto IntrinsicID = F->getIntrinsicID();
2161           // Assumptions that are known to be false are equivalent to
2162           // unreachable. Also, if the condition is undefined, then we make the
2163           // choice most beneficial to the optimizer, and choose that to also be
2164           // unreachable.
2165           if (IntrinsicID == Intrinsic::assume) {
2166             if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
2167               // Don't insert a call to llvm.trap right before the unreachable.
2168               changeToUnreachable(CI, false, false, DTU);
2169               Changed = true;
2170               break;
2171             }
2172           } else if (IntrinsicID == Intrinsic::experimental_guard) {
2173             // A call to the guard intrinsic bails out of the current
2174             // compilation unit if the predicate passed to it is false. If the
2175             // predicate is a constant false, then we know the guard will bail
2176             // out of the current compile unconditionally, so all code following
2177             // it is dead.
2178             //
2179             // Note: unlike in llvm.assume, it is not "obviously profitable" for
2180             // guards to treat `undef` as `false` since a guard on `undef` can
2181             // still be useful for widening.
2182             if (match(CI->getArgOperand(0), m_Zero()))
2183               if (!isa<UnreachableInst>(CI->getNextNode())) {
2184                 changeToUnreachable(CI->getNextNode(), /*UseLLVMTrap=*/false,
2185                                     false, DTU);
2186                 Changed = true;
2187                 break;
2188               }
2189           }
2190         } else if ((isa<ConstantPointerNull>(Callee) &&
2191                     !NullPointerIsDefined(CI->getFunction())) ||
2192                    isa<UndefValue>(Callee)) {
2193           changeToUnreachable(CI, /*UseLLVMTrap=*/false, false, DTU);
2194           Changed = true;
2195           break;
2196         }
2197         if (CI->doesNotReturn() && !CI->isMustTailCall()) {
2198           // If we found a call to a no-return function, insert an unreachable
2199           // instruction after it.  Make sure there isn't *already* one there
2200           // though.
2201           if (!isa<UnreachableInst>(CI->getNextNode())) {
2202             // Don't insert a call to llvm.trap right before the unreachable.
2203             changeToUnreachable(CI->getNextNode(), false, false, DTU);
2204             Changed = true;
2205           }
2206           break;
2207         }
2208       } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
2209         // Store to undef and store to null are undefined and used to signal
2210         // that they should be changed to unreachable by passes that can't
2211         // modify the CFG.
2212 
2213         // Don't touch volatile stores.
2214         if (SI->isVolatile()) continue;
2215 
2216         Value *Ptr = SI->getOperand(1);
2217 
2218         if (isa<UndefValue>(Ptr) ||
2219             (isa<ConstantPointerNull>(Ptr) &&
2220              !NullPointerIsDefined(SI->getFunction(),
2221                                    SI->getPointerAddressSpace()))) {
2222           changeToUnreachable(SI, true, false, DTU);
2223           Changed = true;
2224           break;
2225         }
2226       }
2227     }
2228 
2229     Instruction *Terminator = BB->getTerminator();
2230     if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
2231       // Turn invokes that call 'nounwind' functions into ordinary calls.
2232       Value *Callee = II->getCalledOperand();
2233       if ((isa<ConstantPointerNull>(Callee) &&
2234            !NullPointerIsDefined(BB->getParent())) ||
2235           isa<UndefValue>(Callee)) {
2236         changeToUnreachable(II, true, false, DTU);
2237         Changed = true;
2238       } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
2239         if (II->use_empty() && II->onlyReadsMemory()) {
2240           // jump to the normal destination branch.
2241           BasicBlock *NormalDestBB = II->getNormalDest();
2242           BasicBlock *UnwindDestBB = II->getUnwindDest();
2243           BranchInst::Create(NormalDestBB, II);
2244           UnwindDestBB->removePredecessor(II->getParent());
2245           II->eraseFromParent();
2246           if (DTU)
2247             DTU->applyUpdatesPermissive(
2248                 {{DominatorTree::Delete, BB, UnwindDestBB}});
2249         } else
2250           changeToCall(II, DTU);
2251         Changed = true;
2252       }
2253     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
2254       // Remove catchpads which cannot be reached.
2255       struct CatchPadDenseMapInfo {
2256         static CatchPadInst *getEmptyKey() {
2257           return DenseMapInfo<CatchPadInst *>::getEmptyKey();
2258         }
2259 
2260         static CatchPadInst *getTombstoneKey() {
2261           return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
2262         }
2263 
2264         static unsigned getHashValue(CatchPadInst *CatchPad) {
2265           return static_cast<unsigned>(hash_combine_range(
2266               CatchPad->value_op_begin(), CatchPad->value_op_end()));
2267         }
2268 
2269         static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
2270           if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
2271               RHS == getEmptyKey() || RHS == getTombstoneKey())
2272             return LHS == RHS;
2273           return LHS->isIdenticalTo(RHS);
2274         }
2275       };
2276 
2277       // Set of unique CatchPads.
2278       SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
2279                     CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
2280           HandlerSet;
2281       detail::DenseSetEmpty Empty;
2282       for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
2283                                              E = CatchSwitch->handler_end();
2284            I != E; ++I) {
2285         BasicBlock *HandlerBB = *I;
2286         auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
2287         if (!HandlerSet.insert({CatchPad, Empty}).second) {
2288           CatchSwitch->removeHandler(I);
2289           --I;
2290           --E;
2291           Changed = true;
2292         }
2293       }
2294     }
2295 
2296     Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
2297     for (BasicBlock *Successor : successors(BB))
2298       if (Reachable.insert(Successor).second)
2299         Worklist.push_back(Successor);
2300   } while (!Worklist.empty());
2301   return Changed;
2302 }
2303 
2304 void llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
2305   Instruction *TI = BB->getTerminator();
2306 
2307   if (auto *II = dyn_cast<InvokeInst>(TI)) {
2308     changeToCall(II, DTU);
2309     return;
2310   }
2311 
2312   Instruction *NewTI;
2313   BasicBlock *UnwindDest;
2314 
2315   if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
2316     NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
2317     UnwindDest = CRI->getUnwindDest();
2318   } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
2319     auto *NewCatchSwitch = CatchSwitchInst::Create(
2320         CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
2321         CatchSwitch->getName(), CatchSwitch);
2322     for (BasicBlock *PadBB : CatchSwitch->handlers())
2323       NewCatchSwitch->addHandler(PadBB);
2324 
2325     NewTI = NewCatchSwitch;
2326     UnwindDest = CatchSwitch->getUnwindDest();
2327   } else {
2328     llvm_unreachable("Could not find unwind successor");
2329   }
2330 
2331   NewTI->takeName(TI);
2332   NewTI->setDebugLoc(TI->getDebugLoc());
2333   UnwindDest->removePredecessor(BB);
2334   TI->replaceAllUsesWith(NewTI);
2335   TI->eraseFromParent();
2336   if (DTU)
2337     DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDest}});
2338 }
2339 
2340 /// removeUnreachableBlocks - Remove blocks that are not reachable, even
2341 /// if they are in a dead cycle.  Return true if a change was made, false
2342 /// otherwise.
2343 bool llvm::removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
2344                                    MemorySSAUpdater *MSSAU) {
2345   SmallPtrSet<BasicBlock *, 16> Reachable;
2346   bool Changed = markAliveBlocks(F, Reachable, DTU);
2347 
2348   // If there are unreachable blocks in the CFG...
2349   if (Reachable.size() == F.size())
2350     return Changed;
2351 
2352   assert(Reachable.size() < F.size());
2353   NumRemoved += F.size() - Reachable.size();
2354 
2355   SmallSetVector<BasicBlock *, 8> DeadBlockSet;
2356   for (BasicBlock &BB : F) {
2357     // Skip reachable basic blocks
2358     if (Reachable.count(&BB))
2359       continue;
2360     DeadBlockSet.insert(&BB);
2361   }
2362 
2363   if (MSSAU)
2364     MSSAU->removeBlocks(DeadBlockSet);
2365 
2366   // Loop over all of the basic blocks that are not reachable, dropping all of
2367   // their internal references. Update DTU if available.
2368   std::vector<DominatorTree::UpdateType> Updates;
2369   for (auto *BB : DeadBlockSet) {
2370     for (BasicBlock *Successor : successors(BB)) {
2371       if (!DeadBlockSet.count(Successor))
2372         Successor->removePredecessor(BB);
2373       if (DTU)
2374         Updates.push_back({DominatorTree::Delete, BB, Successor});
2375     }
2376     BB->dropAllReferences();
2377     if (DTU) {
2378       Instruction *TI = BB->getTerminator();
2379       assert(TI && "Basic block should have a terminator");
2380       // Terminators like invoke can have users. We have to replace their users,
2381       // before removing them.
2382       if (!TI->use_empty())
2383         TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
2384       TI->eraseFromParent();
2385       new UnreachableInst(BB->getContext(), BB);
2386       assert(succ_empty(BB) && "The successor list of BB isn't empty before "
2387                                "applying corresponding DTU updates.");
2388     }
2389   }
2390 
2391   if (DTU) {
2392     DTU->applyUpdatesPermissive(Updates);
2393     bool Deleted = false;
2394     for (auto *BB : DeadBlockSet) {
2395       if (DTU->isBBPendingDeletion(BB))
2396         --NumRemoved;
2397       else
2398         Deleted = true;
2399       DTU->deleteBB(BB);
2400     }
2401     if (!Deleted)
2402       return false;
2403   } else {
2404     for (auto *BB : DeadBlockSet)
2405       BB->eraseFromParent();
2406   }
2407 
2408   return true;
2409 }
2410 
2411 void llvm::combineMetadata(Instruction *K, const Instruction *J,
2412                            ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
2413   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
2414   K->dropUnknownNonDebugMetadata(KnownIDs);
2415   K->getAllMetadataOtherThanDebugLoc(Metadata);
2416   for (const auto &MD : Metadata) {
2417     unsigned Kind = MD.first;
2418     MDNode *JMD = J->getMetadata(Kind);
2419     MDNode *KMD = MD.second;
2420 
2421     switch (Kind) {
2422       default:
2423         K->setMetadata(Kind, nullptr); // Remove unknown metadata
2424         break;
2425       case LLVMContext::MD_dbg:
2426         llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
2427       case LLVMContext::MD_tbaa:
2428         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2429         break;
2430       case LLVMContext::MD_alias_scope:
2431         K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
2432         break;
2433       case LLVMContext::MD_noalias:
2434       case LLVMContext::MD_mem_parallel_loop_access:
2435         K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
2436         break;
2437       case LLVMContext::MD_access_group:
2438         K->setMetadata(LLVMContext::MD_access_group,
2439                        intersectAccessGroups(K, J));
2440         break;
2441       case LLVMContext::MD_range:
2442 
2443         // If K does move, use most generic range. Otherwise keep the range of
2444         // K.
2445         if (DoesKMove)
2446           // FIXME: If K does move, we should drop the range info and nonnull.
2447           //        Currently this function is used with DoesKMove in passes
2448           //        doing hoisting/sinking and the current behavior of using the
2449           //        most generic range is correct in those cases.
2450           K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
2451         break;
2452       case LLVMContext::MD_fpmath:
2453         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2454         break;
2455       case LLVMContext::MD_invariant_load:
2456         // Only set the !invariant.load if it is present in both instructions.
2457         K->setMetadata(Kind, JMD);
2458         break;
2459       case LLVMContext::MD_nonnull:
2460         // If K does move, keep nonull if it is present in both instructions.
2461         if (DoesKMove)
2462           K->setMetadata(Kind, JMD);
2463         break;
2464       case LLVMContext::MD_invariant_group:
2465         // Preserve !invariant.group in K.
2466         break;
2467       case LLVMContext::MD_align:
2468         K->setMetadata(Kind,
2469           MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2470         break;
2471       case LLVMContext::MD_dereferenceable:
2472       case LLVMContext::MD_dereferenceable_or_null:
2473         K->setMetadata(Kind,
2474           MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2475         break;
2476       case LLVMContext::MD_preserve_access_index:
2477         // Preserve !preserve.access.index in K.
2478         break;
2479     }
2480   }
2481   // Set !invariant.group from J if J has it. If both instructions have it
2482   // then we will just pick it from J - even when they are different.
2483   // Also make sure that K is load or store - f.e. combining bitcast with load
2484   // could produce bitcast with invariant.group metadata, which is invalid.
2485   // FIXME: we should try to preserve both invariant.group md if they are
2486   // different, but right now instruction can only have one invariant.group.
2487   if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
2488     if (isa<LoadInst>(K) || isa<StoreInst>(K))
2489       K->setMetadata(LLVMContext::MD_invariant_group, JMD);
2490 }
2491 
2492 void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
2493                                  bool KDominatesJ) {
2494   unsigned KnownIDs[] = {
2495       LLVMContext::MD_tbaa,            LLVMContext::MD_alias_scope,
2496       LLVMContext::MD_noalias,         LLVMContext::MD_range,
2497       LLVMContext::MD_invariant_load,  LLVMContext::MD_nonnull,
2498       LLVMContext::MD_invariant_group, LLVMContext::MD_align,
2499       LLVMContext::MD_dereferenceable,
2500       LLVMContext::MD_dereferenceable_or_null,
2501       LLVMContext::MD_access_group,    LLVMContext::MD_preserve_access_index};
2502   combineMetadata(K, J, KnownIDs, KDominatesJ);
2503 }
2504 
2505 void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) {
2506   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
2507   Source.getAllMetadata(MD);
2508   MDBuilder MDB(Dest.getContext());
2509   Type *NewType = Dest.getType();
2510   const DataLayout &DL = Source.getModule()->getDataLayout();
2511   for (const auto &MDPair : MD) {
2512     unsigned ID = MDPair.first;
2513     MDNode *N = MDPair.second;
2514     // Note, essentially every kind of metadata should be preserved here! This
2515     // routine is supposed to clone a load instruction changing *only its type*.
2516     // The only metadata it makes sense to drop is metadata which is invalidated
2517     // when the pointer type changes. This should essentially never be the case
2518     // in LLVM, but we explicitly switch over only known metadata to be
2519     // conservatively correct. If you are adding metadata to LLVM which pertains
2520     // to loads, you almost certainly want to add it here.
2521     switch (ID) {
2522     case LLVMContext::MD_dbg:
2523     case LLVMContext::MD_tbaa:
2524     case LLVMContext::MD_prof:
2525     case LLVMContext::MD_fpmath:
2526     case LLVMContext::MD_tbaa_struct:
2527     case LLVMContext::MD_invariant_load:
2528     case LLVMContext::MD_alias_scope:
2529     case LLVMContext::MD_noalias:
2530     case LLVMContext::MD_nontemporal:
2531     case LLVMContext::MD_mem_parallel_loop_access:
2532     case LLVMContext::MD_access_group:
2533       // All of these directly apply.
2534       Dest.setMetadata(ID, N);
2535       break;
2536 
2537     case LLVMContext::MD_nonnull:
2538       copyNonnullMetadata(Source, N, Dest);
2539       break;
2540 
2541     case LLVMContext::MD_align:
2542     case LLVMContext::MD_dereferenceable:
2543     case LLVMContext::MD_dereferenceable_or_null:
2544       // These only directly apply if the new type is also a pointer.
2545       if (NewType->isPointerTy())
2546         Dest.setMetadata(ID, N);
2547       break;
2548 
2549     case LLVMContext::MD_range:
2550       copyRangeMetadata(DL, Source, N, Dest);
2551       break;
2552     }
2553   }
2554 }
2555 
2556 void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
2557   auto *ReplInst = dyn_cast<Instruction>(Repl);
2558   if (!ReplInst)
2559     return;
2560 
2561   // Patch the replacement so that it is not more restrictive than the value
2562   // being replaced.
2563   // Note that if 'I' is a load being replaced by some operation,
2564   // for example, by an arithmetic operation, then andIRFlags()
2565   // would just erase all math flags from the original arithmetic
2566   // operation, which is clearly not wanted and not needed.
2567   if (!isa<LoadInst>(I))
2568     ReplInst->andIRFlags(I);
2569 
2570   // FIXME: If both the original and replacement value are part of the
2571   // same control-flow region (meaning that the execution of one
2572   // guarantees the execution of the other), then we can combine the
2573   // noalias scopes here and do better than the general conservative
2574   // answer used in combineMetadata().
2575 
2576   // In general, GVN unifies expressions over different control-flow
2577   // regions, and so we need a conservative combination of the noalias
2578   // scopes.
2579   static const unsigned KnownIDs[] = {
2580       LLVMContext::MD_tbaa,            LLVMContext::MD_alias_scope,
2581       LLVMContext::MD_noalias,         LLVMContext::MD_range,
2582       LLVMContext::MD_fpmath,          LLVMContext::MD_invariant_load,
2583       LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull,
2584       LLVMContext::MD_access_group,    LLVMContext::MD_preserve_access_index};
2585   combineMetadata(ReplInst, I, KnownIDs, false);
2586 }
2587 
2588 template <typename RootType, typename DominatesFn>
2589 static unsigned replaceDominatedUsesWith(Value *From, Value *To,
2590                                          const RootType &Root,
2591                                          const DominatesFn &Dominates) {
2592   assert(From->getType() == To->getType());
2593 
2594   unsigned Count = 0;
2595   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2596        UI != UE;) {
2597     Use &U = *UI++;
2598     if (!Dominates(Root, U))
2599       continue;
2600     U.set(To);
2601     LLVM_DEBUG(dbgs() << "Replace dominated use of '" << From->getName()
2602                       << "' as " << *To << " in " << *U << "\n");
2603     ++Count;
2604   }
2605   return Count;
2606 }
2607 
2608 unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
2609    assert(From->getType() == To->getType());
2610    auto *BB = From->getParent();
2611    unsigned Count = 0;
2612 
2613   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2614        UI != UE;) {
2615     Use &U = *UI++;
2616     auto *I = cast<Instruction>(U.getUser());
2617     if (I->getParent() == BB)
2618       continue;
2619     U.set(To);
2620     ++Count;
2621   }
2622   return Count;
2623 }
2624 
2625 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2626                                         DominatorTree &DT,
2627                                         const BasicBlockEdge &Root) {
2628   auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
2629     return DT.dominates(Root, U);
2630   };
2631   return ::replaceDominatedUsesWith(From, To, Root, Dominates);
2632 }
2633 
2634 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2635                                         DominatorTree &DT,
2636                                         const BasicBlock *BB) {
2637   auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) {
2638     auto *I = cast<Instruction>(U.getUser())->getParent();
2639     return DT.properlyDominates(BB, I);
2640   };
2641   return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates);
2642 }
2643 
2644 bool llvm::callsGCLeafFunction(const CallBase *Call,
2645                                const TargetLibraryInfo &TLI) {
2646   // Check if the function is specifically marked as a gc leaf function.
2647   if (Call->hasFnAttr("gc-leaf-function"))
2648     return true;
2649   if (const Function *F = Call->getCalledFunction()) {
2650     if (F->hasFnAttribute("gc-leaf-function"))
2651       return true;
2652 
2653     if (auto IID = F->getIntrinsicID()) {
2654       // Most LLVM intrinsics do not take safepoints.
2655       return IID != Intrinsic::experimental_gc_statepoint &&
2656              IID != Intrinsic::experimental_deoptimize &&
2657              IID != Intrinsic::memcpy_element_unordered_atomic &&
2658              IID != Intrinsic::memmove_element_unordered_atomic;
2659     }
2660   }
2661 
2662   // Lib calls can be materialized by some passes, and won't be
2663   // marked as 'gc-leaf-function.' All available Libcalls are
2664   // GC-leaf.
2665   LibFunc LF;
2666   if (TLI.getLibFunc(*Call, LF)) {
2667     return TLI.has(LF);
2668   }
2669 
2670   return false;
2671 }
2672 
2673 void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
2674                                LoadInst &NewLI) {
2675   auto *NewTy = NewLI.getType();
2676 
2677   // This only directly applies if the new type is also a pointer.
2678   if (NewTy->isPointerTy()) {
2679     NewLI.setMetadata(LLVMContext::MD_nonnull, N);
2680     return;
2681   }
2682 
2683   // The only other translation we can do is to integral loads with !range
2684   // metadata.
2685   if (!NewTy->isIntegerTy())
2686     return;
2687 
2688   MDBuilder MDB(NewLI.getContext());
2689   const Value *Ptr = OldLI.getPointerOperand();
2690   auto *ITy = cast<IntegerType>(NewTy);
2691   auto *NullInt = ConstantExpr::getPtrToInt(
2692       ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
2693   auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
2694   NewLI.setMetadata(LLVMContext::MD_range,
2695                     MDB.createRange(NonNullInt, NullInt));
2696 }
2697 
2698 void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
2699                              MDNode *N, LoadInst &NewLI) {
2700   auto *NewTy = NewLI.getType();
2701 
2702   // Give up unless it is converted to a pointer where there is a single very
2703   // valuable mapping we can do reliably.
2704   // FIXME: It would be nice to propagate this in more ways, but the type
2705   // conversions make it hard.
2706   if (!NewTy->isPointerTy())
2707     return;
2708 
2709   unsigned BitWidth = DL.getPointerTypeSizeInBits(NewTy);
2710   if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
2711     MDNode *NN = MDNode::get(OldLI.getContext(), None);
2712     NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
2713   }
2714 }
2715 
2716 void llvm::dropDebugUsers(Instruction &I) {
2717   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
2718   findDbgUsers(DbgUsers, &I);
2719   for (auto *DII : DbgUsers)
2720     DII->eraseFromParent();
2721 }
2722 
2723 void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
2724                                     BasicBlock *BB) {
2725   // Since we are moving the instructions out of its basic block, we do not
2726   // retain their original debug locations (DILocations) and debug intrinsic
2727   // instructions.
2728   //
2729   // Doing so would degrade the debugging experience and adversely affect the
2730   // accuracy of profiling information.
2731   //
2732   // Currently, when hoisting the instructions, we take the following actions:
2733   // - Remove their debug intrinsic instructions.
2734   // - Set their debug locations to the values from the insertion point.
2735   //
2736   // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
2737   // need to be deleted, is because there will not be any instructions with a
2738   // DILocation in either branch left after performing the transformation. We
2739   // can only insert a dbg.value after the two branches are joined again.
2740   //
2741   // See PR38762, PR39243 for more details.
2742   //
2743   // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
2744   // encode predicated DIExpressions that yield different results on different
2745   // code paths.
2746   for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
2747     Instruction *I = &*II;
2748     I->dropUnknownNonDebugMetadata();
2749     if (I->isUsedByMetadata())
2750       dropDebugUsers(*I);
2751     if (isa<DbgInfoIntrinsic>(I)) {
2752       // Remove DbgInfo Intrinsics.
2753       II = I->eraseFromParent();
2754       continue;
2755     }
2756     I->setDebugLoc(InsertPt->getDebugLoc());
2757     ++II;
2758   }
2759   DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(),
2760                                  BB->begin(),
2761                                  BB->getTerminator()->getIterator());
2762 }
2763 
2764 namespace {
2765 
2766 /// A potential constituent of a bitreverse or bswap expression. See
2767 /// collectBitParts for a fuller explanation.
2768 struct BitPart {
2769   BitPart(Value *P, unsigned BW) : Provider(P) {
2770     Provenance.resize(BW);
2771   }
2772 
2773   /// The Value that this is a bitreverse/bswap of.
2774   Value *Provider;
2775 
2776   /// The "provenance" of each bit. Provenance[A] = B means that bit A
2777   /// in Provider becomes bit B in the result of this expression.
2778   SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
2779 
2780   enum { Unset = -1 };
2781 };
2782 
2783 } // end anonymous namespace
2784 
2785 /// Analyze the specified subexpression and see if it is capable of providing
2786 /// pieces of a bswap or bitreverse. The subexpression provides a potential
2787 /// piece of a bswap or bitreverse if it can be proved that each non-zero bit in
2788 /// the output of the expression came from a corresponding bit in some other
2789 /// value. This function is recursive, and the end result is a mapping of
2790 /// bitnumber to bitnumber. It is the caller's responsibility to validate that
2791 /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
2792 ///
2793 /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
2794 /// that the expression deposits the low byte of %X into the high byte of the
2795 /// result and that all other bits are zero. This expression is accepted and a
2796 /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
2797 /// [0-7].
2798 ///
2799 /// For vector types, all analysis is performed at the per-element level. No
2800 /// cross-element analysis is supported (shuffle/insertion/reduction), and all
2801 /// constant masks must be splatted across all elements.
2802 ///
2803 /// To avoid revisiting values, the BitPart results are memoized into the
2804 /// provided map. To avoid unnecessary copying of BitParts, BitParts are
2805 /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
2806 /// store BitParts objects, not pointers. As we need the concept of a nullptr
2807 /// BitParts (Value has been analyzed and the analysis failed), we an Optional
2808 /// type instead to provide the same functionality.
2809 ///
2810 /// Because we pass around references into \c BPS, we must use a container that
2811 /// does not invalidate internal references (std::map instead of DenseMap).
2812 static const Optional<BitPart> &
2813 collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
2814                 std::map<Value *, Optional<BitPart>> &BPS, int Depth) {
2815   auto I = BPS.find(V);
2816   if (I != BPS.end())
2817     return I->second;
2818 
2819   auto &Result = BPS[V] = None;
2820   auto BitWidth = V->getType()->getScalarSizeInBits();
2821 
2822   // Prevent stack overflow by limiting the recursion depth
2823   if (Depth == BitPartRecursionMaxDepth) {
2824     LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n");
2825     return Result;
2826   }
2827 
2828   if (auto *I = dyn_cast<Instruction>(V)) {
2829     Value *X, *Y;
2830     const APInt *C;
2831 
2832     // If this is an or instruction, it may be an inner node of the bswap.
2833     if (match(V, m_Or(m_Value(X), m_Value(Y)))) {
2834       const auto &A =
2835           collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS, Depth + 1);
2836       const auto &B =
2837           collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS, Depth + 1);
2838       if (!A || !B)
2839         return Result;
2840 
2841       // Try and merge the two together.
2842       if (!A->Provider || A->Provider != B->Provider)
2843         return Result;
2844 
2845       Result = BitPart(A->Provider, BitWidth);
2846       for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx) {
2847         if (A->Provenance[BitIdx] != BitPart::Unset &&
2848             B->Provenance[BitIdx] != BitPart::Unset &&
2849             A->Provenance[BitIdx] != B->Provenance[BitIdx])
2850           return Result = None;
2851 
2852         if (A->Provenance[BitIdx] == BitPart::Unset)
2853           Result->Provenance[BitIdx] = B->Provenance[BitIdx];
2854         else
2855           Result->Provenance[BitIdx] = A->Provenance[BitIdx];
2856       }
2857 
2858       return Result;
2859     }
2860 
2861     // If this is a logical shift by a constant, recurse then shift the result.
2862     if (match(V, m_LogicalShift(m_Value(X), m_APInt(C)))) {
2863       const APInt &BitShift = *C;
2864 
2865       // Ensure the shift amount is defined.
2866       if (BitShift.uge(BitWidth))
2867         return Result;
2868 
2869       const auto &Res =
2870           collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS, Depth + 1);
2871       if (!Res)
2872         return Result;
2873       Result = Res;
2874 
2875       // Perform the "shift" on BitProvenance.
2876       auto &P = Result->Provenance;
2877       if (I->getOpcode() == Instruction::Shl) {
2878         P.erase(std::prev(P.end(), BitShift.getZExtValue()), P.end());
2879         P.insert(P.begin(), BitShift.getZExtValue(), BitPart::Unset);
2880       } else {
2881         P.erase(P.begin(), std::next(P.begin(), BitShift.getZExtValue()));
2882         P.insert(P.end(), BitShift.getZExtValue(), BitPart::Unset);
2883       }
2884 
2885       return Result;
2886     }
2887 
2888     // If this is a logical 'and' with a mask that clears bits, recurse then
2889     // unset the appropriate bits.
2890     if (match(V, m_And(m_Value(X), m_APInt(C)))) {
2891       const APInt &AndMask = *C;
2892 
2893       // Check that the mask allows a multiple of 8 bits for a bswap, for an
2894       // early exit.
2895       unsigned NumMaskedBits = AndMask.countPopulation();
2896       if (!MatchBitReversals && (NumMaskedBits % 8) != 0)
2897         return Result;
2898 
2899       const auto &Res =
2900           collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS, Depth + 1);
2901       if (!Res)
2902         return Result;
2903       Result = Res;
2904 
2905       for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
2906         // If the AndMask is zero for this bit, clear the bit.
2907         if (AndMask[BitIdx] == 0)
2908           Result->Provenance[BitIdx] = BitPart::Unset;
2909       return Result;
2910     }
2911 
2912     // If this is a zext instruction zero extend the result.
2913     if (match(V, m_ZExt(m_Value(X)))) {
2914       const auto &Res =
2915           collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS, Depth + 1);
2916       if (!Res)
2917         return Result;
2918 
2919       Result = BitPart(Res->Provider, BitWidth);
2920       auto NarrowBitWidth = X->getType()->getScalarSizeInBits();
2921       for (unsigned BitIdx = 0; BitIdx < NarrowBitWidth; ++BitIdx)
2922         Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
2923       for (unsigned BitIdx = NarrowBitWidth; BitIdx < BitWidth; ++BitIdx)
2924         Result->Provenance[BitIdx] = BitPart::Unset;
2925       return Result;
2926     }
2927 
2928     // BITREVERSE - most likely due to us previous matching a partial
2929     // bitreverse.
2930     if (match(V, m_BitReverse(m_Value(X)))) {
2931       const auto &Res =
2932           collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS, Depth + 1);
2933       if (!Res)
2934         return Result;
2935 
2936       Result = BitPart(Res->Provider, BitWidth);
2937       for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
2938         Result->Provenance[(BitWidth - 1) - BitIdx] = Res->Provenance[BitIdx];
2939       return Result;
2940     }
2941 
2942     // BSWAP - most likely due to us previous matching a partial bswap.
2943     if (match(V, m_BSwap(m_Value(X)))) {
2944       const auto &Res =
2945           collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS, Depth + 1);
2946       if (!Res)
2947         return Result;
2948 
2949       unsigned ByteWidth = BitWidth / 8;
2950       Result = BitPart(Res->Provider, BitWidth);
2951       for (unsigned ByteIdx = 0; ByteIdx < ByteWidth; ++ByteIdx) {
2952         unsigned ByteBitOfs = ByteIdx * 8;
2953         for (unsigned BitIdx = 0; BitIdx < 8; ++BitIdx)
2954           Result->Provenance[(BitWidth - 8 - ByteBitOfs) + BitIdx] =
2955               Res->Provenance[ByteBitOfs + BitIdx];
2956       }
2957       return Result;
2958     }
2959 
2960     // Funnel 'double' shifts take 3 operands, 2 inputs and the shift
2961     // amount (modulo).
2962     // fshl(X,Y,Z): (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
2963     // fshr(X,Y,Z): (X << (BW - (Z % BW))) | (Y >> (Z % BW))
2964     if (match(V, m_FShl(m_Value(X), m_Value(Y), m_APInt(C))) ||
2965         match(V, m_FShr(m_Value(X), m_Value(Y), m_APInt(C)))) {
2966       // We can treat fshr as a fshl by flipping the modulo amount.
2967       unsigned ModAmt = C->urem(BitWidth);
2968       if (cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::fshr)
2969         ModAmt = BitWidth - ModAmt;
2970 
2971       const auto &LHS =
2972           collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS, Depth + 1);
2973       const auto &RHS =
2974           collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS, Depth + 1);
2975 
2976       // Check we have both sources and they are from the same provider.
2977       if (!LHS || !RHS || !LHS->Provider || LHS->Provider != RHS->Provider)
2978         return Result;
2979 
2980       unsigned StartBitRHS = BitWidth - ModAmt;
2981       Result = BitPart(LHS->Provider, BitWidth);
2982       for (unsigned BitIdx = 0; BitIdx < StartBitRHS; ++BitIdx)
2983         Result->Provenance[BitIdx + ModAmt] = LHS->Provenance[BitIdx];
2984       for (unsigned BitIdx = 0; BitIdx < ModAmt; ++BitIdx)
2985         Result->Provenance[BitIdx] = RHS->Provenance[BitIdx + StartBitRHS];
2986       return Result;
2987     }
2988   }
2989 
2990   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
2991   // the input value to the bswap/bitreverse.
2992   Result = BitPart(V, BitWidth);
2993   for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
2994     Result->Provenance[BitIdx] = BitIdx;
2995   return Result;
2996 }
2997 
2998 static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
2999                                           unsigned BitWidth) {
3000   if (From % 8 != To % 8)
3001     return false;
3002   // Convert from bit indices to byte indices and check for a byte reversal.
3003   From >>= 3;
3004   To >>= 3;
3005   BitWidth >>= 3;
3006   return From == BitWidth - To - 1;
3007 }
3008 
3009 static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
3010                                                unsigned BitWidth) {
3011   return From == BitWidth - To - 1;
3012 }
3013 
3014 bool llvm::recognizeBSwapOrBitReverseIdiom(
3015     Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
3016     SmallVectorImpl<Instruction *> &InsertedInsts) {
3017   if (Operator::getOpcode(I) != Instruction::Or)
3018     return false;
3019   if (!MatchBSwaps && !MatchBitReversals)
3020     return false;
3021   Type *ITy = I->getType();
3022   if (!ITy->isIntOrIntVectorTy() || ITy->getScalarSizeInBits() > 128)
3023     return false;  // Can't do integer/elements > 128 bits.
3024 
3025   Type *DemandedTy = ITy;
3026   if (I->hasOneUse())
3027     if (auto *Trunc = dyn_cast<TruncInst>(I->user_back()))
3028       DemandedTy = Trunc->getType();
3029 
3030   // Try to find all the pieces corresponding to the bswap.
3031   std::map<Value *, Optional<BitPart>> BPS;
3032   auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0);
3033   if (!Res)
3034     return false;
3035   ArrayRef<int8_t> BitProvenance = Res->Provenance;
3036   assert(all_of(BitProvenance,
3037                 [](int8_t I) { return I == BitPart::Unset || 0 <= I; }) &&
3038          "Illegal bit provenance index");
3039 
3040   // If the upper bits are zero, then attempt to perform as a truncated op.
3041   if (BitProvenance.back() == BitPart::Unset) {
3042     while (!BitProvenance.empty() && BitProvenance.back() == BitPart::Unset)
3043       BitProvenance = BitProvenance.drop_back();
3044     if (BitProvenance.empty())
3045       return false; // TODO - handle null value?
3046     DemandedTy = Type::getIntNTy(I->getContext(), BitProvenance.size());
3047     if (auto *IVecTy = dyn_cast<VectorType>(ITy))
3048       DemandedTy = VectorType::get(DemandedTy, IVecTy);
3049   }
3050 
3051   // Check BitProvenance hasn't found a source larger than the result type.
3052   unsigned DemandedBW = DemandedTy->getScalarSizeInBits();
3053   if (DemandedBW > ITy->getScalarSizeInBits())
3054     return false;
3055 
3056   // Now, is the bit permutation correct for a bswap or a bitreverse? We can
3057   // only byteswap values with an even number of bytes.
3058   APInt DemandedMask = APInt::getAllOnesValue(DemandedBW);
3059   bool OKForBSwap = MatchBSwaps && (DemandedBW % 16) == 0;
3060   bool OKForBitReverse = MatchBitReversals;
3061   for (unsigned BitIdx = 0;
3062        (BitIdx < DemandedBW) && (OKForBSwap || OKForBitReverse); ++BitIdx) {
3063     if (BitProvenance[BitIdx] == BitPart::Unset) {
3064       DemandedMask.clearBit(BitIdx);
3065       continue;
3066     }
3067     OKForBSwap &= bitTransformIsCorrectForBSwap(BitProvenance[BitIdx], BitIdx,
3068                                                 DemandedBW);
3069     OKForBitReverse &= bitTransformIsCorrectForBitReverse(BitProvenance[BitIdx],
3070                                                           BitIdx, DemandedBW);
3071   }
3072 
3073   Intrinsic::ID Intrin;
3074   if (OKForBSwap)
3075     Intrin = Intrinsic::bswap;
3076   else if (OKForBitReverse)
3077     Intrin = Intrinsic::bitreverse;
3078   else
3079     return false;
3080 
3081   Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
3082   Value *Provider = Res->Provider;
3083 
3084   // We may need to truncate the provider.
3085   if (DemandedTy != Provider->getType()) {
3086     auto *Trunc =
3087         CastInst::CreateIntegerCast(Provider, DemandedTy, false, "trunc", I);
3088     InsertedInsts.push_back(Trunc);
3089     Provider = Trunc;
3090   }
3091 
3092   Instruction *Result = CallInst::Create(F, Provider, "rev", I);
3093   InsertedInsts.push_back(Result);
3094 
3095   if (!DemandedMask.isAllOnesValue()) {
3096     auto *Mask = ConstantInt::get(DemandedTy, DemandedMask);
3097     Result = BinaryOperator::Create(Instruction::And, Result, Mask, "mask", I);
3098     InsertedInsts.push_back(Result);
3099   }
3100 
3101   // We may need to zeroextend back to the result type.
3102   if (ITy != Result->getType()) {
3103     auto *ExtInst = CastInst::CreateIntegerCast(Result, ITy, false, "zext", I);
3104     InsertedInsts.push_back(ExtInst);
3105   }
3106 
3107   return true;
3108 }
3109 
3110 // CodeGen has special handling for some string functions that may replace
3111 // them with target-specific intrinsics.  Since that'd skip our interceptors
3112 // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
3113 // we mark affected calls as NoBuiltin, which will disable optimization
3114 // in CodeGen.
3115 void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
3116     CallInst *CI, const TargetLibraryInfo *TLI) {
3117   Function *F = CI->getCalledFunction();
3118   LibFunc Func;
3119   if (F && !F->hasLocalLinkage() && F->hasName() &&
3120       TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
3121       !F->doesNotAccessMemory())
3122     CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
3123 }
3124 
3125 bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
3126   // We can't have a PHI with a metadata type.
3127   if (I->getOperand(OpIdx)->getType()->isMetadataTy())
3128     return false;
3129 
3130   // Early exit.
3131   if (!isa<Constant>(I->getOperand(OpIdx)))
3132     return true;
3133 
3134   switch (I->getOpcode()) {
3135   default:
3136     return true;
3137   case Instruction::Call:
3138   case Instruction::Invoke: {
3139     const auto &CB = cast<CallBase>(*I);
3140 
3141     // Can't handle inline asm. Skip it.
3142     if (CB.isInlineAsm())
3143       return false;
3144 
3145     // Constant bundle operands may need to retain their constant-ness for
3146     // correctness.
3147     if (CB.isBundleOperand(OpIdx))
3148       return false;
3149 
3150     if (OpIdx < CB.getNumArgOperands()) {
3151       // Some variadic intrinsics require constants in the variadic arguments,
3152       // which currently aren't markable as immarg.
3153       if (isa<IntrinsicInst>(CB) &&
3154           OpIdx >= CB.getFunctionType()->getNumParams()) {
3155         // This is known to be OK for stackmap.
3156         return CB.getIntrinsicID() == Intrinsic::experimental_stackmap;
3157       }
3158 
3159       // gcroot is a special case, since it requires a constant argument which
3160       // isn't also required to be a simple ConstantInt.
3161       if (CB.getIntrinsicID() == Intrinsic::gcroot)
3162         return false;
3163 
3164       // Some intrinsic operands are required to be immediates.
3165       return !CB.paramHasAttr(OpIdx, Attribute::ImmArg);
3166     }
3167 
3168     // It is never allowed to replace the call argument to an intrinsic, but it
3169     // may be possible for a call.
3170     return !isa<IntrinsicInst>(CB);
3171   }
3172   case Instruction::ShuffleVector:
3173     // Shufflevector masks are constant.
3174     return OpIdx != 2;
3175   case Instruction::Switch:
3176   case Instruction::ExtractValue:
3177     // All operands apart from the first are constant.
3178     return OpIdx == 0;
3179   case Instruction::InsertValue:
3180     // All operands apart from the first and the second are constant.
3181     return OpIdx < 2;
3182   case Instruction::Alloca:
3183     // Static allocas (constant size in the entry block) are handled by
3184     // prologue/epilogue insertion so they're free anyway. We definitely don't
3185     // want to make them non-constant.
3186     return !cast<AllocaInst>(I)->isStaticAlloca();
3187   case Instruction::GetElementPtr:
3188     if (OpIdx == 0)
3189       return true;
3190     gep_type_iterator It = gep_type_begin(I);
3191     for (auto E = std::next(It, OpIdx); It != E; ++It)
3192       if (It.isStruct())
3193         return false;
3194     return true;
3195   }
3196 }
3197 
3198 Value *llvm::invertCondition(Value *Condition) {
3199   // First: Check if it's a constant
3200   if (Constant *C = dyn_cast<Constant>(Condition))
3201     return ConstantExpr::getNot(C);
3202 
3203   // Second: If the condition is already inverted, return the original value
3204   Value *NotCondition;
3205   if (match(Condition, m_Not(m_Value(NotCondition))))
3206     return NotCondition;
3207 
3208   BasicBlock *Parent = nullptr;
3209   Instruction *Inst = dyn_cast<Instruction>(Condition);
3210   if (Inst)
3211     Parent = Inst->getParent();
3212   else if (Argument *Arg = dyn_cast<Argument>(Condition))
3213     Parent = &Arg->getParent()->getEntryBlock();
3214   assert(Parent && "Unsupported condition to invert");
3215 
3216   // Third: Check all the users for an invert
3217   for (User *U : Condition->users())
3218     if (Instruction *I = dyn_cast<Instruction>(U))
3219       if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
3220         return I;
3221 
3222   // Last option: Create a new instruction
3223   auto *Inverted =
3224       BinaryOperator::CreateNot(Condition, Condition->getName() + ".inv");
3225   if (Inst && !isa<PHINode>(Inst))
3226     Inverted->insertAfter(Inst);
3227   else
3228     Inverted->insertBefore(&*Parent->getFirstInsertionPt());
3229   return Inverted;
3230 }
3231