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