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