xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Utils/Local.cpp (revision 71ac745d76c3ba442e753daff1870893f272b29d)
10b57cec5SDimitry Andric //===- Local.cpp - Functions to perform local transformations -------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This family of functions perform various local transformations to the
100b57cec5SDimitry Andric // program.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
150b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
160b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
170b57cec5SDimitry Andric #include "llvm/ADT/DenseMapInfo.h"
180b57cec5SDimitry Andric #include "llvm/ADT/DenseSet.h"
190b57cec5SDimitry Andric #include "llvm/ADT/Hashing.h"
200b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
220b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
230b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
240b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
255ffd83dbSDimitry Andric #include "llvm/Analysis/AssumeBundleQueries.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
280b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
290b57cec5SDimitry Andric #include "llvm/Analysis/MemoryBuiltins.h"
300b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
310b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
320b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
330b57cec5SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
340b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
350b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
360b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
370b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
380b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
390b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
400b57cec5SDimitry Andric #include "llvm/IR/ConstantRange.h"
410b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
420b57cec5SDimitry Andric #include "llvm/IR/DIBuilder.h"
430b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
441fd87a68SDimitry Andric #include "llvm/IR/DebugInfo.h"
450b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
460b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
470b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
480b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
4906c3fb27SDimitry Andric #include "llvm/IR/EHPersonalities.h"
500b57cec5SDimitry Andric #include "llvm/IR/Function.h"
510b57cec5SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
520b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
530b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
540b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
550b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
560b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
570b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
580b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
59bdd1243dSDimitry Andric #include "llvm/IR/IntrinsicsWebAssembly.h"
600b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
610b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
620fca6ea1SDimitry Andric #include "llvm/IR/MemoryModelRelaxationAnnotations.h"
630b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
640b57cec5SDimitry Andric #include "llvm/IR/Module.h"
650b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h"
66bdd1243dSDimitry Andric #include "llvm/IR/ProfDataUtils.h"
670b57cec5SDimitry Andric #include "llvm/IR/Type.h"
680b57cec5SDimitry Andric #include "llvm/IR/Use.h"
690b57cec5SDimitry Andric #include "llvm/IR/User.h"
700b57cec5SDimitry Andric #include "llvm/IR/Value.h"
710b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h"
720b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
735f757f3fSDimitry Andric #include "llvm/Support/CommandLine.h"
740b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
750b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
760b57cec5SDimitry Andric #include "llvm/Support/KnownBits.h"
770b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
785ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
790b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
800b57cec5SDimitry Andric #include <algorithm>
810b57cec5SDimitry Andric #include <cassert>
820b57cec5SDimitry Andric #include <cstdint>
830b57cec5SDimitry Andric #include <iterator>
840b57cec5SDimitry Andric #include <map>
85bdd1243dSDimitry Andric #include <optional>
860b57cec5SDimitry Andric #include <utility>
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric using namespace llvm;
890b57cec5SDimitry Andric using namespace llvm::PatternMatch;
900b57cec5SDimitry Andric 
915f757f3fSDimitry Andric extern cl::opt<bool> UseNewDbgInfoFormat;
925f757f3fSDimitry Andric 
930b57cec5SDimitry Andric #define DEBUG_TYPE "local"
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
96e8d8bef9SDimitry Andric STATISTIC(NumPHICSEs, "Number of PHI's that got CSE'd");
97e8d8bef9SDimitry Andric 
98e8d8bef9SDimitry Andric static cl::opt<bool> PHICSEDebugHash(
99e8d8bef9SDimitry Andric     "phicse-debug-hash",
100e8d8bef9SDimitry Andric #ifdef EXPENSIVE_CHECKS
101e8d8bef9SDimitry Andric     cl::init(true),
102e8d8bef9SDimitry Andric #else
103e8d8bef9SDimitry Andric     cl::init(false),
104e8d8bef9SDimitry Andric #endif
105e8d8bef9SDimitry Andric     cl::Hidden,
106e8d8bef9SDimitry Andric     cl::desc("Perform extra assertion checking to verify that PHINodes's hash "
107e8d8bef9SDimitry Andric              "function is well-behaved w.r.t. its isEqual predicate"));
108e8d8bef9SDimitry Andric 
109e8d8bef9SDimitry Andric static cl::opt<unsigned> PHICSENumPHISmallSize(
110e8d8bef9SDimitry Andric     "phicse-num-phi-smallsize", cl::init(32), cl::Hidden,
111e8d8bef9SDimitry Andric     cl::desc(
112e8d8bef9SDimitry Andric         "When the basic block contains not more than this number of PHI nodes, "
113e8d8bef9SDimitry Andric         "perform a (faster!) exhaustive search instead of set-driven one."));
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric // Max recursion depth for collectBitParts used when detecting bswap and
116fe6060f1SDimitry Andric // bitreverse idioms.
117fe6060f1SDimitry Andric static const unsigned BitPartRecursionMaxDepth = 48;
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1200b57cec5SDimitry Andric //  Local constant propagation.
1210b57cec5SDimitry Andric //
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric /// ConstantFoldTerminator - If a terminator instruction is predicated on a
1240b57cec5SDimitry Andric /// constant value, convert it into an unconditional branch to the constant
1250b57cec5SDimitry Andric /// destination.  This is a nontrivial operation because the successors of this
1260b57cec5SDimitry Andric /// basic block must have their PHI nodes updated.
1270b57cec5SDimitry Andric /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
1280b57cec5SDimitry Andric /// conditions and indirectbr addresses this might make dead if
1290b57cec5SDimitry Andric /// DeleteDeadConditions is true.
1300b57cec5SDimitry Andric bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
1310b57cec5SDimitry Andric                                   const TargetLibraryInfo *TLI,
1320b57cec5SDimitry Andric                                   DomTreeUpdater *DTU) {
1330b57cec5SDimitry Andric   Instruction *T = BB->getTerminator();
1340b57cec5SDimitry Andric   IRBuilder<> Builder(T);
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric   // Branch - See if we are conditional jumping on constant
1370b57cec5SDimitry Andric   if (auto *BI = dyn_cast<BranchInst>(T)) {
1380b57cec5SDimitry Andric     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
139e8d8bef9SDimitry Andric 
1400b57cec5SDimitry Andric     BasicBlock *Dest1 = BI->getSuccessor(0);
1410b57cec5SDimitry Andric     BasicBlock *Dest2 = BI->getSuccessor(1);
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric     if (Dest2 == Dest1) {       // Conditional branch to same location?
1440b57cec5SDimitry Andric       // This branch matches something like this:
1450b57cec5SDimitry Andric       //     br bool %cond, label %Dest, label %Dest
1460b57cec5SDimitry Andric       // and changes it into:  br label %Dest
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric       // Let the basic block know that we are letting go of one copy of it.
1490b57cec5SDimitry Andric       assert(BI->getParent() && "Terminator not inserted in block!");
1500b57cec5SDimitry Andric       Dest1->removePredecessor(BI->getParent());
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric       // Replace the conditional branch with an unconditional one.
153fe6060f1SDimitry Andric       BranchInst *NewBI = Builder.CreateBr(Dest1);
154fe6060f1SDimitry Andric 
155fe6060f1SDimitry Andric       // Transfer the metadata to the new branch instruction.
156fe6060f1SDimitry Andric       NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
157fe6060f1SDimitry Andric                                 LLVMContext::MD_annotation});
158fe6060f1SDimitry Andric 
1590b57cec5SDimitry Andric       Value *Cond = BI->getCondition();
1600b57cec5SDimitry Andric       BI->eraseFromParent();
1610b57cec5SDimitry Andric       if (DeleteDeadConditions)
1620b57cec5SDimitry Andric         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
1630b57cec5SDimitry Andric       return true;
1640b57cec5SDimitry Andric     }
165e8d8bef9SDimitry Andric 
166e8d8bef9SDimitry Andric     if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
167e8d8bef9SDimitry Andric       // Are we branching on constant?
168e8d8bef9SDimitry Andric       // YES.  Change to unconditional branch...
169e8d8bef9SDimitry Andric       BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
170e8d8bef9SDimitry Andric       BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
171e8d8bef9SDimitry Andric 
172e8d8bef9SDimitry Andric       // Let the basic block know that we are letting go of it.  Based on this,
173e8d8bef9SDimitry Andric       // it will adjust it's PHI nodes.
174e8d8bef9SDimitry Andric       OldDest->removePredecessor(BB);
175e8d8bef9SDimitry Andric 
176e8d8bef9SDimitry Andric       // Replace the conditional branch with an unconditional one.
177fe6060f1SDimitry Andric       BranchInst *NewBI = Builder.CreateBr(Destination);
178fe6060f1SDimitry Andric 
179fe6060f1SDimitry Andric       // Transfer the metadata to the new branch instruction.
180fe6060f1SDimitry Andric       NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
181fe6060f1SDimitry Andric                                 LLVMContext::MD_annotation});
182fe6060f1SDimitry Andric 
183e8d8bef9SDimitry Andric       BI->eraseFromParent();
184e8d8bef9SDimitry Andric       if (DTU)
185e8d8bef9SDimitry Andric         DTU->applyUpdates({{DominatorTree::Delete, BB, OldDest}});
186e8d8bef9SDimitry Andric       return true;
187e8d8bef9SDimitry Andric     }
188e8d8bef9SDimitry Andric 
1890b57cec5SDimitry Andric     return false;
1900b57cec5SDimitry Andric   }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   if (auto *SI = dyn_cast<SwitchInst>(T)) {
1930b57cec5SDimitry Andric     // If we are switching on a constant, we can convert the switch to an
1940b57cec5SDimitry Andric     // unconditional branch.
1950b57cec5SDimitry Andric     auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
1960b57cec5SDimitry Andric     BasicBlock *DefaultDest = SI->getDefaultDest();
1970b57cec5SDimitry Andric     BasicBlock *TheOnlyDest = DefaultDest;
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric     // If the default is unreachable, ignore it when searching for TheOnlyDest.
2000b57cec5SDimitry Andric     if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
2010b57cec5SDimitry Andric         SI->getNumCases() > 0) {
2020b57cec5SDimitry Andric       TheOnlyDest = SI->case_begin()->getCaseSuccessor();
2030b57cec5SDimitry Andric     }
2040b57cec5SDimitry Andric 
205e8d8bef9SDimitry Andric     bool Changed = false;
206e8d8bef9SDimitry Andric 
2070b57cec5SDimitry Andric     // Figure out which case it goes to.
20806c3fb27SDimitry Andric     for (auto It = SI->case_begin(), End = SI->case_end(); It != End;) {
2090b57cec5SDimitry Andric       // Found case matching a constant operand?
21006c3fb27SDimitry Andric       if (It->getCaseValue() == CI) {
21106c3fb27SDimitry Andric         TheOnlyDest = It->getCaseSuccessor();
2120b57cec5SDimitry Andric         break;
2130b57cec5SDimitry Andric       }
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric       // Check to see if this branch is going to the same place as the default
2160b57cec5SDimitry Andric       // dest.  If so, eliminate it as an explicit compare.
21706c3fb27SDimitry Andric       if (It->getCaseSuccessor() == DefaultDest) {
218bdd1243dSDimitry Andric         MDNode *MD = getValidBranchWeightMDNode(*SI);
2190b57cec5SDimitry Andric         unsigned NCases = SI->getNumCases();
2200b57cec5SDimitry Andric         // Fold the case metadata into the default if there will be any branches
2210b57cec5SDimitry Andric         // left, unless the metadata doesn't match the switch.
222bdd1243dSDimitry Andric         if (NCases > 1 && MD) {
2230b57cec5SDimitry Andric           // Collect branch weights into a vector.
2240b57cec5SDimitry Andric           SmallVector<uint32_t, 8> Weights;
225bdd1243dSDimitry Andric           extractBranchWeights(MD, Weights);
226bdd1243dSDimitry Andric 
2270b57cec5SDimitry Andric           // Merge weight of this case to the default weight.
22806c3fb27SDimitry Andric           unsigned Idx = It->getCaseIndex();
229bdd1243dSDimitry Andric           // TODO: Add overflow check.
23006c3fb27SDimitry Andric           Weights[0] += Weights[Idx + 1];
2310b57cec5SDimitry Andric           // Remove weight for this case.
23206c3fb27SDimitry Andric           std::swap(Weights[Idx + 1], Weights.back());
2330b57cec5SDimitry Andric           Weights.pop_back();
2340fca6ea1SDimitry Andric           setBranchWeights(*SI, Weights, hasBranchWeightOrigin(MD));
2350b57cec5SDimitry Andric         }
2360b57cec5SDimitry Andric         // Remove this entry.
2370b57cec5SDimitry Andric         BasicBlock *ParentBB = SI->getParent();
2380b57cec5SDimitry Andric         DefaultDest->removePredecessor(ParentBB);
23906c3fb27SDimitry Andric         It = SI->removeCase(It);
24006c3fb27SDimitry Andric         End = SI->case_end();
241bdd1243dSDimitry Andric 
242bdd1243dSDimitry Andric         // Removing this case may have made the condition constant. In that
243bdd1243dSDimitry Andric         // case, update CI and restart iteration through the cases.
244bdd1243dSDimitry Andric         if (auto *NewCI = dyn_cast<ConstantInt>(SI->getCondition())) {
245bdd1243dSDimitry Andric           CI = NewCI;
24606c3fb27SDimitry Andric           It = SI->case_begin();
247bdd1243dSDimitry Andric         }
248bdd1243dSDimitry Andric 
249e8d8bef9SDimitry Andric         Changed = true;
2500b57cec5SDimitry Andric         continue;
2510b57cec5SDimitry Andric       }
2520b57cec5SDimitry Andric 
2530b57cec5SDimitry Andric       // Otherwise, check to see if the switch only branches to one destination.
2540b57cec5SDimitry Andric       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
2550b57cec5SDimitry Andric       // destinations.
25606c3fb27SDimitry Andric       if (It->getCaseSuccessor() != TheOnlyDest)
2570b57cec5SDimitry Andric         TheOnlyDest = nullptr;
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric       // Increment this iterator as we haven't removed the case.
26006c3fb27SDimitry Andric       ++It;
2610b57cec5SDimitry Andric     }
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric     if (CI && !TheOnlyDest) {
2640b57cec5SDimitry Andric       // Branching on a constant, but not any of the cases, go to the default
2650b57cec5SDimitry Andric       // successor.
2660b57cec5SDimitry Andric       TheOnlyDest = SI->getDefaultDest();
2670b57cec5SDimitry Andric     }
2680b57cec5SDimitry Andric 
2690b57cec5SDimitry Andric     // If we found a single destination that we can fold the switch into, do so
2700b57cec5SDimitry Andric     // now.
2710b57cec5SDimitry Andric     if (TheOnlyDest) {
2720b57cec5SDimitry Andric       // Insert the new branch.
2730b57cec5SDimitry Andric       Builder.CreateBr(TheOnlyDest);
2740b57cec5SDimitry Andric       BasicBlock *BB = SI->getParent();
275e8d8bef9SDimitry Andric 
276fe6060f1SDimitry Andric       SmallSet<BasicBlock *, 8> RemovedSuccessors;
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric       // Remove entries from PHI nodes which we no longer branch to...
279e8d8bef9SDimitry Andric       BasicBlock *SuccToKeep = TheOnlyDest;
2800b57cec5SDimitry Andric       for (BasicBlock *Succ : successors(SI)) {
281e8d8bef9SDimitry Andric         if (DTU && Succ != TheOnlyDest)
282e8d8bef9SDimitry Andric           RemovedSuccessors.insert(Succ);
2830b57cec5SDimitry Andric         // Found case matching a constant operand?
284e8d8bef9SDimitry Andric         if (Succ == SuccToKeep) {
285e8d8bef9SDimitry Andric           SuccToKeep = nullptr; // Don't modify the first branch to TheOnlyDest
2860b57cec5SDimitry Andric         } else {
2870b57cec5SDimitry Andric           Succ->removePredecessor(BB);
2880b57cec5SDimitry Andric         }
2890b57cec5SDimitry Andric       }
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric       // Delete the old switch.
2920b57cec5SDimitry Andric       Value *Cond = SI->getCondition();
2930b57cec5SDimitry Andric       SI->eraseFromParent();
2940b57cec5SDimitry Andric       if (DeleteDeadConditions)
2950b57cec5SDimitry Andric         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
296e8d8bef9SDimitry Andric       if (DTU) {
297e8d8bef9SDimitry Andric         std::vector<DominatorTree::UpdateType> Updates;
298e8d8bef9SDimitry Andric         Updates.reserve(RemovedSuccessors.size());
299e8d8bef9SDimitry Andric         for (auto *RemovedSuccessor : RemovedSuccessors)
300e8d8bef9SDimitry Andric           Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
301e8d8bef9SDimitry Andric         DTU->applyUpdates(Updates);
302e8d8bef9SDimitry Andric       }
3030b57cec5SDimitry Andric       return true;
3040b57cec5SDimitry Andric     }
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric     if (SI->getNumCases() == 1) {
3070b57cec5SDimitry Andric       // Otherwise, we can fold this switch into a conditional branch
3080b57cec5SDimitry Andric       // instruction if it has only one non-default destination.
3090b57cec5SDimitry Andric       auto FirstCase = *SI->case_begin();
3100b57cec5SDimitry Andric       Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
3110b57cec5SDimitry Andric           FirstCase.getCaseValue(), "cond");
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric       // Insert the new branch.
3140b57cec5SDimitry Andric       BranchInst *NewBr = Builder.CreateCondBr(Cond,
3150b57cec5SDimitry Andric                                                FirstCase.getCaseSuccessor(),
3160b57cec5SDimitry Andric                                                SI->getDefaultDest());
317bdd1243dSDimitry Andric       SmallVector<uint32_t> Weights;
318bdd1243dSDimitry Andric       if (extractBranchWeights(*SI, Weights) && Weights.size() == 2) {
319bdd1243dSDimitry Andric         uint32_t DefWeight = Weights[0];
320bdd1243dSDimitry Andric         uint32_t CaseWeight = Weights[1];
3210b57cec5SDimitry Andric         // The TrueWeight should be the weight for the single case of SI.
3220b57cec5SDimitry Andric         NewBr->setMetadata(LLVMContext::MD_prof,
323bdd1243dSDimitry Andric                            MDBuilder(BB->getContext())
324bdd1243dSDimitry Andric                                .createBranchWeights(CaseWeight, DefWeight));
3250b57cec5SDimitry Andric       }
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric       // Update make.implicit metadata to the newly-created conditional branch.
3280b57cec5SDimitry Andric       MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
3290b57cec5SDimitry Andric       if (MakeImplicitMD)
3300b57cec5SDimitry Andric         NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric       // Delete the old switch.
3330b57cec5SDimitry Andric       SI->eraseFromParent();
3340b57cec5SDimitry Andric       return true;
3350b57cec5SDimitry Andric     }
336e8d8bef9SDimitry Andric     return Changed;
3370b57cec5SDimitry Andric   }
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric   if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {
3400b57cec5SDimitry Andric     // indirectbr blockaddress(@F, @BB) -> br label @BB
3410b57cec5SDimitry Andric     if (auto *BA =
3420b57cec5SDimitry Andric           dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
3430b57cec5SDimitry Andric       BasicBlock *TheOnlyDest = BA->getBasicBlock();
344fe6060f1SDimitry Andric       SmallSet<BasicBlock *, 8> RemovedSuccessors;
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric       // Insert the new branch.
3470b57cec5SDimitry Andric       Builder.CreateBr(TheOnlyDest);
3480b57cec5SDimitry Andric 
349e8d8bef9SDimitry Andric       BasicBlock *SuccToKeep = TheOnlyDest;
3500b57cec5SDimitry Andric       for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
3510b57cec5SDimitry Andric         BasicBlock *DestBB = IBI->getDestination(i);
352e8d8bef9SDimitry Andric         if (DTU && DestBB != TheOnlyDest)
353e8d8bef9SDimitry Andric           RemovedSuccessors.insert(DestBB);
354e8d8bef9SDimitry Andric         if (IBI->getDestination(i) == SuccToKeep) {
355e8d8bef9SDimitry Andric           SuccToKeep = nullptr;
356e8d8bef9SDimitry Andric         } else {
357e8d8bef9SDimitry Andric           DestBB->removePredecessor(BB);
3580b57cec5SDimitry Andric         }
3590b57cec5SDimitry Andric       }
3600b57cec5SDimitry Andric       Value *Address = IBI->getAddress();
3610b57cec5SDimitry Andric       IBI->eraseFromParent();
3620b57cec5SDimitry Andric       if (DeleteDeadConditions)
3638bcb0991SDimitry Andric         // Delete pointer cast instructions.
3640b57cec5SDimitry Andric         RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
3650b57cec5SDimitry Andric 
3668bcb0991SDimitry Andric       // Also zap the blockaddress constant if there are no users remaining,
3678bcb0991SDimitry Andric       // otherwise the destination is still marked as having its address taken.
3688bcb0991SDimitry Andric       if (BA->use_empty())
3698bcb0991SDimitry Andric         BA->destroyConstant();
3708bcb0991SDimitry Andric 
3710b57cec5SDimitry Andric       // If we didn't find our destination in the IBI successor list, then we
3720b57cec5SDimitry Andric       // have undefined behavior.  Replace the unconditional branch with an
3730b57cec5SDimitry Andric       // 'unreachable' instruction.
374e8d8bef9SDimitry Andric       if (SuccToKeep) {
3750b57cec5SDimitry Andric         BB->getTerminator()->eraseFromParent();
3760b57cec5SDimitry Andric         new UnreachableInst(BB->getContext(), BB);
3770b57cec5SDimitry Andric       }
3780b57cec5SDimitry Andric 
379e8d8bef9SDimitry Andric       if (DTU) {
380e8d8bef9SDimitry Andric         std::vector<DominatorTree::UpdateType> Updates;
381e8d8bef9SDimitry Andric         Updates.reserve(RemovedSuccessors.size());
382e8d8bef9SDimitry Andric         for (auto *RemovedSuccessor : RemovedSuccessors)
383e8d8bef9SDimitry Andric           Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
384e8d8bef9SDimitry Andric         DTU->applyUpdates(Updates);
385e8d8bef9SDimitry Andric       }
3860b57cec5SDimitry Andric       return true;
3870b57cec5SDimitry Andric     }
3880b57cec5SDimitry Andric   }
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric   return false;
3910b57cec5SDimitry Andric }
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
3940b57cec5SDimitry Andric //  Local dead code elimination.
3950b57cec5SDimitry Andric //
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric /// isInstructionTriviallyDead - Return true if the result produced by the
3980b57cec5SDimitry Andric /// instruction is not used, and the instruction has no side effects.
3990b57cec5SDimitry Andric ///
4000b57cec5SDimitry Andric bool llvm::isInstructionTriviallyDead(Instruction *I,
4010b57cec5SDimitry Andric                                       const TargetLibraryInfo *TLI) {
4020b57cec5SDimitry Andric   if (!I->use_empty())
4030b57cec5SDimitry Andric     return false;
4040b57cec5SDimitry Andric   return wouldInstructionBeTriviallyDead(I, TLI);
4050b57cec5SDimitry Andric }
4060b57cec5SDimitry Andric 
4070eae32dcSDimitry Andric bool llvm::wouldInstructionBeTriviallyDeadOnUnusedPaths(
4080eae32dcSDimitry Andric     Instruction *I, const TargetLibraryInfo *TLI) {
4090eae32dcSDimitry Andric   // Instructions that are "markers" and have implied meaning on code around
4100eae32dcSDimitry Andric   // them (without explicit uses), are not dead on unused paths.
4110eae32dcSDimitry Andric   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
4120eae32dcSDimitry Andric     if (II->getIntrinsicID() == Intrinsic::stacksave ||
4130eae32dcSDimitry Andric         II->getIntrinsicID() == Intrinsic::launder_invariant_group ||
4140eae32dcSDimitry Andric         II->isLifetimeStartOrEnd())
4150eae32dcSDimitry Andric       return false;
4160eae32dcSDimitry Andric   return wouldInstructionBeTriviallyDead(I, TLI);
4170eae32dcSDimitry Andric }
4180eae32dcSDimitry Andric 
4195f757f3fSDimitry Andric bool llvm::wouldInstructionBeTriviallyDead(const Instruction *I,
4200b57cec5SDimitry Andric                                            const TargetLibraryInfo *TLI) {
4210b57cec5SDimitry Andric   if (I->isTerminator())
4220b57cec5SDimitry Andric     return false;
4230b57cec5SDimitry Andric 
4240b57cec5SDimitry Andric   // We don't want the landingpad-like instructions removed by anything this
4250b57cec5SDimitry Andric   // general.
4260b57cec5SDimitry Andric   if (I->isEHPad())
4270b57cec5SDimitry Andric     return false;
4280b57cec5SDimitry Andric 
42906c3fb27SDimitry Andric   // We don't want debug info removed by anything this general.
43006c3fb27SDimitry Andric   if (isa<DbgVariableIntrinsic>(I))
4310b57cec5SDimitry Andric     return false;
43206c3fb27SDimitry Andric 
4335f757f3fSDimitry Andric   if (const DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
4340b57cec5SDimitry Andric     if (DLI->getLabel())
4350b57cec5SDimitry Andric       return false;
4360b57cec5SDimitry Andric     return true;
4370b57cec5SDimitry Andric   }
4380b57cec5SDimitry Andric 
439fcaf7f86SDimitry Andric   if (auto *CB = dyn_cast<CallBase>(I))
440fcaf7f86SDimitry Andric     if (isRemovableAlloc(CB, TLI))
441fcaf7f86SDimitry Andric       return true;
442fcaf7f86SDimitry Andric 
443bdd1243dSDimitry Andric   if (!I->willReturn()) {
444bdd1243dSDimitry Andric     auto *II = dyn_cast<IntrinsicInst>(I);
445bdd1243dSDimitry Andric     if (!II)
446e8d8bef9SDimitry Andric       return false;
447e8d8bef9SDimitry Andric 
4485f757f3fSDimitry Andric     switch (II->getIntrinsicID()) {
4495f757f3fSDimitry Andric     case Intrinsic::experimental_guard: {
4505f757f3fSDimitry Andric       // Guards on true are operationally no-ops.  In the future we can
4515f757f3fSDimitry Andric       // consider more sophisticated tradeoffs for guards considering potential
4525f757f3fSDimitry Andric       // for check widening, but for now we keep things simple.
4535f757f3fSDimitry Andric       auto *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0));
4545f757f3fSDimitry Andric       return Cond && Cond->isOne();
4555f757f3fSDimitry Andric     }
456bdd1243dSDimitry Andric     // TODO: These intrinsics are not safe to remove, because this may remove
457bdd1243dSDimitry Andric     // a well-defined trap.
458bdd1243dSDimitry Andric     case Intrinsic::wasm_trunc_signed:
459bdd1243dSDimitry Andric     case Intrinsic::wasm_trunc_unsigned:
460bdd1243dSDimitry Andric     case Intrinsic::ptrauth_auth:
461bdd1243dSDimitry Andric     case Intrinsic::ptrauth_resign:
462bdd1243dSDimitry Andric       return true;
463bdd1243dSDimitry Andric     default:
464bdd1243dSDimitry Andric       return false;
465bdd1243dSDimitry Andric     }
466bdd1243dSDimitry Andric   }
467bdd1243dSDimitry Andric 
4680b57cec5SDimitry Andric   if (!I->mayHaveSideEffects())
4690b57cec5SDimitry Andric     return true;
4700b57cec5SDimitry Andric 
4710b57cec5SDimitry Andric   // Special case intrinsics that "may have side effects" but can be deleted
4720b57cec5SDimitry Andric   // when dead.
4735f757f3fSDimitry Andric   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
4740b57cec5SDimitry Andric     // Safe to delete llvm.stacksave and launder.invariant.group if dead.
4750b57cec5SDimitry Andric     if (II->getIntrinsicID() == Intrinsic::stacksave ||
4760b57cec5SDimitry Andric         II->getIntrinsicID() == Intrinsic::launder_invariant_group)
4770b57cec5SDimitry Andric       return true;
4780b57cec5SDimitry Andric 
4790fca6ea1SDimitry Andric     // Intrinsics declare sideeffects to prevent them from moving, but they are
4800fca6ea1SDimitry Andric     // nops without users.
4810fca6ea1SDimitry Andric     if (II->getIntrinsicID() == Intrinsic::allow_runtime_check ||
4820fca6ea1SDimitry Andric         II->getIntrinsicID() == Intrinsic::allow_ubsan_check)
4830fca6ea1SDimitry Andric       return true;
4840fca6ea1SDimitry Andric 
4855ffd83dbSDimitry Andric     if (II->isLifetimeStartOrEnd()) {
4865ffd83dbSDimitry Andric       auto *Arg = II->getArgOperand(1);
4870b57cec5SDimitry Andric       // Lifetime intrinsics are dead when their right-hand is undef.
4885ffd83dbSDimitry Andric       if (isa<UndefValue>(Arg))
4895ffd83dbSDimitry Andric         return true;
4905ffd83dbSDimitry Andric       // If the right-hand is an alloc, global, or argument and the only uses
4915ffd83dbSDimitry Andric       // are lifetime intrinsics then the intrinsics are dead.
4925ffd83dbSDimitry Andric       if (isa<AllocaInst>(Arg) || isa<GlobalValue>(Arg) || isa<Argument>(Arg))
4935ffd83dbSDimitry Andric         return llvm::all_of(Arg->uses(), [](Use &Use) {
4945ffd83dbSDimitry Andric           if (IntrinsicInst *IntrinsicUse =
4955ffd83dbSDimitry Andric                   dyn_cast<IntrinsicInst>(Use.getUser()))
4965ffd83dbSDimitry Andric             return IntrinsicUse->isLifetimeStartOrEnd();
4975ffd83dbSDimitry Andric           return false;
4985ffd83dbSDimitry Andric         });
4995ffd83dbSDimitry Andric       return false;
5005ffd83dbSDimitry Andric     }
5010b57cec5SDimitry Andric 
5025f757f3fSDimitry Andric     // Assumptions are dead if their condition is trivially true.
5035f757f3fSDimitry Andric     if (II->getIntrinsicID() == Intrinsic::assume &&
5045f757f3fSDimitry Andric         isAssumeWithEmptyBundle(cast<AssumeInst>(*II))) {
5050b57cec5SDimitry Andric       if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
5060b57cec5SDimitry Andric         return !Cond->isZero();
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric       return false;
5090b57cec5SDimitry Andric     }
510fe6060f1SDimitry Andric 
511fe6060f1SDimitry Andric     if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(I)) {
512bdd1243dSDimitry Andric       std::optional<fp::ExceptionBehavior> ExBehavior =
513bdd1243dSDimitry Andric           FPI->getExceptionBehavior();
51481ad6265SDimitry Andric       return *ExBehavior != fp::ebStrict;
515fe6060f1SDimitry Andric     }
5160b57cec5SDimitry Andric   }
5170b57cec5SDimitry Andric 
518fcaf7f86SDimitry Andric   if (auto *Call = dyn_cast<CallBase>(I)) {
519fcaf7f86SDimitry Andric     if (Value *FreedOp = getFreedOperand(Call, TLI))
520fcaf7f86SDimitry Andric       if (Constant *C = dyn_cast<Constant>(FreedOp))
5210b57cec5SDimitry Andric         return C->isNullValue() || isa<UndefValue>(C);
5220b57cec5SDimitry Andric     if (isMathLibCallNoop(Call, TLI))
5230b57cec5SDimitry Andric       return true;
524fcaf7f86SDimitry Andric   }
5250b57cec5SDimitry Andric 
52681ad6265SDimitry Andric   // Non-volatile atomic loads from constants can be removed.
52781ad6265SDimitry Andric   if (auto *LI = dyn_cast<LoadInst>(I))
52881ad6265SDimitry Andric     if (auto *GV = dyn_cast<GlobalVariable>(
52981ad6265SDimitry Andric             LI->getPointerOperand()->stripPointerCasts()))
53081ad6265SDimitry Andric       if (!LI->isVolatile() && GV->isConstant())
531fe6060f1SDimitry Andric         return true;
532fe6060f1SDimitry Andric 
5330b57cec5SDimitry Andric   return false;
5340b57cec5SDimitry Andric }
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
5370b57cec5SDimitry Andric /// trivially dead instruction, delete it.  If that makes any of its operands
5380b57cec5SDimitry Andric /// trivially dead, delete them too, recursively.  Return true if any
5390b57cec5SDimitry Andric /// instructions were deleted.
5400b57cec5SDimitry Andric bool llvm::RecursivelyDeleteTriviallyDeadInstructions(
541e8d8bef9SDimitry Andric     Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU,
542e8d8bef9SDimitry Andric     std::function<void(Value *)> AboutToDeleteCallback) {
5430b57cec5SDimitry Andric   Instruction *I = dyn_cast<Instruction>(V);
5440b57cec5SDimitry Andric   if (!I || !isInstructionTriviallyDead(I, TLI))
5450b57cec5SDimitry Andric     return false;
5460b57cec5SDimitry Andric 
5475ffd83dbSDimitry Andric   SmallVector<WeakTrackingVH, 16> DeadInsts;
5480b57cec5SDimitry Andric   DeadInsts.push_back(I);
549e8d8bef9SDimitry Andric   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
550e8d8bef9SDimitry Andric                                              AboutToDeleteCallback);
5510b57cec5SDimitry Andric 
5520b57cec5SDimitry Andric   return true;
5530b57cec5SDimitry Andric }
5540b57cec5SDimitry Andric 
5555ffd83dbSDimitry Andric bool llvm::RecursivelyDeleteTriviallyDeadInstructionsPermissive(
5565ffd83dbSDimitry Andric     SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
557e8d8bef9SDimitry Andric     MemorySSAUpdater *MSSAU,
558e8d8bef9SDimitry Andric     std::function<void(Value *)> AboutToDeleteCallback) {
5595ffd83dbSDimitry Andric   unsigned S = 0, E = DeadInsts.size(), Alive = 0;
5605ffd83dbSDimitry Andric   for (; S != E; ++S) {
56106c3fb27SDimitry Andric     auto *I = dyn_cast_or_null<Instruction>(DeadInsts[S]);
5624824e7fdSDimitry Andric     if (!I || !isInstructionTriviallyDead(I)) {
5635ffd83dbSDimitry Andric       DeadInsts[S] = nullptr;
5645ffd83dbSDimitry Andric       ++Alive;
5655ffd83dbSDimitry Andric     }
5665ffd83dbSDimitry Andric   }
5675ffd83dbSDimitry Andric   if (Alive == E)
5685ffd83dbSDimitry Andric     return false;
569e8d8bef9SDimitry Andric   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
570e8d8bef9SDimitry Andric                                              AboutToDeleteCallback);
5715ffd83dbSDimitry Andric   return true;
5725ffd83dbSDimitry Andric }
5735ffd83dbSDimitry Andric 
5740b57cec5SDimitry Andric void llvm::RecursivelyDeleteTriviallyDeadInstructions(
5755ffd83dbSDimitry Andric     SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
576e8d8bef9SDimitry Andric     MemorySSAUpdater *MSSAU,
577e8d8bef9SDimitry Andric     std::function<void(Value *)> AboutToDeleteCallback) {
5780b57cec5SDimitry Andric   // Process the dead instruction list until empty.
5790b57cec5SDimitry Andric   while (!DeadInsts.empty()) {
5805ffd83dbSDimitry Andric     Value *V = DeadInsts.pop_back_val();
5815ffd83dbSDimitry Andric     Instruction *I = cast_or_null<Instruction>(V);
5825ffd83dbSDimitry Andric     if (!I)
5835ffd83dbSDimitry Andric       continue;
5845ffd83dbSDimitry Andric     assert(isInstructionTriviallyDead(I, TLI) &&
5850b57cec5SDimitry Andric            "Live instruction found in dead worklist!");
5865ffd83dbSDimitry Andric     assert(I->use_empty() && "Instructions with uses are not dead.");
5870b57cec5SDimitry Andric 
5880b57cec5SDimitry Andric     // Don't lose the debug info while deleting the instructions.
5895ffd83dbSDimitry Andric     salvageDebugInfo(*I);
5900b57cec5SDimitry Andric 
591e8d8bef9SDimitry Andric     if (AboutToDeleteCallback)
592e8d8bef9SDimitry Andric       AboutToDeleteCallback(I);
593e8d8bef9SDimitry Andric 
5940b57cec5SDimitry Andric     // Null out all of the instruction's operands to see if any operand becomes
5950b57cec5SDimitry Andric     // dead as we go.
5965ffd83dbSDimitry Andric     for (Use &OpU : I->operands()) {
5970b57cec5SDimitry Andric       Value *OpV = OpU.get();
5980b57cec5SDimitry Andric       OpU.set(nullptr);
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric       if (!OpV->use_empty())
6010b57cec5SDimitry Andric         continue;
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric       // If the operand is an instruction that became dead as we nulled out the
6040b57cec5SDimitry Andric       // operand, and if it is 'trivially' dead, delete it in a future loop
6050b57cec5SDimitry Andric       // iteration.
6060b57cec5SDimitry Andric       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
6070b57cec5SDimitry Andric         if (isInstructionTriviallyDead(OpI, TLI))
6080b57cec5SDimitry Andric           DeadInsts.push_back(OpI);
6090b57cec5SDimitry Andric     }
6100b57cec5SDimitry Andric     if (MSSAU)
6115ffd83dbSDimitry Andric       MSSAU->removeMemoryAccess(I);
6120b57cec5SDimitry Andric 
6135ffd83dbSDimitry Andric     I->eraseFromParent();
6140b57cec5SDimitry Andric   }
6150b57cec5SDimitry Andric }
6160b57cec5SDimitry Andric 
6170b57cec5SDimitry Andric bool llvm::replaceDbgUsesWithUndef(Instruction *I) {
6180b57cec5SDimitry Andric   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
6190fca6ea1SDimitry Andric   SmallVector<DbgVariableRecord *, 1> DPUsers;
6205f757f3fSDimitry Andric   findDbgUsers(DbgUsers, I, &DPUsers);
621bdd1243dSDimitry Andric   for (auto *DII : DbgUsers)
622bdd1243dSDimitry Andric     DII->setKillLocation();
6230fca6ea1SDimitry Andric   for (auto *DVR : DPUsers)
6240fca6ea1SDimitry Andric     DVR->setKillLocation();
6255f757f3fSDimitry Andric   return !DbgUsers.empty() || !DPUsers.empty();
6260b57cec5SDimitry Andric }
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric /// areAllUsesEqual - Check whether the uses of a value are all the same.
6290b57cec5SDimitry Andric /// This is similar to Instruction::hasOneUse() except this will also return
6300b57cec5SDimitry Andric /// true when there are no uses or multiple uses that all refer to the same
6310b57cec5SDimitry Andric /// value.
6320b57cec5SDimitry Andric static bool areAllUsesEqual(Instruction *I) {
6330b57cec5SDimitry Andric   Value::user_iterator UI = I->user_begin();
6340b57cec5SDimitry Andric   Value::user_iterator UE = I->user_end();
6350b57cec5SDimitry Andric   if (UI == UE)
6360b57cec5SDimitry Andric     return true;
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric   User *TheUse = *UI;
6390b57cec5SDimitry Andric   for (++UI; UI != UE; ++UI) {
6400b57cec5SDimitry Andric     if (*UI != TheUse)
6410b57cec5SDimitry Andric       return false;
6420b57cec5SDimitry Andric   }
6430b57cec5SDimitry Andric   return true;
6440b57cec5SDimitry Andric }
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
6470b57cec5SDimitry Andric /// dead PHI node, due to being a def-use chain of single-use nodes that
6480b57cec5SDimitry Andric /// either forms a cycle or is terminated by a trivially dead instruction,
6490b57cec5SDimitry Andric /// delete it.  If that makes any of its operands trivially dead, delete them
6500b57cec5SDimitry Andric /// too, recursively.  Return true if a change was made.
6510b57cec5SDimitry Andric bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
6525ffd83dbSDimitry Andric                                         const TargetLibraryInfo *TLI,
6535ffd83dbSDimitry Andric                                         llvm::MemorySSAUpdater *MSSAU) {
6540b57cec5SDimitry Andric   SmallPtrSet<Instruction*, 4> Visited;
6550b57cec5SDimitry Andric   for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
6560b57cec5SDimitry Andric        I = cast<Instruction>(*I->user_begin())) {
6570b57cec5SDimitry Andric     if (I->use_empty())
6585ffd83dbSDimitry Andric       return RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
6590b57cec5SDimitry Andric 
6600b57cec5SDimitry Andric     // If we find an instruction more than once, we're on a cycle that
6610b57cec5SDimitry Andric     // won't prove fruitful.
6620b57cec5SDimitry Andric     if (!Visited.insert(I).second) {
6630b57cec5SDimitry Andric       // Break the cycle and delete the instruction and its operands.
664fcaf7f86SDimitry Andric       I->replaceAllUsesWith(PoisonValue::get(I->getType()));
6655ffd83dbSDimitry Andric       (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
6660b57cec5SDimitry Andric       return true;
6670b57cec5SDimitry Andric     }
6680b57cec5SDimitry Andric   }
6690b57cec5SDimitry Andric   return false;
6700b57cec5SDimitry Andric }
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric static bool
6730b57cec5SDimitry Andric simplifyAndDCEInstruction(Instruction *I,
6740b57cec5SDimitry Andric                           SmallSetVector<Instruction *, 16> &WorkList,
6750b57cec5SDimitry Andric                           const DataLayout &DL,
6760b57cec5SDimitry Andric                           const TargetLibraryInfo *TLI) {
6770b57cec5SDimitry Andric   if (isInstructionTriviallyDead(I, TLI)) {
6780b57cec5SDimitry Andric     salvageDebugInfo(*I);
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric     // Null out all of the instruction's operands to see if any operand becomes
6810b57cec5SDimitry Andric     // dead as we go.
6820b57cec5SDimitry Andric     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
6830b57cec5SDimitry Andric       Value *OpV = I->getOperand(i);
6840b57cec5SDimitry Andric       I->setOperand(i, nullptr);
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric       if (!OpV->use_empty() || I == OpV)
6870b57cec5SDimitry Andric         continue;
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric       // If the operand is an instruction that became dead as we nulled out the
6900b57cec5SDimitry Andric       // operand, and if it is 'trivially' dead, delete it in a future loop
6910b57cec5SDimitry Andric       // iteration.
6920b57cec5SDimitry Andric       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
6930b57cec5SDimitry Andric         if (isInstructionTriviallyDead(OpI, TLI))
6940b57cec5SDimitry Andric           WorkList.insert(OpI);
6950b57cec5SDimitry Andric     }
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric     I->eraseFromParent();
6980b57cec5SDimitry Andric 
6990b57cec5SDimitry Andric     return true;
7000b57cec5SDimitry Andric   }
7010b57cec5SDimitry Andric 
70281ad6265SDimitry Andric   if (Value *SimpleV = simplifyInstruction(I, DL)) {
7030b57cec5SDimitry Andric     // Add the users to the worklist. CAREFUL: an instruction can use itself,
7040b57cec5SDimitry Andric     // in the case of a phi node.
7050b57cec5SDimitry Andric     for (User *U : I->users()) {
7060b57cec5SDimitry Andric       if (U != I) {
7070b57cec5SDimitry Andric         WorkList.insert(cast<Instruction>(U));
7080b57cec5SDimitry Andric       }
7090b57cec5SDimitry Andric     }
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric     // Replace the instruction with its simplified value.
7120b57cec5SDimitry Andric     bool Changed = false;
7130b57cec5SDimitry Andric     if (!I->use_empty()) {
7140b57cec5SDimitry Andric       I->replaceAllUsesWith(SimpleV);
7150b57cec5SDimitry Andric       Changed = true;
7160b57cec5SDimitry Andric     }
7170b57cec5SDimitry Andric     if (isInstructionTriviallyDead(I, TLI)) {
7180b57cec5SDimitry Andric       I->eraseFromParent();
7190b57cec5SDimitry Andric       Changed = true;
7200b57cec5SDimitry Andric     }
7210b57cec5SDimitry Andric     return Changed;
7220b57cec5SDimitry Andric   }
7230b57cec5SDimitry Andric   return false;
7240b57cec5SDimitry Andric }
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
7270b57cec5SDimitry Andric /// simplify any instructions in it and recursively delete dead instructions.
7280b57cec5SDimitry Andric ///
7290b57cec5SDimitry Andric /// This returns true if it changed the code, note that it can delete
7300b57cec5SDimitry Andric /// instructions in other blocks as well in this block.
7310b57cec5SDimitry Andric bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
7320b57cec5SDimitry Andric                                        const TargetLibraryInfo *TLI) {
7330b57cec5SDimitry Andric   bool MadeChange = false;
7340fca6ea1SDimitry Andric   const DataLayout &DL = BB->getDataLayout();
7350b57cec5SDimitry Andric 
7360b57cec5SDimitry Andric #ifndef NDEBUG
7370b57cec5SDimitry Andric   // In debug builds, ensure that the terminator of the block is never replaced
7380b57cec5SDimitry Andric   // or deleted by these simplifications. The idea of simplification is that it
7390b57cec5SDimitry Andric   // cannot introduce new instructions, and there is no way to replace the
7400b57cec5SDimitry Andric   // terminator of a block without introducing a new instruction.
7410b57cec5SDimitry Andric   AssertingVH<Instruction> TerminatorVH(&BB->back());
7420b57cec5SDimitry Andric #endif
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric   SmallSetVector<Instruction *, 16> WorkList;
7450b57cec5SDimitry Andric   // Iterate over the original function, only adding insts to the worklist
7460b57cec5SDimitry Andric   // if they actually need to be revisited. This avoids having to pre-init
7470b57cec5SDimitry Andric   // the worklist with the entire function's worth of instructions.
7480b57cec5SDimitry Andric   for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
7490b57cec5SDimitry Andric        BI != E;) {
7500b57cec5SDimitry Andric     assert(!BI->isTerminator());
7510b57cec5SDimitry Andric     Instruction *I = &*BI;
7520b57cec5SDimitry Andric     ++BI;
7530b57cec5SDimitry Andric 
7540b57cec5SDimitry Andric     // We're visiting this instruction now, so make sure it's not in the
7550b57cec5SDimitry Andric     // worklist from an earlier visit.
7560b57cec5SDimitry Andric     if (!WorkList.count(I))
7570b57cec5SDimitry Andric       MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
7580b57cec5SDimitry Andric   }
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric   while (!WorkList.empty()) {
7610b57cec5SDimitry Andric     Instruction *I = WorkList.pop_back_val();
7620b57cec5SDimitry Andric     MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
7630b57cec5SDimitry Andric   }
7640b57cec5SDimitry Andric   return MadeChange;
7650b57cec5SDimitry Andric }
7660b57cec5SDimitry Andric 
7670b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
7680b57cec5SDimitry Andric //  Control Flow Graph Restructuring.
7690b57cec5SDimitry Andric //
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
7720b57cec5SDimitry Andric                                        DomTreeUpdater *DTU) {
7730b57cec5SDimitry Andric 
7740b57cec5SDimitry Andric   // If BB has single-entry PHI nodes, fold them.
7750b57cec5SDimitry Andric   while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
7760b57cec5SDimitry Andric     Value *NewVal = PN->getIncomingValue(0);
777fcaf7f86SDimitry Andric     // Replace self referencing PHI with poison, it must be dead.
778fcaf7f86SDimitry Andric     if (NewVal == PN) NewVal = PoisonValue::get(PN->getType());
7790b57cec5SDimitry Andric     PN->replaceAllUsesWith(NewVal);
7800b57cec5SDimitry Andric     PN->eraseFromParent();
7810b57cec5SDimitry Andric   }
7820b57cec5SDimitry Andric 
7830b57cec5SDimitry Andric   BasicBlock *PredBB = DestBB->getSinglePredecessor();
7840b57cec5SDimitry Andric   assert(PredBB && "Block doesn't have a single predecessor!");
7850b57cec5SDimitry Andric 
786fe6060f1SDimitry Andric   bool ReplaceEntryBB = PredBB->isEntryBlock();
7870b57cec5SDimitry Andric 
7880b57cec5SDimitry Andric   // DTU updates: Collect all the edges that enter
7890b57cec5SDimitry Andric   // PredBB. These dominator edges will be redirected to DestBB.
7900b57cec5SDimitry Andric   SmallVector<DominatorTree::UpdateType, 32> Updates;
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric   if (DTU) {
7934824e7fdSDimitry Andric     // To avoid processing the same predecessor more than once.
7944824e7fdSDimitry Andric     SmallPtrSet<BasicBlock *, 2> SeenPreds;
7954824e7fdSDimitry Andric     Updates.reserve(Updates.size() + 2 * pred_size(PredBB) + 1);
7964824e7fdSDimitry Andric     for (BasicBlock *PredOfPredBB : predecessors(PredBB))
7970b57cec5SDimitry Andric       // This predecessor of PredBB may already have DestBB as a successor.
798fe6060f1SDimitry Andric       if (PredOfPredBB != PredBB)
7994824e7fdSDimitry Andric         if (SeenPreds.insert(PredOfPredBB).second)
800fe6060f1SDimitry Andric           Updates.push_back({DominatorTree::Insert, PredOfPredBB, DestBB});
8014824e7fdSDimitry Andric     SeenPreds.clear();
8024824e7fdSDimitry Andric     for (BasicBlock *PredOfPredBB : predecessors(PredBB))
8034824e7fdSDimitry Andric       if (SeenPreds.insert(PredOfPredBB).second)
804fe6060f1SDimitry Andric         Updates.push_back({DominatorTree::Delete, PredOfPredBB, PredBB});
805e8d8bef9SDimitry Andric     Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
8060b57cec5SDimitry Andric   }
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric   // Zap anything that took the address of DestBB.  Not doing this will give the
8090b57cec5SDimitry Andric   // address an invalid value.
8100b57cec5SDimitry Andric   if (DestBB->hasAddressTaken()) {
8110b57cec5SDimitry Andric     BlockAddress *BA = BlockAddress::get(DestBB);
8120b57cec5SDimitry Andric     Constant *Replacement =
8130b57cec5SDimitry Andric       ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
8140b57cec5SDimitry Andric     BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
8150b57cec5SDimitry Andric                                                      BA->getType()));
8160b57cec5SDimitry Andric     BA->destroyConstant();
8170b57cec5SDimitry Andric   }
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric   // Anything that branched to PredBB now branches to DestBB.
8200b57cec5SDimitry Andric   PredBB->replaceAllUsesWith(DestBB);
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric   // Splice all the instructions from PredBB to DestBB.
8230b57cec5SDimitry Andric   PredBB->getTerminator()->eraseFromParent();
824bdd1243dSDimitry Andric   DestBB->splice(DestBB->begin(), PredBB);
8250b57cec5SDimitry Andric   new UnreachableInst(PredBB->getContext(), PredBB);
8260b57cec5SDimitry Andric 
8270b57cec5SDimitry Andric   // If the PredBB is the entry block of the function, move DestBB up to
8280b57cec5SDimitry Andric   // become the entry block after we erase PredBB.
8290b57cec5SDimitry Andric   if (ReplaceEntryBB)
8300b57cec5SDimitry Andric     DestBB->moveAfter(PredBB);
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric   if (DTU) {
833bdd1243dSDimitry Andric     assert(PredBB->size() == 1 &&
8340b57cec5SDimitry Andric            isa<UnreachableInst>(PredBB->getTerminator()) &&
8350b57cec5SDimitry Andric            "The successor list of PredBB isn't empty before "
8360b57cec5SDimitry Andric            "applying corresponding DTU updates.");
8370b57cec5SDimitry Andric     DTU->applyUpdatesPermissive(Updates);
8380b57cec5SDimitry Andric     DTU->deleteBB(PredBB);
8390b57cec5SDimitry Andric     // Recalculation of DomTree is needed when updating a forward DomTree and
8400b57cec5SDimitry Andric     // the Entry BB is replaced.
8410b57cec5SDimitry Andric     if (ReplaceEntryBB && DTU->hasDomTree()) {
8420b57cec5SDimitry Andric       // The entry block was removed and there is no external interface for
8430b57cec5SDimitry Andric       // the dominator tree to be notified of this change. In this corner-case
8440b57cec5SDimitry Andric       // we recalculate the entire tree.
8450b57cec5SDimitry Andric       DTU->recalculate(*(DestBB->getParent()));
8460b57cec5SDimitry Andric     }
8470b57cec5SDimitry Andric   }
8480b57cec5SDimitry Andric 
8490b57cec5SDimitry Andric   else {
8500b57cec5SDimitry Andric     PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.
8510b57cec5SDimitry Andric   }
8520b57cec5SDimitry Andric }
8530b57cec5SDimitry Andric 
8548bcb0991SDimitry Andric /// Return true if we can choose one of these values to use in place of the
8558bcb0991SDimitry Andric /// other. Note that we will always choose the non-undef value to keep.
8560b57cec5SDimitry Andric static bool CanMergeValues(Value *First, Value *Second) {
8570b57cec5SDimitry Andric   return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
8580b57cec5SDimitry Andric }
8590b57cec5SDimitry Andric 
8608bcb0991SDimitry Andric /// Return true if we can fold BB, an almost-empty BB ending in an unconditional
8618bcb0991SDimitry Andric /// branch to Succ, into Succ.
8620b57cec5SDimitry Andric ///
8630b57cec5SDimitry Andric /// Assumption: Succ is the single successor for BB.
8645f757f3fSDimitry Andric static bool
8655f757f3fSDimitry Andric CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ,
8665f757f3fSDimitry Andric                                 const SmallPtrSetImpl<BasicBlock *> &BBPreds) {
8670b57cec5SDimitry Andric   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
8680b57cec5SDimitry Andric 
8690b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
8700b57cec5SDimitry Andric                     << Succ->getName() << "\n");
8710b57cec5SDimitry Andric   // Shortcut, if there is only a single predecessor it must be BB and merging
8720b57cec5SDimitry Andric   // is always safe
8735f757f3fSDimitry Andric   if (Succ->getSinglePredecessor())
8745f757f3fSDimitry Andric     return true;
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric   // Look at all the phi nodes in Succ, to see if they present a conflict when
8770b57cec5SDimitry Andric   // merging these blocks
8780b57cec5SDimitry Andric   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
8790b57cec5SDimitry Andric     PHINode *PN = cast<PHINode>(I);
8800b57cec5SDimitry Andric 
8810b57cec5SDimitry Andric     // If the incoming value from BB is again a PHINode in
8820b57cec5SDimitry Andric     // BB which has the same incoming value for *PI as PN does, we can
8830b57cec5SDimitry Andric     // merge the phi nodes and then the blocks can still be merged
8840b57cec5SDimitry Andric     PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
8850b57cec5SDimitry Andric     if (BBPN && BBPN->getParent() == BB) {
8860b57cec5SDimitry Andric       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
8870b57cec5SDimitry Andric         BasicBlock *IBB = PN->getIncomingBlock(PI);
8880b57cec5SDimitry Andric         if (BBPreds.count(IBB) &&
8890b57cec5SDimitry Andric             !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
8900b57cec5SDimitry Andric                             PN->getIncomingValue(PI))) {
8910b57cec5SDimitry Andric           LLVM_DEBUG(dbgs()
8920b57cec5SDimitry Andric                      << "Can't fold, phi node " << PN->getName() << " in "
8930b57cec5SDimitry Andric                      << Succ->getName() << " is conflicting with "
8940b57cec5SDimitry Andric                      << BBPN->getName() << " with regard to common predecessor "
8950b57cec5SDimitry Andric                      << IBB->getName() << "\n");
8960b57cec5SDimitry Andric           return false;
8970b57cec5SDimitry Andric         }
8980b57cec5SDimitry Andric       }
8990b57cec5SDimitry Andric     } else {
9000b57cec5SDimitry Andric       Value* Val = PN->getIncomingValueForBlock(BB);
9010b57cec5SDimitry Andric       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
9020b57cec5SDimitry Andric         // See if the incoming value for the common predecessor is equal to the
9030b57cec5SDimitry Andric         // one for BB, in which case this phi node will not prevent the merging
9040b57cec5SDimitry Andric         // of the block.
9050b57cec5SDimitry Andric         BasicBlock *IBB = PN->getIncomingBlock(PI);
9060b57cec5SDimitry Andric         if (BBPreds.count(IBB) &&
9070b57cec5SDimitry Andric             !CanMergeValues(Val, PN->getIncomingValue(PI))) {
9080b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()
9090b57cec5SDimitry Andric                             << " in " << Succ->getName()
9100b57cec5SDimitry Andric                             << " is conflicting with regard to common "
9110b57cec5SDimitry Andric                             << "predecessor " << IBB->getName() << "\n");
9120b57cec5SDimitry Andric           return false;
9130b57cec5SDimitry Andric         }
9140b57cec5SDimitry Andric       }
9150b57cec5SDimitry Andric     }
9160b57cec5SDimitry Andric   }
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric   return true;
9190b57cec5SDimitry Andric }
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric using PredBlockVector = SmallVector<BasicBlock *, 16>;
9220b57cec5SDimitry Andric using IncomingValueMap = DenseMap<BasicBlock *, Value *>;
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric /// Determines the value to use as the phi node input for a block.
9250b57cec5SDimitry Andric ///
9260b57cec5SDimitry Andric /// Select between \p OldVal any value that we know flows from \p BB
9270b57cec5SDimitry Andric /// to a particular phi on the basis of which one (if either) is not
9280b57cec5SDimitry Andric /// undef. Update IncomingValues based on the selected value.
9290b57cec5SDimitry Andric ///
9300b57cec5SDimitry Andric /// \param OldVal The value we are considering selecting.
9310b57cec5SDimitry Andric /// \param BB The block that the value flows in from.
9320b57cec5SDimitry Andric /// \param IncomingValues A map from block-to-value for other phi inputs
9330b57cec5SDimitry Andric /// that we have examined.
9340b57cec5SDimitry Andric ///
9350b57cec5SDimitry Andric /// \returns the selected value.
9360b57cec5SDimitry Andric static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
9370b57cec5SDimitry Andric                                           IncomingValueMap &IncomingValues) {
9380b57cec5SDimitry Andric   if (!isa<UndefValue>(OldVal)) {
9390b57cec5SDimitry Andric     assert((!IncomingValues.count(BB) ||
9400b57cec5SDimitry Andric             IncomingValues.find(BB)->second == OldVal) &&
9410b57cec5SDimitry Andric            "Expected OldVal to match incoming value from BB!");
9420b57cec5SDimitry Andric 
9430b57cec5SDimitry Andric     IncomingValues.insert(std::make_pair(BB, OldVal));
9440b57cec5SDimitry Andric     return OldVal;
9450b57cec5SDimitry Andric   }
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric   IncomingValueMap::const_iterator It = IncomingValues.find(BB);
9480b57cec5SDimitry Andric   if (It != IncomingValues.end()) return It->second;
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric   return OldVal;
9510b57cec5SDimitry Andric }
9520b57cec5SDimitry Andric 
9530b57cec5SDimitry Andric /// Create a map from block to value for the operands of a
9540b57cec5SDimitry Andric /// given phi.
9550b57cec5SDimitry Andric ///
9560b57cec5SDimitry Andric /// Create a map from block to value for each non-undef value flowing
9570b57cec5SDimitry Andric /// into \p PN.
9580b57cec5SDimitry Andric ///
9590b57cec5SDimitry Andric /// \param PN The phi we are collecting the map for.
9600b57cec5SDimitry Andric /// \param IncomingValues [out] The map from block to value for this phi.
9610b57cec5SDimitry Andric static void gatherIncomingValuesToPhi(PHINode *PN,
9620b57cec5SDimitry Andric                                       IncomingValueMap &IncomingValues) {
9630b57cec5SDimitry Andric   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9640b57cec5SDimitry Andric     BasicBlock *BB = PN->getIncomingBlock(i);
9650b57cec5SDimitry Andric     Value *V = PN->getIncomingValue(i);
9660b57cec5SDimitry Andric 
9670b57cec5SDimitry Andric     if (!isa<UndefValue>(V))
9680b57cec5SDimitry Andric       IncomingValues.insert(std::make_pair(BB, V));
9690b57cec5SDimitry Andric   }
9700b57cec5SDimitry Andric }
9710b57cec5SDimitry Andric 
9720b57cec5SDimitry Andric /// Replace the incoming undef values to a phi with the values
9730b57cec5SDimitry Andric /// from a block-to-value map.
9740b57cec5SDimitry Andric ///
9750b57cec5SDimitry Andric /// \param PN The phi we are replacing the undefs in.
9760b57cec5SDimitry Andric /// \param IncomingValues A map from block to value.
9770b57cec5SDimitry Andric static void replaceUndefValuesInPhi(PHINode *PN,
9780b57cec5SDimitry Andric                                     const IncomingValueMap &IncomingValues) {
979d409305fSDimitry Andric   SmallVector<unsigned> TrueUndefOps;
9800b57cec5SDimitry Andric   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9810b57cec5SDimitry Andric     Value *V = PN->getIncomingValue(i);
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric     if (!isa<UndefValue>(V)) continue;
9840b57cec5SDimitry Andric 
9850b57cec5SDimitry Andric     BasicBlock *BB = PN->getIncomingBlock(i);
9860b57cec5SDimitry Andric     IncomingValueMap::const_iterator It = IncomingValues.find(BB);
9870b57cec5SDimitry Andric 
988d409305fSDimitry Andric     // Keep track of undef/poison incoming values. Those must match, so we fix
989d409305fSDimitry Andric     // them up below if needed.
990d409305fSDimitry Andric     // Note: this is conservatively correct, but we could try harder and group
991d409305fSDimitry Andric     // the undef values per incoming basic block.
992d409305fSDimitry Andric     if (It == IncomingValues.end()) {
993d409305fSDimitry Andric       TrueUndefOps.push_back(i);
994d409305fSDimitry Andric       continue;
995d409305fSDimitry Andric     }
996d409305fSDimitry Andric 
997d409305fSDimitry Andric     // There is a defined value for this incoming block, so map this undef
998d409305fSDimitry Andric     // incoming value to the defined value.
9990b57cec5SDimitry Andric     PN->setIncomingValue(i, It->second);
10000b57cec5SDimitry Andric   }
1001d409305fSDimitry Andric 
1002d409305fSDimitry Andric   // If there are both undef and poison values incoming, then convert those
1003d409305fSDimitry Andric   // values to undef. It is invalid to have different values for the same
1004d409305fSDimitry Andric   // incoming block.
1005d409305fSDimitry Andric   unsigned PoisonCount = count_if(TrueUndefOps, [&](unsigned i) {
1006d409305fSDimitry Andric     return isa<PoisonValue>(PN->getIncomingValue(i));
1007d409305fSDimitry Andric   });
1008d409305fSDimitry Andric   if (PoisonCount != 0 && PoisonCount != TrueUndefOps.size()) {
1009d409305fSDimitry Andric     for (unsigned i : TrueUndefOps)
1010d409305fSDimitry Andric       PN->setIncomingValue(i, UndefValue::get(PN->getType()));
1011d409305fSDimitry Andric   }
10120b57cec5SDimitry Andric }
10130b57cec5SDimitry Andric 
10145f757f3fSDimitry Andric // Only when they shares a single common predecessor, return true.
10155f757f3fSDimitry Andric // Only handles cases when BB can't be merged while its predecessors can be
10165f757f3fSDimitry Andric // redirected.
10175f757f3fSDimitry Andric static bool
10185f757f3fSDimitry Andric CanRedirectPredsOfEmptyBBToSucc(BasicBlock *BB, BasicBlock *Succ,
10195f757f3fSDimitry Andric                                 const SmallPtrSetImpl<BasicBlock *> &BBPreds,
10205f757f3fSDimitry Andric                                 const SmallPtrSetImpl<BasicBlock *> &SuccPreds,
10215f757f3fSDimitry Andric                                 BasicBlock *&CommonPred) {
10225f757f3fSDimitry Andric 
10235f757f3fSDimitry Andric   // There must be phis in BB, otherwise BB will be merged into Succ directly
10245f757f3fSDimitry Andric   if (BB->phis().empty() || Succ->phis().empty())
10255f757f3fSDimitry Andric     return false;
10265f757f3fSDimitry Andric 
10275f757f3fSDimitry Andric   // BB must have predecessors not shared that can be redirected to Succ
10285f757f3fSDimitry Andric   if (!BB->hasNPredecessorsOrMore(2))
10295f757f3fSDimitry Andric     return false;
10305f757f3fSDimitry Andric 
1031*71ac745dSDimitry Andric   if (any_of(BBPreds, [](const BasicBlock *Pred) {
1032*71ac745dSDimitry Andric         return isa<IndirectBrInst>(Pred->getTerminator());
1033*71ac745dSDimitry Andric       }))
1034*71ac745dSDimitry Andric     return false;
1035*71ac745dSDimitry Andric 
1036*71ac745dSDimitry Andric   // Get the single common predecessor of both BB and Succ. Return false
1037*71ac745dSDimitry Andric   // when there are more than one common predecessors.
10385f757f3fSDimitry Andric   for (BasicBlock *SuccPred : SuccPreds) {
10395f757f3fSDimitry Andric     if (BBPreds.count(SuccPred)) {
10405f757f3fSDimitry Andric       if (CommonPred)
10415f757f3fSDimitry Andric         return false;
10425f757f3fSDimitry Andric       CommonPred = SuccPred;
10435f757f3fSDimitry Andric     }
10445f757f3fSDimitry Andric   }
10455f757f3fSDimitry Andric 
10465f757f3fSDimitry Andric   return true;
10475f757f3fSDimitry Andric }
10485f757f3fSDimitry Andric 
10490b57cec5SDimitry Andric /// Replace a value flowing from a block to a phi with
10500b57cec5SDimitry Andric /// potentially multiple instances of that value flowing from the
10510b57cec5SDimitry Andric /// block's predecessors to the phi.
10520b57cec5SDimitry Andric ///
10530b57cec5SDimitry Andric /// \param BB The block with the value flowing into the phi.
10540b57cec5SDimitry Andric /// \param BBPreds The predecessors of BB.
10550b57cec5SDimitry Andric /// \param PN The phi that we are updating.
10565f757f3fSDimitry Andric /// \param CommonPred The common predecessor of BB and PN's BasicBlock
10570b57cec5SDimitry Andric static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
10580b57cec5SDimitry Andric                                                 const PredBlockVector &BBPreds,
10595f757f3fSDimitry Andric                                                 PHINode *PN,
10605f757f3fSDimitry Andric                                                 BasicBlock *CommonPred) {
10610b57cec5SDimitry Andric   Value *OldVal = PN->removeIncomingValue(BB, false);
10620b57cec5SDimitry Andric   assert(OldVal && "No entry in PHI for Pred BB!");
10630b57cec5SDimitry Andric 
10640b57cec5SDimitry Andric   IncomingValueMap IncomingValues;
10650b57cec5SDimitry Andric 
10660b57cec5SDimitry Andric   // We are merging two blocks - BB, and the block containing PN - and
10670b57cec5SDimitry Andric   // as a result we need to redirect edges from the predecessors of BB
10680b57cec5SDimitry Andric   // to go to the block containing PN, and update PN
10690b57cec5SDimitry Andric   // accordingly. Since we allow merging blocks in the case where the
10700b57cec5SDimitry Andric   // predecessor and successor blocks both share some predecessors,
10710b57cec5SDimitry Andric   // and where some of those common predecessors might have undef
10720b57cec5SDimitry Andric   // values flowing into PN, we want to rewrite those values to be
10730b57cec5SDimitry Andric   // consistent with the non-undef values.
10740b57cec5SDimitry Andric 
10750b57cec5SDimitry Andric   gatherIncomingValuesToPhi(PN, IncomingValues);
10760b57cec5SDimitry Andric 
10770b57cec5SDimitry Andric   // If this incoming value is one of the PHI nodes in BB, the new entries
10780b57cec5SDimitry Andric   // in the PHI node are the entries from the old PHI.
10790b57cec5SDimitry Andric   if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
10800b57cec5SDimitry Andric     PHINode *OldValPN = cast<PHINode>(OldVal);
10810b57cec5SDimitry Andric     for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
10820b57cec5SDimitry Andric       // Note that, since we are merging phi nodes and BB and Succ might
10830b57cec5SDimitry Andric       // have common predecessors, we could end up with a phi node with
10840b57cec5SDimitry Andric       // identical incoming branches. This will be cleaned up later (and
10850b57cec5SDimitry Andric       // will trigger asserts if we try to clean it up now, without also
10860b57cec5SDimitry Andric       // simplifying the corresponding conditional branch).
10870b57cec5SDimitry Andric       BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
10885f757f3fSDimitry Andric 
10895f757f3fSDimitry Andric       if (PredBB == CommonPred)
10905f757f3fSDimitry Andric         continue;
10915f757f3fSDimitry Andric 
10920b57cec5SDimitry Andric       Value *PredVal = OldValPN->getIncomingValue(i);
10935f757f3fSDimitry Andric       Value *Selected =
10945f757f3fSDimitry Andric           selectIncomingValueForBlock(PredVal, PredBB, IncomingValues);
10950b57cec5SDimitry Andric 
10960b57cec5SDimitry Andric       // And add a new incoming value for this predecessor for the
10970b57cec5SDimitry Andric       // newly retargeted branch.
10980b57cec5SDimitry Andric       PN->addIncoming(Selected, PredBB);
10990b57cec5SDimitry Andric     }
11005f757f3fSDimitry Andric     if (CommonPred)
11015f757f3fSDimitry Andric       PN->addIncoming(OldValPN->getIncomingValueForBlock(CommonPred), BB);
11025f757f3fSDimitry Andric 
11030b57cec5SDimitry Andric   } else {
11040fca6ea1SDimitry Andric     for (BasicBlock *PredBB : BBPreds) {
11050b57cec5SDimitry Andric       // Update existing incoming values in PN for this
11060b57cec5SDimitry Andric       // predecessor of BB.
11075f757f3fSDimitry Andric       if (PredBB == CommonPred)
11085f757f3fSDimitry Andric         continue;
11095f757f3fSDimitry Andric 
11105f757f3fSDimitry Andric       Value *Selected =
11115f757f3fSDimitry Andric           selectIncomingValueForBlock(OldVal, PredBB, IncomingValues);
11120b57cec5SDimitry Andric 
11130b57cec5SDimitry Andric       // And add a new incoming value for this predecessor for the
11140b57cec5SDimitry Andric       // newly retargeted branch.
11150b57cec5SDimitry Andric       PN->addIncoming(Selected, PredBB);
11160b57cec5SDimitry Andric     }
11175f757f3fSDimitry Andric     if (CommonPred)
11185f757f3fSDimitry Andric       PN->addIncoming(OldVal, BB);
11190b57cec5SDimitry Andric   }
11200b57cec5SDimitry Andric 
11210b57cec5SDimitry Andric   replaceUndefValuesInPhi(PN, IncomingValues);
11220b57cec5SDimitry Andric }
11230b57cec5SDimitry Andric 
11240b57cec5SDimitry Andric bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
11250b57cec5SDimitry Andric                                                    DomTreeUpdater *DTU) {
11260b57cec5SDimitry Andric   assert(BB != &BB->getParent()->getEntryBlock() &&
11270b57cec5SDimitry Andric          "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
11280b57cec5SDimitry Andric 
11295f757f3fSDimitry Andric   // We can't simplify infinite loops.
11300b57cec5SDimitry Andric   BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
11315f757f3fSDimitry Andric   if (BB == Succ)
11325f757f3fSDimitry Andric     return false;
11330b57cec5SDimitry Andric 
11345f757f3fSDimitry Andric   SmallPtrSet<BasicBlock *, 16> BBPreds(pred_begin(BB), pred_end(BB));
11355f757f3fSDimitry Andric   SmallPtrSet<BasicBlock *, 16> SuccPreds(pred_begin(Succ), pred_end(Succ));
11365f757f3fSDimitry Andric 
11375f757f3fSDimitry Andric   // The single common predecessor of BB and Succ when BB cannot be killed
11385f757f3fSDimitry Andric   BasicBlock *CommonPred = nullptr;
11395f757f3fSDimitry Andric 
11405f757f3fSDimitry Andric   bool BBKillable = CanPropagatePredecessorsForPHIs(BB, Succ, BBPreds);
11415f757f3fSDimitry Andric 
1142*71ac745dSDimitry Andric   // Even if we can not fold BB into Succ, we may be able to redirect the
11435f757f3fSDimitry Andric   // predecessors of BB to Succ.
11445f757f3fSDimitry Andric   bool BBPhisMergeable =
11455f757f3fSDimitry Andric       BBKillable ||
11465f757f3fSDimitry Andric       CanRedirectPredsOfEmptyBBToSucc(BB, Succ, BBPreds, SuccPreds, CommonPred);
11475f757f3fSDimitry Andric 
11485f757f3fSDimitry Andric   if (!BBKillable && !BBPhisMergeable)
11495f757f3fSDimitry Andric     return false;
11505f757f3fSDimitry Andric 
11515f757f3fSDimitry Andric   // Check to see if merging these blocks/phis would cause conflicts for any of
11525f757f3fSDimitry Andric   // the phi nodes in BB or Succ. If not, we can safely merge.
11530b57cec5SDimitry Andric 
11540b57cec5SDimitry Andric   // Check for cases where Succ has multiple predecessors and a PHI node in BB
11550b57cec5SDimitry Andric   // has uses which will not disappear when the PHI nodes are merged.  It is
11560b57cec5SDimitry Andric   // possible to handle such cases, but difficult: it requires checking whether
11570b57cec5SDimitry Andric   // BB dominates Succ, which is non-trivial to calculate in the case where
11580b57cec5SDimitry Andric   // Succ has multiple predecessors.  Also, it requires checking whether
11590b57cec5SDimitry Andric   // constructing the necessary self-referential PHI node doesn't introduce any
11600b57cec5SDimitry Andric   // conflicts; this isn't too difficult, but the previous code for doing this
11610b57cec5SDimitry Andric   // was incorrect.
11620b57cec5SDimitry Andric   //
11630b57cec5SDimitry Andric   // Note that if this check finds a live use, BB dominates Succ, so BB is
11640b57cec5SDimitry Andric   // something like a loop pre-header (or rarely, a part of an irreducible CFG);
11650b57cec5SDimitry Andric   // folding the branch isn't profitable in that case anyway.
11660b57cec5SDimitry Andric   if (!Succ->getSinglePredecessor()) {
11670b57cec5SDimitry Andric     BasicBlock::iterator BBI = BB->begin();
11680b57cec5SDimitry Andric     while (isa<PHINode>(*BBI)) {
11690b57cec5SDimitry Andric       for (Use &U : BBI->uses()) {
11700b57cec5SDimitry Andric         if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
11710b57cec5SDimitry Andric           if (PN->getIncomingBlock(U) != BB)
11720b57cec5SDimitry Andric             return false;
11730b57cec5SDimitry Andric         } else {
11740b57cec5SDimitry Andric           return false;
11750b57cec5SDimitry Andric         }
11760b57cec5SDimitry Andric       }
11770b57cec5SDimitry Andric       ++BBI;
11780b57cec5SDimitry Andric     }
11790b57cec5SDimitry Andric   }
11800b57cec5SDimitry Andric 
11815f757f3fSDimitry Andric   if (BBPhisMergeable && CommonPred)
11825f757f3fSDimitry Andric     LLVM_DEBUG(dbgs() << "Found Common Predecessor between: " << BB->getName()
11835f757f3fSDimitry Andric                       << " and " << Succ->getName() << " : "
11845f757f3fSDimitry Andric                       << CommonPred->getName() << "\n");
11855f757f3fSDimitry Andric 
1186bdd1243dSDimitry Andric   // 'BB' and 'BB->Pred' are loop latches, bail out to presrve inner loop
1187bdd1243dSDimitry Andric   // metadata.
1188bdd1243dSDimitry Andric   //
1189bdd1243dSDimitry Andric   // FIXME: This is a stop-gap solution to preserve inner-loop metadata given
1190bdd1243dSDimitry Andric   // current status (that loop metadata is implemented as metadata attached to
1191bdd1243dSDimitry Andric   // the branch instruction in the loop latch block). To quote from review
1192bdd1243dSDimitry Andric   // comments, "the current representation of loop metadata (using a loop latch
1193bdd1243dSDimitry Andric   // terminator attachment) is known to be fundamentally broken. Loop latches
1194bdd1243dSDimitry Andric   // are not uniquely associated with loops (both in that a latch can be part of
1195bdd1243dSDimitry Andric   // multiple loops and a loop may have multiple latches). Loop headers are. The
1196bdd1243dSDimitry Andric   // solution to this problem is also known: Add support for basic block
1197bdd1243dSDimitry Andric   // metadata, and attach loop metadata to the loop header."
1198bdd1243dSDimitry Andric   //
1199bdd1243dSDimitry Andric   // Why bail out:
1200bdd1243dSDimitry Andric   // In this case, we expect 'BB' is the latch for outer-loop and 'BB->Pred' is
1201bdd1243dSDimitry Andric   // the latch for inner-loop (see reason below), so bail out to prerserve
1202bdd1243dSDimitry Andric   // inner-loop metadata rather than eliminating 'BB' and attaching its metadata
1203bdd1243dSDimitry Andric   // to this inner-loop.
1204bdd1243dSDimitry Andric   // - The reason we believe 'BB' and 'BB->Pred' have different inner-most
1205bdd1243dSDimitry Andric   // loops: assuming 'BB' and 'BB->Pred' are from the same inner-most loop L,
1206bdd1243dSDimitry Andric   // then 'BB' is the header and latch of 'L' and thereby 'L' must consist of
1207bdd1243dSDimitry Andric   // one self-looping basic block, which is contradictory with the assumption.
1208bdd1243dSDimitry Andric   //
1209bdd1243dSDimitry Andric   // To illustrate how inner-loop metadata is dropped:
1210bdd1243dSDimitry Andric   //
1211bdd1243dSDimitry Andric   // CFG Before
1212bdd1243dSDimitry Andric   //
1213bdd1243dSDimitry Andric   // BB is while.cond.exit, attached with loop metdata md2.
1214bdd1243dSDimitry Andric   // BB->Pred is for.body, attached with loop metadata md1.
1215bdd1243dSDimitry Andric   //
1216bdd1243dSDimitry Andric   //      entry
1217bdd1243dSDimitry Andric   //        |
1218bdd1243dSDimitry Andric   //        v
1219bdd1243dSDimitry Andric   // ---> while.cond   ------------->  while.end
1220bdd1243dSDimitry Andric   // |       |
1221bdd1243dSDimitry Andric   // |       v
1222bdd1243dSDimitry Andric   // |   while.body
1223bdd1243dSDimitry Andric   // |       |
1224bdd1243dSDimitry Andric   // |       v
1225bdd1243dSDimitry Andric   // |    for.body <---- (md1)
1226bdd1243dSDimitry Andric   // |       |  |______|
1227bdd1243dSDimitry Andric   // |       v
1228bdd1243dSDimitry Andric   // |    while.cond.exit (md2)
1229bdd1243dSDimitry Andric   // |       |
1230bdd1243dSDimitry Andric   // |_______|
1231bdd1243dSDimitry Andric   //
1232bdd1243dSDimitry Andric   // CFG After
1233bdd1243dSDimitry Andric   //
1234bdd1243dSDimitry Andric   // while.cond1 is the merge of while.cond.exit and while.cond above.
1235bdd1243dSDimitry Andric   // for.body is attached with md2, and md1 is dropped.
1236bdd1243dSDimitry Andric   // If LoopSimplify runs later (as a part of loop pass), it could create
1237bdd1243dSDimitry Andric   // dedicated exits for inner-loop (essentially adding `while.cond.exit`
1238bdd1243dSDimitry Andric   // back), but won't it won't see 'md1' nor restore it for the inner-loop.
1239bdd1243dSDimitry Andric   //
1240bdd1243dSDimitry Andric   //       entry
1241bdd1243dSDimitry Andric   //         |
1242bdd1243dSDimitry Andric   //         v
1243bdd1243dSDimitry Andric   // ---> while.cond1  ------------->  while.end
1244bdd1243dSDimitry Andric   // |       |
1245bdd1243dSDimitry Andric   // |       v
1246bdd1243dSDimitry Andric   // |   while.body
1247bdd1243dSDimitry Andric   // |       |
1248bdd1243dSDimitry Andric   // |       v
1249bdd1243dSDimitry Andric   // |    for.body <---- (md2)
1250bdd1243dSDimitry Andric   // |_______|  |______|
1251bdd1243dSDimitry Andric   if (Instruction *TI = BB->getTerminator())
1252bdd1243dSDimitry Andric     if (TI->hasMetadata(LLVMContext::MD_loop))
1253bdd1243dSDimitry Andric       for (BasicBlock *Pred : predecessors(BB))
1254bdd1243dSDimitry Andric         if (Instruction *PredTI = Pred->getTerminator())
1255bdd1243dSDimitry Andric           if (PredTI->hasMetadata(LLVMContext::MD_loop))
12560b57cec5SDimitry Andric             return false;
12570b57cec5SDimitry Andric 
12585f757f3fSDimitry Andric   if (BBKillable)
12590b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
12605f757f3fSDimitry Andric   else if (BBPhisMergeable)
12615f757f3fSDimitry Andric     LLVM_DEBUG(dbgs() << "Merge Phis in Trivial BB: \n" << *BB);
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric   SmallVector<DominatorTree::UpdateType, 32> Updates;
12645f757f3fSDimitry Andric 
12650b57cec5SDimitry Andric   if (DTU) {
12664824e7fdSDimitry Andric     // To avoid processing the same predecessor more than once.
12674824e7fdSDimitry Andric     SmallPtrSet<BasicBlock *, 8> SeenPreds;
12685f757f3fSDimitry Andric     // All predecessors of BB (except the common predecessor) will be moved to
12695f757f3fSDimitry Andric     // Succ.
12704824e7fdSDimitry Andric     Updates.reserve(Updates.size() + 2 * pred_size(BB) + 1);
12715f757f3fSDimitry Andric 
12725f757f3fSDimitry Andric     for (auto *PredOfBB : predecessors(BB)) {
12735f757f3fSDimitry Andric       // Do not modify those common predecessors of BB and Succ
12745f757f3fSDimitry Andric       if (!SuccPreds.contains(PredOfBB))
12754824e7fdSDimitry Andric         if (SeenPreds.insert(PredOfBB).second)
1276fe6060f1SDimitry Andric           Updates.push_back({DominatorTree::Insert, PredOfBB, Succ});
12775f757f3fSDimitry Andric     }
12785f757f3fSDimitry Andric 
12794824e7fdSDimitry Andric     SeenPreds.clear();
12805f757f3fSDimitry Andric 
12814824e7fdSDimitry Andric     for (auto *PredOfBB : predecessors(BB))
12825f757f3fSDimitry Andric       // When BB cannot be killed, do not remove the edge between BB and
12835f757f3fSDimitry Andric       // CommonPred.
12845f757f3fSDimitry Andric       if (SeenPreds.insert(PredOfBB).second && PredOfBB != CommonPred)
1285fe6060f1SDimitry Andric         Updates.push_back({DominatorTree::Delete, PredOfBB, BB});
12865f757f3fSDimitry Andric 
12875f757f3fSDimitry Andric     if (BBKillable)
1288e8d8bef9SDimitry Andric       Updates.push_back({DominatorTree::Delete, BB, Succ});
12890b57cec5SDimitry Andric   }
12900b57cec5SDimitry Andric 
12910b57cec5SDimitry Andric   if (isa<PHINode>(Succ->begin())) {
12920b57cec5SDimitry Andric     // If there is more than one pred of succ, and there are PHI nodes in
12930b57cec5SDimitry Andric     // the successor, then we need to add incoming edges for the PHI nodes
12940b57cec5SDimitry Andric     //
129581ad6265SDimitry Andric     const PredBlockVector BBPreds(predecessors(BB));
12960b57cec5SDimitry Andric 
12970b57cec5SDimitry Andric     // Loop over all of the PHI nodes in the successor of BB.
12980b57cec5SDimitry Andric     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
12990b57cec5SDimitry Andric       PHINode *PN = cast<PHINode>(I);
13005f757f3fSDimitry Andric       redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN, CommonPred);
13010b57cec5SDimitry Andric     }
13020b57cec5SDimitry Andric   }
13030b57cec5SDimitry Andric 
13040b57cec5SDimitry Andric   if (Succ->getSinglePredecessor()) {
13050b57cec5SDimitry Andric     // BB is the only predecessor of Succ, so Succ will end up with exactly
13060b57cec5SDimitry Andric     // the same predecessors BB had.
13070b57cec5SDimitry Andric     // Copy over any phi, debug or lifetime instruction.
13080b57cec5SDimitry Andric     BB->getTerminator()->eraseFromParent();
13095f757f3fSDimitry Andric     Succ->splice(Succ->getFirstNonPHIIt(), BB);
13100b57cec5SDimitry Andric   } else {
13110b57cec5SDimitry Andric     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
13125f757f3fSDimitry Andric       // We explicitly check for such uses for merging phis.
13130b57cec5SDimitry Andric       assert(PN->use_empty() && "There shouldn't be any uses here!");
13140b57cec5SDimitry Andric       PN->eraseFromParent();
13150b57cec5SDimitry Andric     }
13160b57cec5SDimitry Andric   }
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric   // If the unconditional branch we replaced contains llvm.loop metadata, we
13190b57cec5SDimitry Andric   // add the metadata to the branch instructions in the predecessors.
132006c3fb27SDimitry Andric   if (Instruction *TI = BB->getTerminator())
132106c3fb27SDimitry Andric     if (MDNode *LoopMD = TI->getMetadata(LLVMContext::MD_loop))
1322fe6060f1SDimitry Andric       for (BasicBlock *Pred : predecessors(BB))
132306c3fb27SDimitry Andric         Pred->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopMD);
13240b57cec5SDimitry Andric 
13255f757f3fSDimitry Andric   if (BBKillable) {
13260b57cec5SDimitry Andric     // Everything that jumped to BB now goes to Succ.
13270b57cec5SDimitry Andric     BB->replaceAllUsesWith(Succ);
13285f757f3fSDimitry Andric 
13295f757f3fSDimitry Andric     if (!Succ->hasName())
13305f757f3fSDimitry Andric       Succ->takeName(BB);
13310b57cec5SDimitry Andric 
13320b57cec5SDimitry Andric     // Clear the successor list of BB to match updates applying to DTU later.
13330b57cec5SDimitry Andric     if (BB->getTerminator())
1334bdd1243dSDimitry Andric       BB->back().eraseFromParent();
13355f757f3fSDimitry Andric 
13360b57cec5SDimitry Andric     new UnreachableInst(BB->getContext(), BB);
13370b57cec5SDimitry Andric     assert(succ_empty(BB) && "The successor list of BB isn't empty before "
13380b57cec5SDimitry Andric                              "applying corresponding DTU updates.");
13395f757f3fSDimitry Andric   } else if (BBPhisMergeable) {
13405f757f3fSDimitry Andric     //  Everything except CommonPred that jumped to BB now goes to Succ.
13415f757f3fSDimitry Andric     BB->replaceUsesWithIf(Succ, [BBPreds, CommonPred](Use &U) -> bool {
13425f757f3fSDimitry Andric       if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser()))
13435f757f3fSDimitry Andric         return UseInst->getParent() != CommonPred &&
13445f757f3fSDimitry Andric                BBPreds.contains(UseInst->getParent());
13455f757f3fSDimitry Andric       return false;
13465f757f3fSDimitry Andric     });
13475f757f3fSDimitry Andric   }
13480b57cec5SDimitry Andric 
1349fe6060f1SDimitry Andric   if (DTU)
1350e8d8bef9SDimitry Andric     DTU->applyUpdates(Updates);
1351fe6060f1SDimitry Andric 
13525f757f3fSDimitry Andric   if (BBKillable)
1353fe6060f1SDimitry Andric     DeleteDeadBlock(BB, DTU);
1354fe6060f1SDimitry Andric 
13550b57cec5SDimitry Andric   return true;
13560b57cec5SDimitry Andric }
13570b57cec5SDimitry Andric 
13584542f901SDimitry Andric static bool
13594542f901SDimitry Andric EliminateDuplicatePHINodesNaiveImpl(BasicBlock *BB,
13604542f901SDimitry Andric                                     SmallPtrSetImpl<PHINode *> &ToRemove) {
1361e8d8bef9SDimitry Andric   // This implementation doesn't currently consider undef operands
1362e8d8bef9SDimitry Andric   // specially. Theoretically, two phis which are identical except for
1363e8d8bef9SDimitry Andric   // one having an undef where the other doesn't could be collapsed.
1364e8d8bef9SDimitry Andric 
1365e8d8bef9SDimitry Andric   bool Changed = false;
1366e8d8bef9SDimitry Andric 
1367e8d8bef9SDimitry Andric   // Examine each PHI.
1368e8d8bef9SDimitry Andric   // Note that increment of I must *NOT* be in the iteration_expression, since
1369e8d8bef9SDimitry Andric   // we don't want to immediately advance when we restart from the beginning.
1370e8d8bef9SDimitry Andric   for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I);) {
1371e8d8bef9SDimitry Andric     ++I;
1372e8d8bef9SDimitry Andric     // Is there an identical PHI node in this basic block?
1373e8d8bef9SDimitry Andric     // Note that we only look in the upper square's triangle,
1374e8d8bef9SDimitry Andric     // we already checked that the lower triangle PHI's aren't identical.
1375e8d8bef9SDimitry Andric     for (auto J = I; PHINode *DuplicatePN = dyn_cast<PHINode>(J); ++J) {
13764542f901SDimitry Andric       if (ToRemove.contains(DuplicatePN))
13774542f901SDimitry Andric         continue;
1378e8d8bef9SDimitry Andric       if (!DuplicatePN->isIdenticalToWhenDefined(PN))
1379e8d8bef9SDimitry Andric         continue;
1380e8d8bef9SDimitry Andric       // A duplicate. Replace this PHI with the base PHI.
1381e8d8bef9SDimitry Andric       ++NumPHICSEs;
1382e8d8bef9SDimitry Andric       DuplicatePN->replaceAllUsesWith(PN);
13834542f901SDimitry Andric       ToRemove.insert(DuplicatePN);
1384e8d8bef9SDimitry Andric       Changed = true;
1385e8d8bef9SDimitry Andric 
1386e8d8bef9SDimitry Andric       // The RAUW can change PHIs that we already visited.
1387e8d8bef9SDimitry Andric       I = BB->begin();
1388e8d8bef9SDimitry Andric       break; // Start over from the beginning.
1389e8d8bef9SDimitry Andric     }
1390e8d8bef9SDimitry Andric   }
1391e8d8bef9SDimitry Andric   return Changed;
1392e8d8bef9SDimitry Andric }
1393e8d8bef9SDimitry Andric 
13944542f901SDimitry Andric static bool
13954542f901SDimitry Andric EliminateDuplicatePHINodesSetBasedImpl(BasicBlock *BB,
13964542f901SDimitry Andric                                        SmallPtrSetImpl<PHINode *> &ToRemove) {
13970b57cec5SDimitry Andric   // This implementation doesn't currently consider undef operands
13980b57cec5SDimitry Andric   // specially. Theoretically, two phis which are identical except for
13990b57cec5SDimitry Andric   // one having an undef where the other doesn't could be collapsed.
14000b57cec5SDimitry Andric 
14010b57cec5SDimitry Andric   struct PHIDenseMapInfo {
14020b57cec5SDimitry Andric     static PHINode *getEmptyKey() {
14030b57cec5SDimitry Andric       return DenseMapInfo<PHINode *>::getEmptyKey();
14040b57cec5SDimitry Andric     }
14050b57cec5SDimitry Andric 
14060b57cec5SDimitry Andric     static PHINode *getTombstoneKey() {
14070b57cec5SDimitry Andric       return DenseMapInfo<PHINode *>::getTombstoneKey();
14080b57cec5SDimitry Andric     }
14090b57cec5SDimitry Andric 
1410e8d8bef9SDimitry Andric     static bool isSentinel(PHINode *PN) {
1411e8d8bef9SDimitry Andric       return PN == getEmptyKey() || PN == getTombstoneKey();
1412e8d8bef9SDimitry Andric     }
1413e8d8bef9SDimitry Andric 
1414e8d8bef9SDimitry Andric     // WARNING: this logic must be kept in sync with
1415e8d8bef9SDimitry Andric     //          Instruction::isIdenticalToWhenDefined()!
1416e8d8bef9SDimitry Andric     static unsigned getHashValueImpl(PHINode *PN) {
14170b57cec5SDimitry Andric       // Compute a hash value on the operands. Instcombine will likely have
14180b57cec5SDimitry Andric       // sorted them, which helps expose duplicates, but we have to check all
14190b57cec5SDimitry Andric       // the operands to be safe in case instcombine hasn't run.
14200b57cec5SDimitry Andric       return static_cast<unsigned>(hash_combine(
14210b57cec5SDimitry Andric           hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
14220b57cec5SDimitry Andric           hash_combine_range(PN->block_begin(), PN->block_end())));
14230b57cec5SDimitry Andric     }
14240b57cec5SDimitry Andric 
1425e8d8bef9SDimitry Andric     static unsigned getHashValue(PHINode *PN) {
1426e8d8bef9SDimitry Andric #ifndef NDEBUG
1427e8d8bef9SDimitry Andric       // If -phicse-debug-hash was specified, return a constant -- this
1428e8d8bef9SDimitry Andric       // will force all hashing to collide, so we'll exhaustively search
1429e8d8bef9SDimitry Andric       // the table for a match, and the assertion in isEqual will fire if
1430e8d8bef9SDimitry Andric       // there's a bug causing equal keys to hash differently.
1431e8d8bef9SDimitry Andric       if (PHICSEDebugHash)
1432e8d8bef9SDimitry Andric         return 0;
1433e8d8bef9SDimitry Andric #endif
1434e8d8bef9SDimitry Andric       return getHashValueImpl(PN);
1435e8d8bef9SDimitry Andric     }
1436e8d8bef9SDimitry Andric 
1437e8d8bef9SDimitry Andric     static bool isEqualImpl(PHINode *LHS, PHINode *RHS) {
1438e8d8bef9SDimitry Andric       if (isSentinel(LHS) || isSentinel(RHS))
14390b57cec5SDimitry Andric         return LHS == RHS;
14400b57cec5SDimitry Andric       return LHS->isIdenticalTo(RHS);
14410b57cec5SDimitry Andric     }
1442e8d8bef9SDimitry Andric 
1443e8d8bef9SDimitry Andric     static bool isEqual(PHINode *LHS, PHINode *RHS) {
1444e8d8bef9SDimitry Andric       // These comparisons are nontrivial, so assert that equality implies
1445e8d8bef9SDimitry Andric       // hash equality (DenseMap demands this as an invariant).
1446e8d8bef9SDimitry Andric       bool Result = isEqualImpl(LHS, RHS);
1447e8d8bef9SDimitry Andric       assert(!Result || (isSentinel(LHS) && LHS == RHS) ||
1448e8d8bef9SDimitry Andric              getHashValueImpl(LHS) == getHashValueImpl(RHS));
1449e8d8bef9SDimitry Andric       return Result;
1450e8d8bef9SDimitry Andric     }
14510b57cec5SDimitry Andric   };
14520b57cec5SDimitry Andric 
14530b57cec5SDimitry Andric   // Set of unique PHINodes.
14540b57cec5SDimitry Andric   DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
1455e8d8bef9SDimitry Andric   PHISet.reserve(4 * PHICSENumPHISmallSize);
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric   // Examine each PHI.
14580b57cec5SDimitry Andric   bool Changed = false;
14590b57cec5SDimitry Andric   for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
14604542f901SDimitry Andric     if (ToRemove.contains(PN))
14614542f901SDimitry Andric       continue;
14620b57cec5SDimitry Andric     auto Inserted = PHISet.insert(PN);
14630b57cec5SDimitry Andric     if (!Inserted.second) {
14640b57cec5SDimitry Andric       // A duplicate. Replace this PHI with its duplicate.
1465e8d8bef9SDimitry Andric       ++NumPHICSEs;
14660b57cec5SDimitry Andric       PN->replaceAllUsesWith(*Inserted.first);
14674542f901SDimitry Andric       ToRemove.insert(PN);
14680b57cec5SDimitry Andric       Changed = true;
14690b57cec5SDimitry Andric 
14700b57cec5SDimitry Andric       // The RAUW can change PHIs that we already visited. Start over from the
14710b57cec5SDimitry Andric       // beginning.
14720b57cec5SDimitry Andric       PHISet.clear();
14730b57cec5SDimitry Andric       I = BB->begin();
14740b57cec5SDimitry Andric     }
14750b57cec5SDimitry Andric   }
14760b57cec5SDimitry Andric 
14770b57cec5SDimitry Andric   return Changed;
14780b57cec5SDimitry Andric }
14790b57cec5SDimitry Andric 
14804542f901SDimitry Andric bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB,
14814542f901SDimitry Andric                                       SmallPtrSetImpl<PHINode *> &ToRemove) {
1482e8d8bef9SDimitry Andric   if (
1483e8d8bef9SDimitry Andric #ifndef NDEBUG
1484e8d8bef9SDimitry Andric       !PHICSEDebugHash &&
1485e8d8bef9SDimitry Andric #endif
1486e8d8bef9SDimitry Andric       hasNItemsOrLess(BB->phis(), PHICSENumPHISmallSize))
14874542f901SDimitry Andric     return EliminateDuplicatePHINodesNaiveImpl(BB, ToRemove);
14884542f901SDimitry Andric   return EliminateDuplicatePHINodesSetBasedImpl(BB, ToRemove);
14894542f901SDimitry Andric }
14904542f901SDimitry Andric 
14914542f901SDimitry Andric bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
14924542f901SDimitry Andric   SmallPtrSet<PHINode *, 8> ToRemove;
14934542f901SDimitry Andric   bool Changed = EliminateDuplicatePHINodes(BB, ToRemove);
14944542f901SDimitry Andric   for (PHINode *PN : ToRemove)
14954542f901SDimitry Andric     PN->eraseFromParent();
14964542f901SDimitry Andric   return Changed;
1497e8d8bef9SDimitry Andric }
14980b57cec5SDimitry Andric 
14995f757f3fSDimitry Andric Align llvm::tryEnforceAlignment(Value *V, Align PrefAlign,
1500e8d8bef9SDimitry Andric                                 const DataLayout &DL) {
15010b57cec5SDimitry Andric   V = V->stripPointerCasts();
15020b57cec5SDimitry Andric 
15030b57cec5SDimitry Andric   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1504e8d8bef9SDimitry Andric     // TODO: Ideally, this function would not be called if PrefAlign is smaller
1505e8d8bef9SDimitry Andric     // than the current alignment, as the known bits calculation should have
1506e8d8bef9SDimitry Andric     // already taken it into account. However, this is not always the case,
1507e8d8bef9SDimitry Andric     // as computeKnownBits() has a depth limit, while stripPointerCasts()
1508e8d8bef9SDimitry Andric     // doesn't.
1509e8d8bef9SDimitry Andric     Align CurrentAlign = AI->getAlign();
1510e8d8bef9SDimitry Andric     if (PrefAlign <= CurrentAlign)
1511e8d8bef9SDimitry Andric       return CurrentAlign;
15120b57cec5SDimitry Andric 
15130b57cec5SDimitry Andric     // If the preferred alignment is greater than the natural stack alignment
15140b57cec5SDimitry Andric     // then don't round up. This avoids dynamic stack realignment.
15155ffd83dbSDimitry Andric     if (DL.exceedsNaturalStackAlignment(PrefAlign))
1516e8d8bef9SDimitry Andric       return CurrentAlign;
15175ffd83dbSDimitry Andric     AI->setAlignment(PrefAlign);
15180b57cec5SDimitry Andric     return PrefAlign;
15190b57cec5SDimitry Andric   }
15200b57cec5SDimitry Andric 
15210b57cec5SDimitry Andric   if (auto *GO = dyn_cast<GlobalObject>(V)) {
15220b57cec5SDimitry Andric     // TODO: as above, this shouldn't be necessary.
1523e8d8bef9SDimitry Andric     Align CurrentAlign = GO->getPointerAlignment(DL);
1524e8d8bef9SDimitry Andric     if (PrefAlign <= CurrentAlign)
1525e8d8bef9SDimitry Andric       return CurrentAlign;
15260b57cec5SDimitry Andric 
15270b57cec5SDimitry Andric     // If there is a large requested alignment and we can, bump up the alignment
15280b57cec5SDimitry Andric     // of the global.  If the memory we set aside for the global may not be the
15290b57cec5SDimitry Andric     // memory used by the final program then it is impossible for us to reliably
15300b57cec5SDimitry Andric     // enforce the preferred alignment.
15310b57cec5SDimitry Andric     if (!GO->canIncreaseAlignment())
1532e8d8bef9SDimitry Andric       return CurrentAlign;
15330b57cec5SDimitry Andric 
153406c3fb27SDimitry Andric     if (GO->isThreadLocal()) {
153506c3fb27SDimitry Andric       unsigned MaxTLSAlign = GO->getParent()->getMaxTLSAlignment() / CHAR_BIT;
153606c3fb27SDimitry Andric       if (MaxTLSAlign && PrefAlign > Align(MaxTLSAlign))
153706c3fb27SDimitry Andric         PrefAlign = Align(MaxTLSAlign);
153806c3fb27SDimitry Andric     }
153906c3fb27SDimitry Andric 
15405ffd83dbSDimitry Andric     GO->setAlignment(PrefAlign);
15410b57cec5SDimitry Andric     return PrefAlign;
15420b57cec5SDimitry Andric   }
15430b57cec5SDimitry Andric 
1544e8d8bef9SDimitry Andric   return Align(1);
15450b57cec5SDimitry Andric }
15460b57cec5SDimitry Andric 
15475ffd83dbSDimitry Andric Align llvm::getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign,
15480b57cec5SDimitry Andric                                        const DataLayout &DL,
15490b57cec5SDimitry Andric                                        const Instruction *CxtI,
15500b57cec5SDimitry Andric                                        AssumptionCache *AC,
15510b57cec5SDimitry Andric                                        const DominatorTree *DT) {
15520b57cec5SDimitry Andric   assert(V->getType()->isPointerTy() &&
15530b57cec5SDimitry Andric          "getOrEnforceKnownAlignment expects a pointer!");
15540b57cec5SDimitry Andric 
15550b57cec5SDimitry Andric   KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);
15560b57cec5SDimitry Andric   unsigned TrailZ = Known.countMinTrailingZeros();
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric   // Avoid trouble with ridiculously large TrailZ values, such as
15590b57cec5SDimitry Andric   // those computed from a null pointer.
15605ffd83dbSDimitry Andric   // LLVM doesn't support alignments larger than (1 << MaxAlignmentExponent).
15615ffd83dbSDimitry Andric   TrailZ = std::min(TrailZ, +Value::MaxAlignmentExponent);
15620b57cec5SDimitry Andric 
15635ffd83dbSDimitry Andric   Align Alignment = Align(1ull << std::min(Known.getBitWidth() - 1, TrailZ));
15640b57cec5SDimitry Andric 
15655ffd83dbSDimitry Andric   if (PrefAlign && *PrefAlign > Alignment)
1566e8d8bef9SDimitry Andric     Alignment = std::max(Alignment, tryEnforceAlignment(V, *PrefAlign, DL));
15670b57cec5SDimitry Andric 
15680b57cec5SDimitry Andric   // We don't need to make any adjustment.
15695ffd83dbSDimitry Andric   return Alignment;
15700b57cec5SDimitry Andric }
15710b57cec5SDimitry Andric 
15720b57cec5SDimitry Andric ///===---------------------------------------------------------------------===//
15730b57cec5SDimitry Andric ///  Dbg Intrinsic utilities
15740b57cec5SDimitry Andric ///
15750b57cec5SDimitry Andric 
15760b57cec5SDimitry Andric /// See if there is a dbg.value intrinsic for DIVar for the PHI node.
15770b57cec5SDimitry Andric static bool PhiHasDebugValue(DILocalVariable *DIVar,
15780b57cec5SDimitry Andric                              DIExpression *DIExpr,
15790b57cec5SDimitry Andric                              PHINode *APN) {
158081ad6265SDimitry Andric   // Since we can't guarantee that the original dbg.declare intrinsic
15810b57cec5SDimitry Andric   // is removed by LowerDbgDeclare(), we need to make sure that we are
15820b57cec5SDimitry Andric   // not inserting the same dbg.value intrinsic over and over.
15830b57cec5SDimitry Andric   SmallVector<DbgValueInst *, 1> DbgValues;
15840fca6ea1SDimitry Andric   SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
15850fca6ea1SDimitry Andric   findDbgValues(DbgValues, APN, &DbgVariableRecords);
15860b57cec5SDimitry Andric   for (auto *DVI : DbgValues) {
1587fe6060f1SDimitry Andric     assert(is_contained(DVI->getValues(), APN));
15880b57cec5SDimitry Andric     if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
15890b57cec5SDimitry Andric       return true;
15900b57cec5SDimitry Andric   }
15910fca6ea1SDimitry Andric   for (auto *DVR : DbgVariableRecords) {
15920fca6ea1SDimitry Andric     assert(is_contained(DVR->location_ops(), APN));
15930fca6ea1SDimitry Andric     if ((DVR->getVariable() == DIVar) && (DVR->getExpression() == DIExpr))
15945f757f3fSDimitry Andric       return true;
15955f757f3fSDimitry Andric   }
15960b57cec5SDimitry Andric   return false;
15970b57cec5SDimitry Andric }
15980b57cec5SDimitry Andric 
15990b57cec5SDimitry Andric /// Check if the alloc size of \p ValTy is large enough to cover the variable
16000b57cec5SDimitry Andric /// (or fragment of the variable) described by \p DII.
16010b57cec5SDimitry Andric ///
16020b57cec5SDimitry Andric /// This is primarily intended as a helper for the different
160306c3fb27SDimitry Andric /// ConvertDebugDeclareToDebugValue functions. The dbg.declare that is converted
160406c3fb27SDimitry Andric /// describes an alloca'd variable, so we need to use the alloc size of the
160506c3fb27SDimitry Andric /// value when doing the comparison. E.g. an i1 value will be identified as
160606c3fb27SDimitry Andric /// covering an n-bit fragment, if the store size of i1 is at least n bits.
16070b57cec5SDimitry Andric static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {
16080fca6ea1SDimitry Andric   const DataLayout &DL = DII->getDataLayout();
1609e8d8bef9SDimitry Andric   TypeSize ValueSize = DL.getTypeAllocSizeInBits(ValTy);
16100fca6ea1SDimitry Andric   if (std::optional<uint64_t> FragmentSize =
16110fca6ea1SDimitry Andric           DII->getExpression()->getActiveBits(DII->getVariable()))
161206c3fb27SDimitry Andric     return TypeSize::isKnownGE(ValueSize, TypeSize::getFixed(*FragmentSize));
161306c3fb27SDimitry Andric 
16140b57cec5SDimitry Andric   // We can't always calculate the size of the DI variable (e.g. if it is a
16150b57cec5SDimitry Andric   // VLA). Try to use the size of the alloca that the dbg intrinsic describes
16160b57cec5SDimitry Andric   // intead.
1617fe6060f1SDimitry Andric   if (DII->isAddressOfVariable()) {
1618fe6060f1SDimitry Andric     // DII should have exactly 1 location when it is an address.
1619fe6060f1SDimitry Andric     assert(DII->getNumVariableLocationOps() == 1 &&
1620fe6060f1SDimitry Andric            "address of variable must have exactly 1 location operand.");
1621fe6060f1SDimitry Andric     if (auto *AI =
1622fe6060f1SDimitry Andric             dyn_cast_or_null<AllocaInst>(DII->getVariableLocationOp(0))) {
1623bdd1243dSDimitry Andric       if (std::optional<TypeSize> FragmentSize =
1624bdd1243dSDimitry Andric               AI->getAllocationSizeInBits(DL)) {
1625e8d8bef9SDimitry Andric         return TypeSize::isKnownGE(ValueSize, *FragmentSize);
1626e8d8bef9SDimitry Andric       }
1627fe6060f1SDimitry Andric     }
1628fe6060f1SDimitry Andric   }
16290b57cec5SDimitry Andric   // Could not determine size of variable. Conservatively return false.
16300b57cec5SDimitry Andric   return false;
16310b57cec5SDimitry Andric }
16320fca6ea1SDimitry Andric // RemoveDIs: duplicate implementation of the above, using DbgVariableRecords,
16330fca6ea1SDimitry Andric // the replacement for dbg.values.
16340fca6ea1SDimitry Andric static bool valueCoversEntireFragment(Type *ValTy, DbgVariableRecord *DVR) {
16350fca6ea1SDimitry Andric   const DataLayout &DL = DVR->getModule()->getDataLayout();
16365f757f3fSDimitry Andric   TypeSize ValueSize = DL.getTypeAllocSizeInBits(ValTy);
16370fca6ea1SDimitry Andric   if (std::optional<uint64_t> FragmentSize =
16380fca6ea1SDimitry Andric           DVR->getExpression()->getActiveBits(DVR->getVariable()))
16395f757f3fSDimitry Andric     return TypeSize::isKnownGE(ValueSize, TypeSize::getFixed(*FragmentSize));
16405f757f3fSDimitry Andric 
16415f757f3fSDimitry Andric   // We can't always calculate the size of the DI variable (e.g. if it is a
16425f757f3fSDimitry Andric   // VLA). Try to use the size of the alloca that the dbg intrinsic describes
16435f757f3fSDimitry Andric   // intead.
16440fca6ea1SDimitry Andric   if (DVR->isAddressOfVariable()) {
16450fca6ea1SDimitry Andric     // DVR should have exactly 1 location when it is an address.
16460fca6ea1SDimitry Andric     assert(DVR->getNumVariableLocationOps() == 1 &&
16475f757f3fSDimitry Andric            "address of variable must have exactly 1 location operand.");
16485f757f3fSDimitry Andric     if (auto *AI =
16490fca6ea1SDimitry Andric             dyn_cast_or_null<AllocaInst>(DVR->getVariableLocationOp(0))) {
16505f757f3fSDimitry Andric       if (std::optional<TypeSize> FragmentSize = AI->getAllocationSizeInBits(DL)) {
16515f757f3fSDimitry Andric         return TypeSize::isKnownGE(ValueSize, *FragmentSize);
16525f757f3fSDimitry Andric       }
16535f757f3fSDimitry Andric     }
16545f757f3fSDimitry Andric   }
16555f757f3fSDimitry Andric   // Could not determine size of variable. Conservatively return false.
16565f757f3fSDimitry Andric   return false;
16575f757f3fSDimitry Andric }
16585f757f3fSDimitry Andric 
16590fca6ea1SDimitry Andric static void insertDbgValueOrDbgVariableRecord(DIBuilder &Builder, Value *DV,
16605f757f3fSDimitry Andric                                               DILocalVariable *DIVar,
16615f757f3fSDimitry Andric                                               DIExpression *DIExpr,
16625f757f3fSDimitry Andric                                               const DebugLoc &NewLoc,
16635f757f3fSDimitry Andric                                               BasicBlock::iterator Instr) {
16645f757f3fSDimitry Andric   if (!UseNewDbgInfoFormat) {
16650fca6ea1SDimitry Andric     auto DbgVal = Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc,
16665f757f3fSDimitry Andric                                                   (Instruction *)nullptr);
16670fca6ea1SDimitry Andric     DbgVal.get<Instruction *>()->insertBefore(Instr);
16685f757f3fSDimitry Andric   } else {
16695f757f3fSDimitry Andric     // RemoveDIs: if we're using the new debug-info format, allocate a
16700fca6ea1SDimitry Andric     // DbgVariableRecord directly instead of a dbg.value intrinsic.
16715f757f3fSDimitry Andric     ValueAsMetadata *DVAM = ValueAsMetadata::get(DV);
16720fca6ea1SDimitry Andric     DbgVariableRecord *DV =
16730fca6ea1SDimitry Andric         new DbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());
16740fca6ea1SDimitry Andric     Instr->getParent()->insertDbgRecordBefore(DV, Instr);
16755f757f3fSDimitry Andric   }
16765f757f3fSDimitry Andric }
16775f757f3fSDimitry Andric 
16780fca6ea1SDimitry Andric static void insertDbgValueOrDbgVariableRecordAfter(
16790fca6ea1SDimitry Andric     DIBuilder &Builder, Value *DV, DILocalVariable *DIVar, DIExpression *DIExpr,
16800fca6ea1SDimitry Andric     const DebugLoc &NewLoc, BasicBlock::iterator Instr) {
16815f757f3fSDimitry Andric   if (!UseNewDbgInfoFormat) {
16820fca6ea1SDimitry Andric     auto DbgVal = Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc,
16835f757f3fSDimitry Andric                                                   (Instruction *)nullptr);
16840fca6ea1SDimitry Andric     DbgVal.get<Instruction *>()->insertAfter(&*Instr);
16855f757f3fSDimitry Andric   } else {
16865f757f3fSDimitry Andric     // RemoveDIs: if we're using the new debug-info format, allocate a
16870fca6ea1SDimitry Andric     // DbgVariableRecord directly instead of a dbg.value intrinsic.
16885f757f3fSDimitry Andric     ValueAsMetadata *DVAM = ValueAsMetadata::get(DV);
16890fca6ea1SDimitry Andric     DbgVariableRecord *DV =
16900fca6ea1SDimitry Andric         new DbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());
16910fca6ea1SDimitry Andric     Instr->getParent()->insertDbgRecordAfter(DV, &*Instr);
16925f757f3fSDimitry Andric   }
16935f757f3fSDimitry Andric }
16940b57cec5SDimitry Andric 
16950b57cec5SDimitry Andric /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
169606c3fb27SDimitry Andric /// that has an associated llvm.dbg.declare intrinsic.
16970b57cec5SDimitry Andric void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
16980b57cec5SDimitry Andric                                            StoreInst *SI, DIBuilder &Builder) {
1699bdd1243dSDimitry Andric   assert(DII->isAddressOfVariable() || isa<DbgAssignIntrinsic>(DII));
17000b57cec5SDimitry Andric   auto *DIVar = DII->getVariable();
17010b57cec5SDimitry Andric   assert(DIVar && "Missing variable");
17020b57cec5SDimitry Andric   auto *DIExpr = DII->getExpression();
17030b57cec5SDimitry Andric   Value *DV = SI->getValueOperand();
17040b57cec5SDimitry Andric 
1705bdd1243dSDimitry Andric   DebugLoc NewLoc = getDebugValueLoc(DII);
17060b57cec5SDimitry Andric 
170706c3fb27SDimitry Andric   // If the alloca describes the variable itself, i.e. the expression in the
170806c3fb27SDimitry Andric   // dbg.declare doesn't start with a dereference, we can perform the
170906c3fb27SDimitry Andric   // conversion if the value covers the entire fragment of DII.
171006c3fb27SDimitry Andric   // If the alloca describes the *address* of DIVar, i.e. DIExpr is
171106c3fb27SDimitry Andric   // *just* a DW_OP_deref, we use DV as is for the dbg.value.
171206c3fb27SDimitry Andric   // We conservatively ignore other dereferences, because the following two are
171306c3fb27SDimitry Andric   // not equivalent:
171406c3fb27SDimitry Andric   //     dbg.declare(alloca, ..., !Expr(deref, plus_uconstant, 2))
171506c3fb27SDimitry Andric   //     dbg.value(DV, ..., !Expr(deref, plus_uconstant, 2))
171606c3fb27SDimitry Andric   // The former is adding 2 to the address of the variable, whereas the latter
171706c3fb27SDimitry Andric   // is adding 2 to the value of the variable. As such, we insist on just a
171806c3fb27SDimitry Andric   // deref expression.
171906c3fb27SDimitry Andric   bool CanConvert =
172006c3fb27SDimitry Andric       DIExpr->isDeref() || (!DIExpr->startsWithDeref() &&
172106c3fb27SDimitry Andric                             valueCoversEntireFragment(DV->getType(), DII));
172206c3fb27SDimitry Andric   if (CanConvert) {
17230fca6ea1SDimitry Andric     insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
17245f757f3fSDimitry Andric                                       SI->getIterator());
172506c3fb27SDimitry Andric     return;
172606c3fb27SDimitry Andric   }
172706c3fb27SDimitry Andric 
17280b57cec5SDimitry Andric   // FIXME: If storing to a part of the variable described by the dbg.declare,
17290b57cec5SDimitry Andric   // then we want to insert a dbg.value for the corresponding fragment.
173006c3fb27SDimitry Andric   LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: " << *DII
173106c3fb27SDimitry Andric                     << '\n');
17320b57cec5SDimitry Andric   // For now, when there is a store to parts of the variable (but we do not
173381ad6265SDimitry Andric   // know which part) we insert an dbg.value intrinsic to indicate that we
17340b57cec5SDimitry Andric   // know nothing about the variable's content.
17350b57cec5SDimitry Andric   DV = UndefValue::get(DV->getType());
17360fca6ea1SDimitry Andric   insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
17375f757f3fSDimitry Andric                                     SI->getIterator());
17380b57cec5SDimitry Andric }
17390b57cec5SDimitry Andric 
17400b57cec5SDimitry Andric /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
174106c3fb27SDimitry Andric /// that has an associated llvm.dbg.declare intrinsic.
17420b57cec5SDimitry Andric void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
17430b57cec5SDimitry Andric                                            LoadInst *LI, DIBuilder &Builder) {
17440b57cec5SDimitry Andric   auto *DIVar = DII->getVariable();
17450b57cec5SDimitry Andric   auto *DIExpr = DII->getExpression();
17460b57cec5SDimitry Andric   assert(DIVar && "Missing variable");
17470b57cec5SDimitry Andric 
17480b57cec5SDimitry Andric   if (!valueCoversEntireFragment(LI->getType(), DII)) {
17490b57cec5SDimitry Andric     // FIXME: If only referring to a part of the variable described by the
17500b57cec5SDimitry Andric     // dbg.declare, then we want to insert a dbg.value for the corresponding
17510b57cec5SDimitry Andric     // fragment.
17520b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
17530b57cec5SDimitry Andric                       << *DII << '\n');
17540b57cec5SDimitry Andric     return;
17550b57cec5SDimitry Andric   }
17560b57cec5SDimitry Andric 
1757bdd1243dSDimitry Andric   DebugLoc NewLoc = getDebugValueLoc(DII);
17580b57cec5SDimitry Andric 
17590b57cec5SDimitry Andric   // We are now tracking the loaded value instead of the address. In the
17600b57cec5SDimitry Andric   // future if multi-location support is added to the IR, it might be
17610b57cec5SDimitry Andric   // preferable to keep tracking both the loaded value and the original
17620b57cec5SDimitry Andric   // address in case the alloca can not be elided.
17630fca6ea1SDimitry Andric   insertDbgValueOrDbgVariableRecordAfter(Builder, LI, DIVar, DIExpr, NewLoc,
17645f757f3fSDimitry Andric                                          LI->getIterator());
17655f757f3fSDimitry Andric }
17665f757f3fSDimitry Andric 
17670fca6ea1SDimitry Andric void llvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
17680fca6ea1SDimitry Andric                                            StoreInst *SI, DIBuilder &Builder) {
17690fca6ea1SDimitry Andric   assert(DVR->isAddressOfVariable() || DVR->isDbgAssign());
17700fca6ea1SDimitry Andric   auto *DIVar = DVR->getVariable();
17715f757f3fSDimitry Andric   assert(DIVar && "Missing variable");
17720fca6ea1SDimitry Andric   auto *DIExpr = DVR->getExpression();
17735f757f3fSDimitry Andric   Value *DV = SI->getValueOperand();
17745f757f3fSDimitry Andric 
17750fca6ea1SDimitry Andric   DebugLoc NewLoc = getDebugValueLoc(DVR);
17765f757f3fSDimitry Andric 
17775f757f3fSDimitry Andric   // If the alloca describes the variable itself, i.e. the expression in the
17785f757f3fSDimitry Andric   // dbg.declare doesn't start with a dereference, we can perform the
17795f757f3fSDimitry Andric   // conversion if the value covers the entire fragment of DII.
17805f757f3fSDimitry Andric   // If the alloca describes the *address* of DIVar, i.e. DIExpr is
17815f757f3fSDimitry Andric   // *just* a DW_OP_deref, we use DV as is for the dbg.value.
17825f757f3fSDimitry Andric   // We conservatively ignore other dereferences, because the following two are
17835f757f3fSDimitry Andric   // not equivalent:
17845f757f3fSDimitry Andric   //     dbg.declare(alloca, ..., !Expr(deref, plus_uconstant, 2))
17855f757f3fSDimitry Andric   //     dbg.value(DV, ..., !Expr(deref, plus_uconstant, 2))
17865f757f3fSDimitry Andric   // The former is adding 2 to the address of the variable, whereas the latter
17875f757f3fSDimitry Andric   // is adding 2 to the value of the variable. As such, we insist on just a
17885f757f3fSDimitry Andric   // deref expression.
17895f757f3fSDimitry Andric   bool CanConvert =
17905f757f3fSDimitry Andric       DIExpr->isDeref() || (!DIExpr->startsWithDeref() &&
17910fca6ea1SDimitry Andric                             valueCoversEntireFragment(DV->getType(), DVR));
17925f757f3fSDimitry Andric   if (CanConvert) {
17930fca6ea1SDimitry Andric     insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
17945f757f3fSDimitry Andric                                       SI->getIterator());
17955f757f3fSDimitry Andric     return;
17965f757f3fSDimitry Andric   }
17975f757f3fSDimitry Andric 
17985f757f3fSDimitry Andric   // FIXME: If storing to a part of the variable described by the dbg.declare,
17995f757f3fSDimitry Andric   // then we want to insert a dbg.value for the corresponding fragment.
18000fca6ea1SDimitry Andric   LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: " << *DVR
18015f757f3fSDimitry Andric                     << '\n');
18025f757f3fSDimitry Andric   assert(UseNewDbgInfoFormat);
18035f757f3fSDimitry Andric 
18045f757f3fSDimitry Andric   // For now, when there is a store to parts of the variable (but we do not
18055f757f3fSDimitry Andric   // know which part) we insert an dbg.value intrinsic to indicate that we
18065f757f3fSDimitry Andric   // know nothing about the variable's content.
18075f757f3fSDimitry Andric   DV = UndefValue::get(DV->getType());
18085f757f3fSDimitry Andric   ValueAsMetadata *DVAM = ValueAsMetadata::get(DV);
18090fca6ea1SDimitry Andric   DbgVariableRecord *NewDVR =
18100fca6ea1SDimitry Andric       new DbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());
18110fca6ea1SDimitry Andric   SI->getParent()->insertDbgRecordBefore(NewDVR, SI->getIterator());
18120b57cec5SDimitry Andric }
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric /// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
181506c3fb27SDimitry Andric /// llvm.dbg.declare intrinsic.
18160b57cec5SDimitry Andric void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
18170b57cec5SDimitry Andric                                            PHINode *APN, DIBuilder &Builder) {
18180b57cec5SDimitry Andric   auto *DIVar = DII->getVariable();
18190b57cec5SDimitry Andric   auto *DIExpr = DII->getExpression();
18200b57cec5SDimitry Andric   assert(DIVar && "Missing variable");
18210b57cec5SDimitry Andric 
18220b57cec5SDimitry Andric   if (PhiHasDebugValue(DIVar, DIExpr, APN))
18230b57cec5SDimitry Andric     return;
18240b57cec5SDimitry Andric 
18250b57cec5SDimitry Andric   if (!valueCoversEntireFragment(APN->getType(), DII)) {
18260b57cec5SDimitry Andric     // FIXME: If only referring to a part of the variable described by the
18270b57cec5SDimitry Andric     // dbg.declare, then we want to insert a dbg.value for the corresponding
18280b57cec5SDimitry Andric     // fragment.
18290b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
18300b57cec5SDimitry Andric                       << *DII << '\n');
18310b57cec5SDimitry Andric     return;
18320b57cec5SDimitry Andric   }
18330b57cec5SDimitry Andric 
18340b57cec5SDimitry Andric   BasicBlock *BB = APN->getParent();
18350b57cec5SDimitry Andric   auto InsertionPt = BB->getFirstInsertionPt();
18360b57cec5SDimitry Andric 
1837bdd1243dSDimitry Andric   DebugLoc NewLoc = getDebugValueLoc(DII);
18380b57cec5SDimitry Andric 
18390b57cec5SDimitry Andric   // The block may be a catchswitch block, which does not have a valid
18400b57cec5SDimitry Andric   // insertion point.
18410b57cec5SDimitry Andric   // FIXME: Insert dbg.value markers in the successors when appropriate.
18425f757f3fSDimitry Andric   if (InsertionPt != BB->end()) {
18430fca6ea1SDimitry Andric     insertDbgValueOrDbgVariableRecord(Builder, APN, DIVar, DIExpr, NewLoc,
18440fca6ea1SDimitry Andric                                       InsertionPt);
18455f757f3fSDimitry Andric   }
18465f757f3fSDimitry Andric }
18475f757f3fSDimitry Andric 
18480fca6ea1SDimitry Andric void llvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, LoadInst *LI,
18495f757f3fSDimitry Andric                                            DIBuilder &Builder) {
18500fca6ea1SDimitry Andric   auto *DIVar = DVR->getVariable();
18510fca6ea1SDimitry Andric   auto *DIExpr = DVR->getExpression();
18525f757f3fSDimitry Andric   assert(DIVar && "Missing variable");
18535f757f3fSDimitry Andric 
18540fca6ea1SDimitry Andric   if (!valueCoversEntireFragment(LI->getType(), DVR)) {
18555f757f3fSDimitry Andric     // FIXME: If only referring to a part of the variable described by the
18560fca6ea1SDimitry Andric     // dbg.declare, then we want to insert a DbgVariableRecord for the
18570fca6ea1SDimitry Andric     // corresponding fragment.
18580fca6ea1SDimitry Andric     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to DbgVariableRecord: "
18590fca6ea1SDimitry Andric                       << *DVR << '\n');
18605f757f3fSDimitry Andric     return;
18615f757f3fSDimitry Andric   }
18625f757f3fSDimitry Andric 
18630fca6ea1SDimitry Andric   DebugLoc NewLoc = getDebugValueLoc(DVR);
18645f757f3fSDimitry Andric 
18655f757f3fSDimitry Andric   // We are now tracking the loaded value instead of the address. In the
18665f757f3fSDimitry Andric   // future if multi-location support is added to the IR, it might be
18675f757f3fSDimitry Andric   // preferable to keep tracking both the loaded value and the original
18685f757f3fSDimitry Andric   // address in case the alloca can not be elided.
18695f757f3fSDimitry Andric   assert(UseNewDbgInfoFormat);
18705f757f3fSDimitry Andric 
18710fca6ea1SDimitry Andric   // Create a DbgVariableRecord directly and insert.
18725f757f3fSDimitry Andric   ValueAsMetadata *LIVAM = ValueAsMetadata::get(LI);
18730fca6ea1SDimitry Andric   DbgVariableRecord *DV =
18740fca6ea1SDimitry Andric       new DbgVariableRecord(LIVAM, DIVar, DIExpr, NewLoc.get());
18750fca6ea1SDimitry Andric   LI->getParent()->insertDbgRecordAfter(DV, LI);
18760b57cec5SDimitry Andric }
18770b57cec5SDimitry Andric 
18780b57cec5SDimitry Andric /// Determine whether this alloca is either a VLA or an array.
18790b57cec5SDimitry Andric static bool isArray(AllocaInst *AI) {
18800b57cec5SDimitry Andric   return AI->isArrayAllocation() ||
18818bcb0991SDimitry Andric          (AI->getAllocatedType() && AI->getAllocatedType()->isArrayTy());
18828bcb0991SDimitry Andric }
18838bcb0991SDimitry Andric 
18848bcb0991SDimitry Andric /// Determine whether this alloca is a structure.
18858bcb0991SDimitry Andric static bool isStructure(AllocaInst *AI) {
18868bcb0991SDimitry Andric   return AI->getAllocatedType() && AI->getAllocatedType()->isStructTy();
18870b57cec5SDimitry Andric }
18880fca6ea1SDimitry Andric void llvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, PHINode *APN,
18895f757f3fSDimitry Andric                                            DIBuilder &Builder) {
18900fca6ea1SDimitry Andric   auto *DIVar = DVR->getVariable();
18910fca6ea1SDimitry Andric   auto *DIExpr = DVR->getExpression();
18925f757f3fSDimitry Andric   assert(DIVar && "Missing variable");
18935f757f3fSDimitry Andric 
18945f757f3fSDimitry Andric   if (PhiHasDebugValue(DIVar, DIExpr, APN))
18955f757f3fSDimitry Andric     return;
18965f757f3fSDimitry Andric 
18970fca6ea1SDimitry Andric   if (!valueCoversEntireFragment(APN->getType(), DVR)) {
18985f757f3fSDimitry Andric     // FIXME: If only referring to a part of the variable described by the
18990fca6ea1SDimitry Andric     // dbg.declare, then we want to insert a DbgVariableRecord for the
19000fca6ea1SDimitry Andric     // corresponding fragment.
19010fca6ea1SDimitry Andric     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to DbgVariableRecord: "
19020fca6ea1SDimitry Andric                       << *DVR << '\n');
19035f757f3fSDimitry Andric     return;
19045f757f3fSDimitry Andric   }
19055f757f3fSDimitry Andric 
19065f757f3fSDimitry Andric   BasicBlock *BB = APN->getParent();
19075f757f3fSDimitry Andric   auto InsertionPt = BB->getFirstInsertionPt();
19085f757f3fSDimitry Andric 
19090fca6ea1SDimitry Andric   DebugLoc NewLoc = getDebugValueLoc(DVR);
19105f757f3fSDimitry Andric 
19115f757f3fSDimitry Andric   // The block may be a catchswitch block, which does not have a valid
19125f757f3fSDimitry Andric   // insertion point.
19130fca6ea1SDimitry Andric   // FIXME: Insert DbgVariableRecord markers in the successors when appropriate.
19145f757f3fSDimitry Andric   if (InsertionPt != BB->end()) {
19150fca6ea1SDimitry Andric     insertDbgValueOrDbgVariableRecord(Builder, APN, DIVar, DIExpr, NewLoc,
19160fca6ea1SDimitry Andric                                       InsertionPt);
19175f757f3fSDimitry Andric   }
19185f757f3fSDimitry Andric }
19190b57cec5SDimitry Andric 
19200b57cec5SDimitry Andric /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
19210b57cec5SDimitry Andric /// of llvm.dbg.value intrinsics.
19220b57cec5SDimitry Andric bool llvm::LowerDbgDeclare(Function &F) {
19235ffd83dbSDimitry Andric   bool Changed = false;
19240b57cec5SDimitry Andric   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
19250b57cec5SDimitry Andric   SmallVector<DbgDeclareInst *, 4> Dbgs;
19260fca6ea1SDimitry Andric   SmallVector<DbgVariableRecord *> DVRs;
19275f757f3fSDimitry Andric   for (auto &FI : F) {
19285f757f3fSDimitry Andric     for (Instruction &BI : FI) {
19295f757f3fSDimitry Andric       if (auto *DDI = dyn_cast<DbgDeclareInst>(&BI))
19300b57cec5SDimitry Andric         Dbgs.push_back(DDI);
19310fca6ea1SDimitry Andric       for (DbgVariableRecord &DVR : filterDbgVars(BI.getDbgRecordRange())) {
19320fca6ea1SDimitry Andric         if (DVR.getType() == DbgVariableRecord::LocationType::Declare)
19330fca6ea1SDimitry Andric           DVRs.push_back(&DVR);
19345f757f3fSDimitry Andric       }
19355f757f3fSDimitry Andric     }
19365f757f3fSDimitry Andric   }
19370b57cec5SDimitry Andric 
19380fca6ea1SDimitry Andric   if (Dbgs.empty() && DVRs.empty())
19395ffd83dbSDimitry Andric     return Changed;
19400b57cec5SDimitry Andric 
19415f757f3fSDimitry Andric   auto LowerOne = [&](auto *DDI) {
19425f757f3fSDimitry Andric     AllocaInst *AI =
19435f757f3fSDimitry Andric         dyn_cast_or_null<AllocaInst>(DDI->getVariableLocationOp(0));
19440b57cec5SDimitry Andric     // If this is an alloca for a scalar variable, insert a dbg.value
19450b57cec5SDimitry Andric     // at each load and store to the alloca and erase the dbg.declare.
19460b57cec5SDimitry Andric     // The dbg.values allow tracking a variable even if it is not
19470b57cec5SDimitry Andric     // stored on the stack, while the dbg.declare can only describe
19480b57cec5SDimitry Andric     // the stack slot (and at a lexical-scope granularity). Later
19490b57cec5SDimitry Andric     // passes will attempt to elide the stack slot.
19508bcb0991SDimitry Andric     if (!AI || isArray(AI) || isStructure(AI))
19515f757f3fSDimitry Andric       return;
19520b57cec5SDimitry Andric 
19530b57cec5SDimitry Andric     // A volatile load/store means that the alloca can't be elided anyway.
19540b57cec5SDimitry Andric     if (llvm::any_of(AI->users(), [](User *U) -> bool {
19550b57cec5SDimitry Andric           if (LoadInst *LI = dyn_cast<LoadInst>(U))
19560b57cec5SDimitry Andric             return LI->isVolatile();
19570b57cec5SDimitry Andric           if (StoreInst *SI = dyn_cast<StoreInst>(U))
19580b57cec5SDimitry Andric             return SI->isVolatile();
19590b57cec5SDimitry Andric           return false;
19600b57cec5SDimitry Andric         }))
19615f757f3fSDimitry Andric       return;
19620b57cec5SDimitry Andric 
1963480093f4SDimitry Andric     SmallVector<const Value *, 8> WorkList;
1964480093f4SDimitry Andric     WorkList.push_back(AI);
1965480093f4SDimitry Andric     while (!WorkList.empty()) {
1966480093f4SDimitry Andric       const Value *V = WorkList.pop_back_val();
1967bdd1243dSDimitry Andric       for (const auto &AIUse : V->uses()) {
19680b57cec5SDimitry Andric         User *U = AIUse.getUser();
19690b57cec5SDimitry Andric         if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
19700b57cec5SDimitry Andric           if (AIUse.getOperandNo() == 1)
19710b57cec5SDimitry Andric             ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
19720b57cec5SDimitry Andric         } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
19730b57cec5SDimitry Andric           ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
19740b57cec5SDimitry Andric         } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
19750b57cec5SDimitry Andric           // This is a call by-value or some other instruction that takes a
19760b57cec5SDimitry Andric           // pointer to the variable. Insert a *value* intrinsic that describes
19770b57cec5SDimitry Andric           // the variable by dereferencing the alloca.
1978480093f4SDimitry Andric           if (!CI->isLifetimeStartOrEnd()) {
1979bdd1243dSDimitry Andric             DebugLoc NewLoc = getDebugValueLoc(DDI);
19800b57cec5SDimitry Andric             auto *DerefExpr =
19810b57cec5SDimitry Andric                 DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
19820fca6ea1SDimitry Andric             insertDbgValueOrDbgVariableRecord(DIB, AI, DDI->getVariable(),
19830fca6ea1SDimitry Andric                                               DerefExpr, NewLoc,
19840fca6ea1SDimitry Andric                                               CI->getIterator());
1985480093f4SDimitry Andric           }
1986480093f4SDimitry Andric         } else if (BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
1987480093f4SDimitry Andric           if (BI->getType()->isPointerTy())
1988480093f4SDimitry Andric             WorkList.push_back(BI);
1989480093f4SDimitry Andric         }
19900b57cec5SDimitry Andric       }
19910b57cec5SDimitry Andric     }
19920b57cec5SDimitry Andric     DDI->eraseFromParent();
19935ffd83dbSDimitry Andric     Changed = true;
19945f757f3fSDimitry Andric   };
19955f757f3fSDimitry Andric 
19965f757f3fSDimitry Andric   for_each(Dbgs, LowerOne);
19970fca6ea1SDimitry Andric   for_each(DVRs, LowerOne);
19985ffd83dbSDimitry Andric 
19995ffd83dbSDimitry Andric   if (Changed)
20005ffd83dbSDimitry Andric     for (BasicBlock &BB : F)
20015ffd83dbSDimitry Andric       RemoveRedundantDbgInstrs(&BB);
20025ffd83dbSDimitry Andric 
20035ffd83dbSDimitry Andric   return Changed;
20040b57cec5SDimitry Andric }
20050b57cec5SDimitry Andric 
20065f757f3fSDimitry Andric // RemoveDIs: re-implementation of insertDebugValuesForPHIs, but which pulls the
20070fca6ea1SDimitry Andric // debug-info out of the block's DbgVariableRecords rather than dbg.value
20080fca6ea1SDimitry Andric // intrinsics.
20090fca6ea1SDimitry Andric static void
20100fca6ea1SDimitry Andric insertDbgVariableRecordsForPHIs(BasicBlock *BB,
20115f757f3fSDimitry Andric                                 SmallVectorImpl<PHINode *> &InsertedPHIs) {
20120fca6ea1SDimitry Andric   assert(BB && "No BasicBlock to clone DbgVariableRecord(s) from.");
20135f757f3fSDimitry Andric   if (InsertedPHIs.size() == 0)
20145f757f3fSDimitry Andric     return;
20155f757f3fSDimitry Andric 
20160fca6ea1SDimitry Andric   // Map existing PHI nodes to their DbgVariableRecords.
20170fca6ea1SDimitry Andric   DenseMap<Value *, DbgVariableRecord *> DbgValueMap;
20185f757f3fSDimitry Andric   for (auto &I : *BB) {
20190fca6ea1SDimitry Andric     for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
20200fca6ea1SDimitry Andric       for (Value *V : DVR.location_ops())
20215f757f3fSDimitry Andric         if (auto *Loc = dyn_cast_or_null<PHINode>(V))
20220fca6ea1SDimitry Andric           DbgValueMap.insert({Loc, &DVR});
20235f757f3fSDimitry Andric     }
20245f757f3fSDimitry Andric   }
20255f757f3fSDimitry Andric   if (DbgValueMap.size() == 0)
20265f757f3fSDimitry Andric     return;
20275f757f3fSDimitry Andric 
20280fca6ea1SDimitry Andric   // Map a pair of the destination BB and old DbgVariableRecord to the new
20290fca6ea1SDimitry Andric   // DbgVariableRecord, so that if a DbgVariableRecord is being rewritten to use
20300fca6ea1SDimitry Andric   // more than one of the inserted PHIs in the same destination BB, we can
20310fca6ea1SDimitry Andric   // update the same DbgVariableRecord with all the new PHIs instead of creating
20320fca6ea1SDimitry Andric   // one copy for each.
20330fca6ea1SDimitry Andric   MapVector<std::pair<BasicBlock *, DbgVariableRecord *>, DbgVariableRecord *>
20340fca6ea1SDimitry Andric       NewDbgValueMap;
20355f757f3fSDimitry Andric   // Then iterate through the new PHIs and look to see if they use one of the
20360fca6ea1SDimitry Andric   // previously mapped PHIs. If so, create a new DbgVariableRecord that will
20370fca6ea1SDimitry Andric   // propagate the info through the new PHI. If we use more than one new PHI in
20380fca6ea1SDimitry Andric   // a single destination BB with the same old dbg.value, merge the updates so
20390fca6ea1SDimitry Andric   // that we get a single new DbgVariableRecord with all the new PHIs.
20405f757f3fSDimitry Andric   for (auto PHI : InsertedPHIs) {
20415f757f3fSDimitry Andric     BasicBlock *Parent = PHI->getParent();
20425f757f3fSDimitry Andric     // Avoid inserting a debug-info record into an EH block.
20435f757f3fSDimitry Andric     if (Parent->getFirstNonPHI()->isEHPad())
20445f757f3fSDimitry Andric       continue;
20455f757f3fSDimitry Andric     for (auto VI : PHI->operand_values()) {
20465f757f3fSDimitry Andric       auto V = DbgValueMap.find(VI);
20475f757f3fSDimitry Andric       if (V != DbgValueMap.end()) {
20480fca6ea1SDimitry Andric         DbgVariableRecord *DbgII = cast<DbgVariableRecord>(V->second);
20495f757f3fSDimitry Andric         auto NewDI = NewDbgValueMap.find({Parent, DbgII});
20505f757f3fSDimitry Andric         if (NewDI == NewDbgValueMap.end()) {
20510fca6ea1SDimitry Andric           DbgVariableRecord *NewDbgII = DbgII->clone();
20525f757f3fSDimitry Andric           NewDI = NewDbgValueMap.insert({{Parent, DbgII}, NewDbgII}).first;
20535f757f3fSDimitry Andric         }
20540fca6ea1SDimitry Andric         DbgVariableRecord *NewDbgII = NewDI->second;
20555f757f3fSDimitry Andric         // If PHI contains VI as an operand more than once, we may
20565f757f3fSDimitry Andric         // replaced it in NewDbgII; confirm that it is present.
20575f757f3fSDimitry Andric         if (is_contained(NewDbgII->location_ops(), VI))
20585f757f3fSDimitry Andric           NewDbgII->replaceVariableLocationOp(VI, PHI);
20595f757f3fSDimitry Andric       }
20605f757f3fSDimitry Andric     }
20615f757f3fSDimitry Andric   }
20620fca6ea1SDimitry Andric   // Insert the new DbgVariableRecords into their destination blocks.
20635f757f3fSDimitry Andric   for (auto DI : NewDbgValueMap) {
20645f757f3fSDimitry Andric     BasicBlock *Parent = DI.first.first;
20650fca6ea1SDimitry Andric     DbgVariableRecord *NewDbgII = DI.second;
20665f757f3fSDimitry Andric     auto InsertionPt = Parent->getFirstInsertionPt();
20675f757f3fSDimitry Andric     assert(InsertionPt != Parent->end() && "Ill-formed basic block");
20685f757f3fSDimitry Andric 
20690fca6ea1SDimitry Andric     Parent->insertDbgRecordBefore(NewDbgII, InsertionPt);
20705f757f3fSDimitry Andric   }
20715f757f3fSDimitry Andric }
20725f757f3fSDimitry Andric 
20730b57cec5SDimitry Andric /// Propagate dbg.value intrinsics through the newly inserted PHIs.
20740b57cec5SDimitry Andric void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
20750b57cec5SDimitry Andric                                     SmallVectorImpl<PHINode *> &InsertedPHIs) {
20760b57cec5SDimitry Andric   assert(BB && "No BasicBlock to clone dbg.value(s) from.");
20770b57cec5SDimitry Andric   if (InsertedPHIs.size() == 0)
20780b57cec5SDimitry Andric     return;
20790b57cec5SDimitry Andric 
20800fca6ea1SDimitry Andric   insertDbgVariableRecordsForPHIs(BB, InsertedPHIs);
20815f757f3fSDimitry Andric 
20820b57cec5SDimitry Andric   // Map existing PHI nodes to their dbg.values.
20830b57cec5SDimitry Andric   ValueToValueMapTy DbgValueMap;
20840b57cec5SDimitry Andric   for (auto &I : *BB) {
20850b57cec5SDimitry Andric     if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
2086fe6060f1SDimitry Andric       for (Value *V : DbgII->location_ops())
2087fe6060f1SDimitry Andric         if (auto *Loc = dyn_cast_or_null<PHINode>(V))
20880b57cec5SDimitry Andric           DbgValueMap.insert({Loc, DbgII});
20890b57cec5SDimitry Andric     }
20900b57cec5SDimitry Andric   }
20910b57cec5SDimitry Andric   if (DbgValueMap.size() == 0)
20920b57cec5SDimitry Andric     return;
20930b57cec5SDimitry Andric 
2094fe6060f1SDimitry Andric   // Map a pair of the destination BB and old dbg.value to the new dbg.value,
2095fe6060f1SDimitry Andric   // so that if a dbg.value is being rewritten to use more than one of the
2096fe6060f1SDimitry Andric   // inserted PHIs in the same destination BB, we can update the same dbg.value
2097fe6060f1SDimitry Andric   // with all the new PHIs instead of creating one copy for each.
2098fe6060f1SDimitry Andric   MapVector<std::pair<BasicBlock *, DbgVariableIntrinsic *>,
2099fe6060f1SDimitry Andric             DbgVariableIntrinsic *>
2100fe6060f1SDimitry Andric       NewDbgValueMap;
21010b57cec5SDimitry Andric   // Then iterate through the new PHIs and look to see if they use one of the
2102fe6060f1SDimitry Andric   // previously mapped PHIs. If so, create a new dbg.value intrinsic that will
2103fe6060f1SDimitry Andric   // propagate the info through the new PHI. If we use more than one new PHI in
2104fe6060f1SDimitry Andric   // a single destination BB with the same old dbg.value, merge the updates so
2105fe6060f1SDimitry Andric   // that we get a single new dbg.value with all the new PHIs.
2106bdd1243dSDimitry Andric   for (auto *PHI : InsertedPHIs) {
21070b57cec5SDimitry Andric     BasicBlock *Parent = PHI->getParent();
21080b57cec5SDimitry Andric     // Avoid inserting an intrinsic into an EH block.
21090b57cec5SDimitry Andric     if (Parent->getFirstNonPHI()->isEHPad())
21100b57cec5SDimitry Andric       continue;
2111bdd1243dSDimitry Andric     for (auto *VI : PHI->operand_values()) {
21120b57cec5SDimitry Andric       auto V = DbgValueMap.find(VI);
21130b57cec5SDimitry Andric       if (V != DbgValueMap.end()) {
21140b57cec5SDimitry Andric         auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
2115fe6060f1SDimitry Andric         auto NewDI = NewDbgValueMap.find({Parent, DbgII});
2116fe6060f1SDimitry Andric         if (NewDI == NewDbgValueMap.end()) {
2117fe6060f1SDimitry Andric           auto *NewDbgII = cast<DbgVariableIntrinsic>(DbgII->clone());
2118fe6060f1SDimitry Andric           NewDI = NewDbgValueMap.insert({{Parent, DbgII}, NewDbgII}).first;
2119fe6060f1SDimitry Andric         }
2120fe6060f1SDimitry Andric         DbgVariableIntrinsic *NewDbgII = NewDI->second;
2121fe6060f1SDimitry Andric         // If PHI contains VI as an operand more than once, we may
2122fe6060f1SDimitry Andric         // replaced it in NewDbgII; confirm that it is present.
2123fe6060f1SDimitry Andric         if (is_contained(NewDbgII->location_ops(), VI))
2124fe6060f1SDimitry Andric           NewDbgII->replaceVariableLocationOp(VI, PHI);
2125fe6060f1SDimitry Andric       }
2126fe6060f1SDimitry Andric     }
2127fe6060f1SDimitry Andric   }
2128fe6060f1SDimitry Andric   // Insert thew new dbg.values into their destination blocks.
2129fe6060f1SDimitry Andric   for (auto DI : NewDbgValueMap) {
2130fe6060f1SDimitry Andric     BasicBlock *Parent = DI.first.first;
2131fe6060f1SDimitry Andric     auto *NewDbgII = DI.second;
21320b57cec5SDimitry Andric     auto InsertionPt = Parent->getFirstInsertionPt();
21330b57cec5SDimitry Andric     assert(InsertionPt != Parent->end() && "Ill-formed basic block");
21340b57cec5SDimitry Andric     NewDbgII->insertBefore(&*InsertionPt);
21350b57cec5SDimitry Andric   }
21360b57cec5SDimitry Andric }
21370b57cec5SDimitry Andric 
21380b57cec5SDimitry Andric bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
21395ffd83dbSDimitry Andric                              DIBuilder &Builder, uint8_t DIExprFlags,
21405ffd83dbSDimitry Andric                              int Offset) {
21417a6dacacSDimitry Andric   TinyPtrVector<DbgDeclareInst *> DbgDeclares = findDbgDeclares(Address);
21420fca6ea1SDimitry Andric   TinyPtrVector<DbgVariableRecord *> DVRDeclares = findDVRDeclares(Address);
21435f757f3fSDimitry Andric 
21445f757f3fSDimitry Andric   auto ReplaceOne = [&](auto *DII) {
21455f757f3fSDimitry Andric     assert(DII->getVariable() && "Missing variable");
21460b57cec5SDimitry Andric     auto *DIExpr = DII->getExpression();
21470b57cec5SDimitry Andric     DIExpr = DIExpression::prepend(DIExpr, DIExprFlags, Offset);
21485f757f3fSDimitry Andric     DII->setExpression(DIExpr);
21495f757f3fSDimitry Andric     DII->replaceVariableLocationOp(Address, NewAddress);
21505f757f3fSDimitry Andric   };
21515f757f3fSDimitry Andric 
21525f757f3fSDimitry Andric   for_each(DbgDeclares, ReplaceOne);
21530fca6ea1SDimitry Andric   for_each(DVRDeclares, ReplaceOne);
21545f757f3fSDimitry Andric 
21550fca6ea1SDimitry Andric   return !DbgDeclares.empty() || !DVRDeclares.empty();
21560b57cec5SDimitry Andric }
21570b57cec5SDimitry Andric 
21585f757f3fSDimitry Andric static void updateOneDbgValueForAlloca(const DebugLoc &Loc,
21595f757f3fSDimitry Andric                                        DILocalVariable *DIVar,
21605f757f3fSDimitry Andric                                        DIExpression *DIExpr, Value *NewAddress,
21610fca6ea1SDimitry Andric                                        DbgValueInst *DVI,
21620fca6ea1SDimitry Andric                                        DbgVariableRecord *DVR,
21630b57cec5SDimitry Andric                                        DIBuilder &Builder, int Offset) {
21640b57cec5SDimitry Andric   assert(DIVar && "Missing variable");
21650b57cec5SDimitry Andric 
21660fca6ea1SDimitry Andric   // This is an alloca-based dbg.value/DbgVariableRecord. The first thing it
21670fca6ea1SDimitry Andric   // should do with the alloca pointer is dereference it. Otherwise we don't
21680fca6ea1SDimitry Andric   // know how to handle it and give up.
21690b57cec5SDimitry Andric   if (!DIExpr || DIExpr->getNumElements() < 1 ||
21700b57cec5SDimitry Andric       DIExpr->getElement(0) != dwarf::DW_OP_deref)
21710b57cec5SDimitry Andric     return;
21720b57cec5SDimitry Andric 
21738bcb0991SDimitry Andric   // Insert the offset before the first deref.
21748bcb0991SDimitry Andric   if (Offset)
21758bcb0991SDimitry Andric     DIExpr = DIExpression::prepend(DIExpr, 0, Offset);
21760b57cec5SDimitry Andric 
21775f757f3fSDimitry Andric   if (DVI) {
21785f757f3fSDimitry Andric     DVI->setExpression(DIExpr);
21795f757f3fSDimitry Andric     DVI->replaceVariableLocationOp(0u, NewAddress);
21805f757f3fSDimitry Andric   } else {
21810fca6ea1SDimitry Andric     assert(DVR);
21820fca6ea1SDimitry Andric     DVR->setExpression(DIExpr);
21830fca6ea1SDimitry Andric     DVR->replaceVariableLocationOp(0u, NewAddress);
21845f757f3fSDimitry Andric   }
21850b57cec5SDimitry Andric }
21860b57cec5SDimitry Andric 
21870b57cec5SDimitry Andric void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
21880b57cec5SDimitry Andric                                     DIBuilder &Builder, int Offset) {
21895f757f3fSDimitry Andric   SmallVector<DbgValueInst *, 1> DbgUsers;
21900fca6ea1SDimitry Andric   SmallVector<DbgVariableRecord *, 1> DPUsers;
21915f757f3fSDimitry Andric   findDbgValues(DbgUsers, AI, &DPUsers);
21925f757f3fSDimitry Andric 
21935f757f3fSDimitry Andric   // Attempt to replace dbg.values that use this alloca.
21945f757f3fSDimitry Andric   for (auto *DVI : DbgUsers)
21955f757f3fSDimitry Andric     updateOneDbgValueForAlloca(DVI->getDebugLoc(), DVI->getVariable(),
21965f757f3fSDimitry Andric                                DVI->getExpression(), NewAllocaAddress, DVI,
21975f757f3fSDimitry Andric                                nullptr, Builder, Offset);
21985f757f3fSDimitry Andric 
21990fca6ea1SDimitry Andric   // Replace any DbgVariableRecords that use this alloca.
22000fca6ea1SDimitry Andric   for (DbgVariableRecord *DVR : DPUsers)
22010fca6ea1SDimitry Andric     updateOneDbgValueForAlloca(DVR->getDebugLoc(), DVR->getVariable(),
22020fca6ea1SDimitry Andric                                DVR->getExpression(), NewAllocaAddress, nullptr,
22030fca6ea1SDimitry Andric                                DVR, Builder, Offset);
22040b57cec5SDimitry Andric }
22050b57cec5SDimitry Andric 
2206bdd1243dSDimitry Andric /// Where possible to salvage debug information for \p I do so.
2207bdd1243dSDimitry Andric /// If not possible mark undef.
22085ffd83dbSDimitry Andric void llvm::salvageDebugInfo(Instruction &I) {
22090b57cec5SDimitry Andric   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
22100fca6ea1SDimitry Andric   SmallVector<DbgVariableRecord *, 1> DPUsers;
22115f757f3fSDimitry Andric   findDbgUsers(DbgUsers, &I, &DPUsers);
22125f757f3fSDimitry Andric   salvageDebugInfoForDbgValues(I, DbgUsers, DPUsers);
22130b57cec5SDimitry Andric }
22140b57cec5SDimitry Andric 
22157a6dacacSDimitry Andric template <typename T> static void salvageDbgAssignAddress(T *Assign) {
22167a6dacacSDimitry Andric   Instruction *I = dyn_cast<Instruction>(Assign->getAddress());
2217bdd1243dSDimitry Andric   // Only instructions can be salvaged at the moment.
2218bdd1243dSDimitry Andric   if (!I)
2219bdd1243dSDimitry Andric     return;
2220bdd1243dSDimitry Andric 
22217a6dacacSDimitry Andric   assert(!Assign->getAddressExpression()->getFragmentInfo().has_value() &&
2222bdd1243dSDimitry Andric          "address-expression shouldn't have fragment info");
2223bdd1243dSDimitry Andric 
2224bdd1243dSDimitry Andric   // The address component of a dbg.assign cannot be variadic.
2225bdd1243dSDimitry Andric   uint64_t CurrentLocOps = 0;
2226bdd1243dSDimitry Andric   SmallVector<Value *, 4> AdditionalValues;
2227bdd1243dSDimitry Andric   SmallVector<uint64_t, 16> Ops;
2228bdd1243dSDimitry Andric   Value *NewV = salvageDebugInfoImpl(*I, CurrentLocOps, Ops, AdditionalValues);
2229bdd1243dSDimitry Andric 
2230bdd1243dSDimitry Andric   // Check if the salvage failed.
2231bdd1243dSDimitry Andric   if (!NewV)
2232bdd1243dSDimitry Andric     return;
2233bdd1243dSDimitry Andric 
2234bdd1243dSDimitry Andric   DIExpression *SalvagedExpr = DIExpression::appendOpsToArg(
22357a6dacacSDimitry Andric       Assign->getAddressExpression(), Ops, 0, /*StackValue=*/false);
2236bdd1243dSDimitry Andric   assert(!SalvagedExpr->getFragmentInfo().has_value() &&
2237bdd1243dSDimitry Andric          "address-expression shouldn't have fragment info");
2238bdd1243dSDimitry Andric 
22390fca6ea1SDimitry Andric   SalvagedExpr = SalvagedExpr->foldConstantMath();
22400fca6ea1SDimitry Andric 
2241bdd1243dSDimitry Andric   // Salvage succeeds if no additional values are required.
2242bdd1243dSDimitry Andric   if (AdditionalValues.empty()) {
22437a6dacacSDimitry Andric     Assign->setAddress(NewV);
22447a6dacacSDimitry Andric     Assign->setAddressExpression(SalvagedExpr);
2245bdd1243dSDimitry Andric   } else {
22467a6dacacSDimitry Andric     Assign->setKillAddress();
2247bdd1243dSDimitry Andric   }
2248bdd1243dSDimitry Andric }
2249bdd1243dSDimitry Andric 
22505ffd83dbSDimitry Andric void llvm::salvageDebugInfoForDbgValues(
22515f757f3fSDimitry Andric     Instruction &I, ArrayRef<DbgVariableIntrinsic *> DbgUsers,
22520fca6ea1SDimitry Andric     ArrayRef<DbgVariableRecord *> DPUsers) {
2253349cc55cSDimitry Andric   // These are arbitrary chosen limits on the maximum number of values and the
2254349cc55cSDimitry Andric   // maximum size of a debug expression we can salvage up to, used for
2255349cc55cSDimitry Andric   // performance reasons.
2256fe6060f1SDimitry Andric   const unsigned MaxDebugArgs = 16;
2257349cc55cSDimitry Andric   const unsigned MaxExpressionSize = 128;
22585ffd83dbSDimitry Andric   bool Salvaged = false;
22590b57cec5SDimitry Andric 
22600b57cec5SDimitry Andric   for (auto *DII : DbgUsers) {
2261bdd1243dSDimitry Andric     if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DII)) {
2262bdd1243dSDimitry Andric       if (DAI->getAddress() == &I) {
2263bdd1243dSDimitry Andric         salvageDbgAssignAddress(DAI);
2264bdd1243dSDimitry Andric         Salvaged = true;
2265bdd1243dSDimitry Andric       }
2266bdd1243dSDimitry Andric       if (DAI->getValue() != &I)
2267bdd1243dSDimitry Andric         continue;
2268bdd1243dSDimitry Andric     }
2269bdd1243dSDimitry Andric 
227006c3fb27SDimitry Andric     // Do not add DW_OP_stack_value for DbgDeclare, because they are implicitly
227106c3fb27SDimitry Andric     // pointing out the value as a DWARF memory location description.
22720b57cec5SDimitry Andric     bool StackValue = isa<DbgValueInst>(DII);
2273fe6060f1SDimitry Andric     auto DIILocation = DII->location_ops();
2274fe6060f1SDimitry Andric     assert(
2275fe6060f1SDimitry Andric         is_contained(DIILocation, &I) &&
2276fe6060f1SDimitry Andric         "DbgVariableIntrinsic must use salvaged instruction as its location");
2277fe6060f1SDimitry Andric     SmallVector<Value *, 4> AdditionalValues;
2278fe6060f1SDimitry Andric     // `I` may appear more than once in DII's location ops, and each use of `I`
2279fe6060f1SDimitry Andric     // must be updated in the DIExpression and potentially have additional
2280fe6060f1SDimitry Andric     // values added; thus we call salvageDebugInfoImpl for each `I` instance in
2281fe6060f1SDimitry Andric     // DIILocation.
2282349cc55cSDimitry Andric     Value *Op0 = nullptr;
2283fe6060f1SDimitry Andric     DIExpression *SalvagedExpr = DII->getExpression();
2284fe6060f1SDimitry Andric     auto LocItr = find(DIILocation, &I);
2285fe6060f1SDimitry Andric     while (SalvagedExpr && LocItr != DIILocation.end()) {
2286349cc55cSDimitry Andric       SmallVector<uint64_t, 16> Ops;
2287fe6060f1SDimitry Andric       unsigned LocNo = std::distance(DIILocation.begin(), LocItr);
2288349cc55cSDimitry Andric       uint64_t CurrentLocOps = SalvagedExpr->getNumLocationOperands();
2289349cc55cSDimitry Andric       Op0 = salvageDebugInfoImpl(I, CurrentLocOps, Ops, AdditionalValues);
2290349cc55cSDimitry Andric       if (!Op0)
2291349cc55cSDimitry Andric         break;
2292349cc55cSDimitry Andric       SalvagedExpr =
2293349cc55cSDimitry Andric           DIExpression::appendOpsToArg(SalvagedExpr, Ops, LocNo, StackValue);
2294fe6060f1SDimitry Andric       LocItr = std::find(++LocItr, DIILocation.end(), &I);
2295fe6060f1SDimitry Andric     }
22960b57cec5SDimitry Andric     // salvageDebugInfoImpl should fail on examining the first element of
22970b57cec5SDimitry Andric     // DbgUsers, or none of them.
2298349cc55cSDimitry Andric     if (!Op0)
22995ffd83dbSDimitry Andric       break;
23000b57cec5SDimitry Andric 
23010fca6ea1SDimitry Andric     SalvagedExpr = SalvagedExpr->foldConstantMath();
2302349cc55cSDimitry Andric     DII->replaceVariableLocationOp(&I, Op0);
2303349cc55cSDimitry Andric     bool IsValidSalvageExpr = SalvagedExpr->getNumElements() <= MaxExpressionSize;
2304349cc55cSDimitry Andric     if (AdditionalValues.empty() && IsValidSalvageExpr) {
2305fe6060f1SDimitry Andric       DII->setExpression(SalvagedExpr);
230606c3fb27SDimitry Andric     } else if (isa<DbgValueInst>(DII) && IsValidSalvageExpr &&
2307fe6060f1SDimitry Andric                DII->getNumVariableLocationOps() + AdditionalValues.size() <=
2308fe6060f1SDimitry Andric                    MaxDebugArgs) {
2309fe6060f1SDimitry Andric       DII->addVariableLocationOps(AdditionalValues, SalvagedExpr);
2310fe6060f1SDimitry Andric     } else {
231106c3fb27SDimitry Andric       // Do not salvage using DIArgList for dbg.declare, as it is not currently
231206c3fb27SDimitry Andric       // supported in those instructions. Also do not salvage if the resulting
231306c3fb27SDimitry Andric       // DIArgList would contain an unreasonably large number of values.
2314bdd1243dSDimitry Andric       DII->setKillLocation();
2315fe6060f1SDimitry Andric     }
23160b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
23175ffd83dbSDimitry Andric     Salvaged = true;
23180b57cec5SDimitry Andric   }
23190fca6ea1SDimitry Andric   // Duplicate of above block for DbgVariableRecords.
23200fca6ea1SDimitry Andric   for (auto *DVR : DPUsers) {
23210fca6ea1SDimitry Andric     if (DVR->isDbgAssign()) {
23220fca6ea1SDimitry Andric       if (DVR->getAddress() == &I) {
23230fca6ea1SDimitry Andric         salvageDbgAssignAddress(DVR);
23247a6dacacSDimitry Andric         Salvaged = true;
23257a6dacacSDimitry Andric       }
23260fca6ea1SDimitry Andric       if (DVR->getValue() != &I)
23277a6dacacSDimitry Andric         continue;
23287a6dacacSDimitry Andric     }
23297a6dacacSDimitry Andric 
23305f757f3fSDimitry Andric     // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
23315f757f3fSDimitry Andric     // are implicitly pointing out the value as a DWARF memory location
23325f757f3fSDimitry Andric     // description.
23330fca6ea1SDimitry Andric     bool StackValue =
23340fca6ea1SDimitry Andric         DVR->getType() != DbgVariableRecord::LocationType::Declare;
23350fca6ea1SDimitry Andric     auto DVRLocation = DVR->location_ops();
23365f757f3fSDimitry Andric     assert(
23370fca6ea1SDimitry Andric         is_contained(DVRLocation, &I) &&
23385f757f3fSDimitry Andric         "DbgVariableIntrinsic must use salvaged instruction as its location");
23395f757f3fSDimitry Andric     SmallVector<Value *, 4> AdditionalValues;
23400fca6ea1SDimitry Andric     // 'I' may appear more than once in DVR's location ops, and each use of 'I'
23415f757f3fSDimitry Andric     // must be updated in the DIExpression and potentially have additional
23425f757f3fSDimitry Andric     // values added; thus we call salvageDebugInfoImpl for each 'I' instance in
23430fca6ea1SDimitry Andric     // DVRLocation.
23445f757f3fSDimitry Andric     Value *Op0 = nullptr;
23450fca6ea1SDimitry Andric     DIExpression *SalvagedExpr = DVR->getExpression();
23460fca6ea1SDimitry Andric     auto LocItr = find(DVRLocation, &I);
23470fca6ea1SDimitry Andric     while (SalvagedExpr && LocItr != DVRLocation.end()) {
23485f757f3fSDimitry Andric       SmallVector<uint64_t, 16> Ops;
23490fca6ea1SDimitry Andric       unsigned LocNo = std::distance(DVRLocation.begin(), LocItr);
23505f757f3fSDimitry Andric       uint64_t CurrentLocOps = SalvagedExpr->getNumLocationOperands();
23515f757f3fSDimitry Andric       Op0 = salvageDebugInfoImpl(I, CurrentLocOps, Ops, AdditionalValues);
23525f757f3fSDimitry Andric       if (!Op0)
23535f757f3fSDimitry Andric         break;
23545f757f3fSDimitry Andric       SalvagedExpr =
23555f757f3fSDimitry Andric           DIExpression::appendOpsToArg(SalvagedExpr, Ops, LocNo, StackValue);
23560fca6ea1SDimitry Andric       LocItr = std::find(++LocItr, DVRLocation.end(), &I);
23575f757f3fSDimitry Andric     }
23585f757f3fSDimitry Andric     // salvageDebugInfoImpl should fail on examining the first element of
23595f757f3fSDimitry Andric     // DbgUsers, or none of them.
23605f757f3fSDimitry Andric     if (!Op0)
23615f757f3fSDimitry Andric       break;
23625f757f3fSDimitry Andric 
23630fca6ea1SDimitry Andric     SalvagedExpr = SalvagedExpr->foldConstantMath();
23640fca6ea1SDimitry Andric     DVR->replaceVariableLocationOp(&I, Op0);
23655f757f3fSDimitry Andric     bool IsValidSalvageExpr =
23665f757f3fSDimitry Andric         SalvagedExpr->getNumElements() <= MaxExpressionSize;
23675f757f3fSDimitry Andric     if (AdditionalValues.empty() && IsValidSalvageExpr) {
23680fca6ea1SDimitry Andric       DVR->setExpression(SalvagedExpr);
23690fca6ea1SDimitry Andric     } else if (DVR->getType() != DbgVariableRecord::LocationType::Declare &&
23705f757f3fSDimitry Andric                IsValidSalvageExpr &&
23710fca6ea1SDimitry Andric                DVR->getNumVariableLocationOps() + AdditionalValues.size() <=
23725f757f3fSDimitry Andric                    MaxDebugArgs) {
23730fca6ea1SDimitry Andric       DVR->addVariableLocationOps(AdditionalValues, SalvagedExpr);
23745f757f3fSDimitry Andric     } else {
23755f757f3fSDimitry Andric       // Do not salvage using DIArgList for dbg.addr/dbg.declare, as it is
23765f757f3fSDimitry Andric       // currently only valid for stack value expressions.
23775f757f3fSDimitry Andric       // Also do not salvage if the resulting DIArgList would contain an
23785f757f3fSDimitry Andric       // unreasonably large number of values.
23790fca6ea1SDimitry Andric       DVR->setKillLocation();
23805f757f3fSDimitry Andric     }
23810fca6ea1SDimitry Andric     LLVM_DEBUG(dbgs() << "SALVAGE: " << DVR << '\n');
23825f757f3fSDimitry Andric     Salvaged = true;
23835f757f3fSDimitry Andric   }
23840b57cec5SDimitry Andric 
23855ffd83dbSDimitry Andric   if (Salvaged)
23865ffd83dbSDimitry Andric     return;
23875ffd83dbSDimitry Andric 
2388bdd1243dSDimitry Andric   for (auto *DII : DbgUsers)
2389bdd1243dSDimitry Andric     DII->setKillLocation();
23905f757f3fSDimitry Andric 
23910fca6ea1SDimitry Andric   for (auto *DVR : DPUsers)
23920fca6ea1SDimitry Andric     DVR->setKillLocation();
23930b57cec5SDimitry Andric }
23940b57cec5SDimitry Andric 
2395349cc55cSDimitry Andric Value *getSalvageOpsForGEP(GetElementPtrInst *GEP, const DataLayout &DL,
2396fe6060f1SDimitry Andric                            uint64_t CurrentLocOps,
2397fe6060f1SDimitry Andric                            SmallVectorImpl<uint64_t> &Opcodes,
2398fe6060f1SDimitry Andric                            SmallVectorImpl<Value *> &AdditionalValues) {
2399fe6060f1SDimitry Andric   unsigned BitWidth = DL.getIndexSizeInBits(GEP->getPointerAddressSpace());
2400fe6060f1SDimitry Andric   // Rewrite a GEP into a DIExpression.
2401fe6060f1SDimitry Andric   MapVector<Value *, APInt> VariableOffsets;
2402fe6060f1SDimitry Andric   APInt ConstantOffset(BitWidth, 0);
2403fe6060f1SDimitry Andric   if (!GEP->collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset))
2404349cc55cSDimitry Andric     return nullptr;
2405fe6060f1SDimitry Andric   if (!VariableOffsets.empty() && !CurrentLocOps) {
2406fe6060f1SDimitry Andric     Opcodes.insert(Opcodes.begin(), {dwarf::DW_OP_LLVM_arg, 0});
2407fe6060f1SDimitry Andric     CurrentLocOps = 1;
2408fe6060f1SDimitry Andric   }
240906c3fb27SDimitry Andric   for (const auto &Offset : VariableOffsets) {
2410fe6060f1SDimitry Andric     AdditionalValues.push_back(Offset.first);
2411fe6060f1SDimitry Andric     assert(Offset.second.isStrictlyPositive() &&
2412fe6060f1SDimitry Andric            "Expected strictly positive multiplier for offset.");
2413fe6060f1SDimitry Andric     Opcodes.append({dwarf::DW_OP_LLVM_arg, CurrentLocOps++, dwarf::DW_OP_constu,
2414fe6060f1SDimitry Andric                     Offset.second.getZExtValue(), dwarf::DW_OP_mul,
2415fe6060f1SDimitry Andric                     dwarf::DW_OP_plus});
2416fe6060f1SDimitry Andric   }
2417fe6060f1SDimitry Andric   DIExpression::appendOffset(Opcodes, ConstantOffset.getSExtValue());
2418349cc55cSDimitry Andric   return GEP->getOperand(0);
2419fe6060f1SDimitry Andric }
2420fe6060f1SDimitry Andric 
2421fe6060f1SDimitry Andric uint64_t getDwarfOpForBinOp(Instruction::BinaryOps Opcode) {
2422fe6060f1SDimitry Andric   switch (Opcode) {
2423fe6060f1SDimitry Andric   case Instruction::Add:
2424fe6060f1SDimitry Andric     return dwarf::DW_OP_plus;
2425fe6060f1SDimitry Andric   case Instruction::Sub:
2426fe6060f1SDimitry Andric     return dwarf::DW_OP_minus;
2427fe6060f1SDimitry Andric   case Instruction::Mul:
2428fe6060f1SDimitry Andric     return dwarf::DW_OP_mul;
2429fe6060f1SDimitry Andric   case Instruction::SDiv:
2430fe6060f1SDimitry Andric     return dwarf::DW_OP_div;
2431fe6060f1SDimitry Andric   case Instruction::SRem:
2432fe6060f1SDimitry Andric     return dwarf::DW_OP_mod;
2433fe6060f1SDimitry Andric   case Instruction::Or:
2434fe6060f1SDimitry Andric     return dwarf::DW_OP_or;
2435fe6060f1SDimitry Andric   case Instruction::And:
2436fe6060f1SDimitry Andric     return dwarf::DW_OP_and;
2437fe6060f1SDimitry Andric   case Instruction::Xor:
2438fe6060f1SDimitry Andric     return dwarf::DW_OP_xor;
2439fe6060f1SDimitry Andric   case Instruction::Shl:
2440fe6060f1SDimitry Andric     return dwarf::DW_OP_shl;
2441fe6060f1SDimitry Andric   case Instruction::LShr:
2442fe6060f1SDimitry Andric     return dwarf::DW_OP_shr;
2443fe6060f1SDimitry Andric   case Instruction::AShr:
2444fe6060f1SDimitry Andric     return dwarf::DW_OP_shra;
2445fe6060f1SDimitry Andric   default:
2446fe6060f1SDimitry Andric     // TODO: Salvage from each kind of binop we know about.
2447fe6060f1SDimitry Andric     return 0;
2448fe6060f1SDimitry Andric   }
2449fe6060f1SDimitry Andric }
2450fe6060f1SDimitry Andric 
245106c3fb27SDimitry Andric static void handleSSAValueOperands(uint64_t CurrentLocOps,
245206c3fb27SDimitry Andric                                    SmallVectorImpl<uint64_t> &Opcodes,
245306c3fb27SDimitry Andric                                    SmallVectorImpl<Value *> &AdditionalValues,
245406c3fb27SDimitry Andric                                    Instruction *I) {
245506c3fb27SDimitry Andric   if (!CurrentLocOps) {
245606c3fb27SDimitry Andric     Opcodes.append({dwarf::DW_OP_LLVM_arg, 0});
245706c3fb27SDimitry Andric     CurrentLocOps = 1;
245806c3fb27SDimitry Andric   }
245906c3fb27SDimitry Andric   Opcodes.append({dwarf::DW_OP_LLVM_arg, CurrentLocOps});
246006c3fb27SDimitry Andric   AdditionalValues.push_back(I->getOperand(1));
246106c3fb27SDimitry Andric }
246206c3fb27SDimitry Andric 
2463349cc55cSDimitry Andric Value *getSalvageOpsForBinOp(BinaryOperator *BI, uint64_t CurrentLocOps,
2464fe6060f1SDimitry Andric                              SmallVectorImpl<uint64_t> &Opcodes,
2465fe6060f1SDimitry Andric                              SmallVectorImpl<Value *> &AdditionalValues) {
2466fe6060f1SDimitry Andric   // Handle binary operations with constant integer operands as a special case.
2467fe6060f1SDimitry Andric   auto *ConstInt = dyn_cast<ConstantInt>(BI->getOperand(1));
2468fe6060f1SDimitry Andric   // Values wider than 64 bits cannot be represented within a DIExpression.
2469fe6060f1SDimitry Andric   if (ConstInt && ConstInt->getBitWidth() > 64)
2470349cc55cSDimitry Andric     return nullptr;
2471fe6060f1SDimitry Andric 
2472fe6060f1SDimitry Andric   Instruction::BinaryOps BinOpcode = BI->getOpcode();
2473fe6060f1SDimitry Andric   // Push any Constant Int operand onto the expression stack.
2474fe6060f1SDimitry Andric   if (ConstInt) {
2475fe6060f1SDimitry Andric     uint64_t Val = ConstInt->getSExtValue();
2476fe6060f1SDimitry Andric     // Add or Sub Instructions with a constant operand can potentially be
2477fe6060f1SDimitry Andric     // simplified.
2478fe6060f1SDimitry Andric     if (BinOpcode == Instruction::Add || BinOpcode == Instruction::Sub) {
2479fe6060f1SDimitry Andric       uint64_t Offset = BinOpcode == Instruction::Add ? Val : -int64_t(Val);
2480fe6060f1SDimitry Andric       DIExpression::appendOffset(Opcodes, Offset);
2481349cc55cSDimitry Andric       return BI->getOperand(0);
2482fe6060f1SDimitry Andric     }
2483fe6060f1SDimitry Andric     Opcodes.append({dwarf::DW_OP_constu, Val});
2484fe6060f1SDimitry Andric   } else {
248506c3fb27SDimitry Andric     handleSSAValueOperands(CurrentLocOps, Opcodes, AdditionalValues, BI);
2486fe6060f1SDimitry Andric   }
2487fe6060f1SDimitry Andric 
2488fe6060f1SDimitry Andric   // Add salvaged binary operator to expression stack, if it has a valid
2489fe6060f1SDimitry Andric   // representation in a DIExpression.
2490fe6060f1SDimitry Andric   uint64_t DwarfBinOp = getDwarfOpForBinOp(BinOpcode);
2491fe6060f1SDimitry Andric   if (!DwarfBinOp)
2492349cc55cSDimitry Andric     return nullptr;
2493fe6060f1SDimitry Andric   Opcodes.push_back(DwarfBinOp);
2494349cc55cSDimitry Andric   return BI->getOperand(0);
2495fe6060f1SDimitry Andric }
2496fe6060f1SDimitry Andric 
249706c3fb27SDimitry Andric uint64_t getDwarfOpForIcmpPred(CmpInst::Predicate Pred) {
249806c3fb27SDimitry Andric   // The signedness of the operation is implicit in the typed stack, signed and
249906c3fb27SDimitry Andric   // unsigned instructions map to the same DWARF opcode.
250006c3fb27SDimitry Andric   switch (Pred) {
250106c3fb27SDimitry Andric   case CmpInst::ICMP_EQ:
250206c3fb27SDimitry Andric     return dwarf::DW_OP_eq;
250306c3fb27SDimitry Andric   case CmpInst::ICMP_NE:
250406c3fb27SDimitry Andric     return dwarf::DW_OP_ne;
250506c3fb27SDimitry Andric   case CmpInst::ICMP_UGT:
250606c3fb27SDimitry Andric   case CmpInst::ICMP_SGT:
250706c3fb27SDimitry Andric     return dwarf::DW_OP_gt;
250806c3fb27SDimitry Andric   case CmpInst::ICMP_UGE:
250906c3fb27SDimitry Andric   case CmpInst::ICMP_SGE:
251006c3fb27SDimitry Andric     return dwarf::DW_OP_ge;
251106c3fb27SDimitry Andric   case CmpInst::ICMP_ULT:
251206c3fb27SDimitry Andric   case CmpInst::ICMP_SLT:
251306c3fb27SDimitry Andric     return dwarf::DW_OP_lt;
251406c3fb27SDimitry Andric   case CmpInst::ICMP_ULE:
251506c3fb27SDimitry Andric   case CmpInst::ICMP_SLE:
251606c3fb27SDimitry Andric     return dwarf::DW_OP_le;
251706c3fb27SDimitry Andric   default:
251806c3fb27SDimitry Andric     return 0;
251906c3fb27SDimitry Andric   }
252006c3fb27SDimitry Andric }
252106c3fb27SDimitry Andric 
252206c3fb27SDimitry Andric Value *getSalvageOpsForIcmpOp(ICmpInst *Icmp, uint64_t CurrentLocOps,
252306c3fb27SDimitry Andric                               SmallVectorImpl<uint64_t> &Opcodes,
252406c3fb27SDimitry Andric                               SmallVectorImpl<Value *> &AdditionalValues) {
252506c3fb27SDimitry Andric   // Handle icmp operations with constant integer operands as a special case.
252606c3fb27SDimitry Andric   auto *ConstInt = dyn_cast<ConstantInt>(Icmp->getOperand(1));
252706c3fb27SDimitry Andric   // Values wider than 64 bits cannot be represented within a DIExpression.
252806c3fb27SDimitry Andric   if (ConstInt && ConstInt->getBitWidth() > 64)
252906c3fb27SDimitry Andric     return nullptr;
253006c3fb27SDimitry Andric   // Push any Constant Int operand onto the expression stack.
253106c3fb27SDimitry Andric   if (ConstInt) {
253206c3fb27SDimitry Andric     if (Icmp->isSigned())
253306c3fb27SDimitry Andric       Opcodes.push_back(dwarf::DW_OP_consts);
253406c3fb27SDimitry Andric     else
253506c3fb27SDimitry Andric       Opcodes.push_back(dwarf::DW_OP_constu);
253606c3fb27SDimitry Andric     uint64_t Val = ConstInt->getSExtValue();
253706c3fb27SDimitry Andric     Opcodes.push_back(Val);
253806c3fb27SDimitry Andric   } else {
253906c3fb27SDimitry Andric     handleSSAValueOperands(CurrentLocOps, Opcodes, AdditionalValues, Icmp);
254006c3fb27SDimitry Andric   }
254106c3fb27SDimitry Andric 
254206c3fb27SDimitry Andric   // Add salvaged binary operator to expression stack, if it has a valid
254306c3fb27SDimitry Andric   // representation in a DIExpression.
254406c3fb27SDimitry Andric   uint64_t DwarfIcmpOp = getDwarfOpForIcmpPred(Icmp->getPredicate());
254506c3fb27SDimitry Andric   if (!DwarfIcmpOp)
254606c3fb27SDimitry Andric     return nullptr;
254706c3fb27SDimitry Andric   Opcodes.push_back(DwarfIcmpOp);
254806c3fb27SDimitry Andric   return Icmp->getOperand(0);
254906c3fb27SDimitry Andric }
255006c3fb27SDimitry Andric 
2551349cc55cSDimitry Andric Value *llvm::salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps,
2552349cc55cSDimitry Andric                                   SmallVectorImpl<uint64_t> &Ops,
2553fe6060f1SDimitry Andric                                   SmallVectorImpl<Value *> &AdditionalValues) {
25540b57cec5SDimitry Andric   auto &M = *I.getModule();
25550b57cec5SDimitry Andric   auto &DL = M.getDataLayout();
25560b57cec5SDimitry Andric 
25570b57cec5SDimitry Andric   if (auto *CI = dyn_cast<CastInst>(&I)) {
2558349cc55cSDimitry Andric     Value *FromValue = CI->getOperand(0);
25595ffd83dbSDimitry Andric     // No-op casts are irrelevant for debug info.
2560349cc55cSDimitry Andric     if (CI->isNoopCast(DL)) {
2561349cc55cSDimitry Andric       return FromValue;
2562349cc55cSDimitry Andric     }
2563480093f4SDimitry Andric 
2564480093f4SDimitry Andric     Type *Type = CI->getType();
2565349cc55cSDimitry Andric     if (Type->isPointerTy())
2566349cc55cSDimitry Andric       Type = DL.getIntPtrType(Type);
25675ffd83dbSDimitry Andric     // Casts other than Trunc, SExt, or ZExt to scalar types cannot be salvaged.
25685ffd83dbSDimitry Andric     if (Type->isVectorTy() ||
2569349cc55cSDimitry Andric         !(isa<TruncInst>(&I) || isa<SExtInst>(&I) || isa<ZExtInst>(&I) ||
2570349cc55cSDimitry Andric           isa<IntToPtrInst>(&I) || isa<PtrToIntInst>(&I)))
25710b57cec5SDimitry Andric       return nullptr;
2572480093f4SDimitry Andric 
2573349cc55cSDimitry Andric     llvm::Type *FromType = FromValue->getType();
2574349cc55cSDimitry Andric     if (FromType->isPointerTy())
2575349cc55cSDimitry Andric       FromType = DL.getIntPtrType(FromType);
2576349cc55cSDimitry Andric 
2577349cc55cSDimitry Andric     unsigned FromTypeBitSize = FromType->getScalarSizeInBits();
2578480093f4SDimitry Andric     unsigned ToTypeBitSize = Type->getScalarSizeInBits();
2579480093f4SDimitry Andric 
2580349cc55cSDimitry Andric     auto ExtOps = DIExpression::getExtOps(FromTypeBitSize, ToTypeBitSize,
2581349cc55cSDimitry Andric                                           isa<SExtInst>(&I));
2582349cc55cSDimitry Andric     Ops.append(ExtOps.begin(), ExtOps.end());
2583349cc55cSDimitry Andric     return FromValue;
2584480093f4SDimitry Andric   }
2585480093f4SDimitry Andric 
2586349cc55cSDimitry Andric   if (auto *GEP = dyn_cast<GetElementPtrInst>(&I))
2587349cc55cSDimitry Andric     return getSalvageOpsForGEP(GEP, DL, CurrentLocOps, Ops, AdditionalValues);
2588349cc55cSDimitry Andric   if (auto *BI = dyn_cast<BinaryOperator>(&I))
2589349cc55cSDimitry Andric     return getSalvageOpsForBinOp(BI, CurrentLocOps, Ops, AdditionalValues);
259006c3fb27SDimitry Andric   if (auto *IC = dyn_cast<ICmpInst>(&I))
259106c3fb27SDimitry Andric     return getSalvageOpsForIcmpOp(IC, CurrentLocOps, Ops, AdditionalValues);
2592349cc55cSDimitry Andric 
25930b57cec5SDimitry Andric   // *Not* to do: we should not attempt to salvage load instructions,
25940b57cec5SDimitry Andric   // because the validity and lifetime of a dbg.value containing
25950b57cec5SDimitry Andric   // DW_OP_deref becomes difficult to analyze. See PR40628 for examples.
25960b57cec5SDimitry Andric   return nullptr;
25970b57cec5SDimitry Andric }
25980b57cec5SDimitry Andric 
25990b57cec5SDimitry Andric /// A replacement for a dbg.value expression.
2600bdd1243dSDimitry Andric using DbgValReplacement = std::optional<DIExpression *>;
26010b57cec5SDimitry Andric 
26020b57cec5SDimitry Andric /// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
2603480093f4SDimitry Andric /// possibly moving/undefing users to prevent use-before-def. Returns true if
26040b57cec5SDimitry Andric /// changes are made.
26050b57cec5SDimitry Andric static bool rewriteDebugUsers(
26060b57cec5SDimitry Andric     Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
26075f757f3fSDimitry Andric     function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr,
26080fca6ea1SDimitry Andric     function_ref<DbgValReplacement(DbgVariableRecord &DVR)> RewriteDVRExpr) {
26090b57cec5SDimitry Andric   // Find debug users of From.
26100b57cec5SDimitry Andric   SmallVector<DbgVariableIntrinsic *, 1> Users;
26110fca6ea1SDimitry Andric   SmallVector<DbgVariableRecord *, 1> DPUsers;
26125f757f3fSDimitry Andric   findDbgUsers(Users, &From, &DPUsers);
26135f757f3fSDimitry Andric   if (Users.empty() && DPUsers.empty())
26140b57cec5SDimitry Andric     return false;
26150b57cec5SDimitry Andric 
26160b57cec5SDimitry Andric   // Prevent use-before-def of To.
26170b57cec5SDimitry Andric   bool Changed = false;
26185f757f3fSDimitry Andric 
2619480093f4SDimitry Andric   SmallPtrSet<DbgVariableIntrinsic *, 1> UndefOrSalvage;
26200fca6ea1SDimitry Andric   SmallPtrSet<DbgVariableRecord *, 1> UndefOrSalvageDVR;
26210b57cec5SDimitry Andric   if (isa<Instruction>(&To)) {
26220b57cec5SDimitry Andric     bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
26230b57cec5SDimitry Andric 
26240b57cec5SDimitry Andric     for (auto *DII : Users) {
26250b57cec5SDimitry Andric       // It's common to see a debug user between From and DomPoint. Move it
26260b57cec5SDimitry Andric       // after DomPoint to preserve the variable update without any reordering.
26270b57cec5SDimitry Andric       if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
26280b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "MOVE:  " << *DII << '\n');
26290b57cec5SDimitry Andric         DII->moveAfter(&DomPoint);
26300b57cec5SDimitry Andric         Changed = true;
26310b57cec5SDimitry Andric 
26320b57cec5SDimitry Andric       // Users which otherwise aren't dominated by the replacement value must
26330b57cec5SDimitry Andric       // be salvaged or deleted.
26340b57cec5SDimitry Andric       } else if (!DT.dominates(&DomPoint, DII)) {
2635480093f4SDimitry Andric         UndefOrSalvage.insert(DII);
26360b57cec5SDimitry Andric       }
26370b57cec5SDimitry Andric     }
26385f757f3fSDimitry Andric 
26390fca6ea1SDimitry Andric     // DbgVariableRecord implementation of the above.
26400fca6ea1SDimitry Andric     for (auto *DVR : DPUsers) {
26410fca6ea1SDimitry Andric       Instruction *MarkedInstr = DVR->getMarker()->MarkedInstr;
26425f757f3fSDimitry Andric       Instruction *NextNonDebug = MarkedInstr;
26435f757f3fSDimitry Andric       // The next instruction might still be a dbg.declare, skip over it.
26445f757f3fSDimitry Andric       if (isa<DbgVariableIntrinsic>(NextNonDebug))
26455f757f3fSDimitry Andric         NextNonDebug = NextNonDebug->getNextNonDebugInstruction();
26465f757f3fSDimitry Andric 
26475f757f3fSDimitry Andric       if (DomPointAfterFrom && NextNonDebug == &DomPoint) {
26480fca6ea1SDimitry Andric         LLVM_DEBUG(dbgs() << "MOVE:  " << *DVR << '\n');
26490fca6ea1SDimitry Andric         DVR->removeFromParent();
26505f757f3fSDimitry Andric         // Ensure there's a marker.
26510fca6ea1SDimitry Andric         DomPoint.getParent()->insertDbgRecordAfter(DVR, &DomPoint);
26525f757f3fSDimitry Andric         Changed = true;
26535f757f3fSDimitry Andric       } else if (!DT.dominates(&DomPoint, MarkedInstr)) {
26540fca6ea1SDimitry Andric         UndefOrSalvageDVR.insert(DVR);
26555f757f3fSDimitry Andric       }
26565f757f3fSDimitry Andric     }
26570b57cec5SDimitry Andric   }
26580b57cec5SDimitry Andric 
26590b57cec5SDimitry Andric   // Update debug users without use-before-def risk.
26600b57cec5SDimitry Andric   for (auto *DII : Users) {
2661480093f4SDimitry Andric     if (UndefOrSalvage.count(DII))
26620b57cec5SDimitry Andric       continue;
26630b57cec5SDimitry Andric 
26640fca6ea1SDimitry Andric     DbgValReplacement DVRepl = RewriteExpr(*DII);
26650fca6ea1SDimitry Andric     if (!DVRepl)
26660b57cec5SDimitry Andric       continue;
26670b57cec5SDimitry Andric 
2668fe6060f1SDimitry Andric     DII->replaceVariableLocationOp(&From, &To);
26690fca6ea1SDimitry Andric     DII->setExpression(*DVRepl);
26700b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "REWRITE:  " << *DII << '\n');
26710b57cec5SDimitry Andric     Changed = true;
26720b57cec5SDimitry Andric   }
26730fca6ea1SDimitry Andric   for (auto *DVR : DPUsers) {
26740fca6ea1SDimitry Andric     if (UndefOrSalvageDVR.count(DVR))
26755f757f3fSDimitry Andric       continue;
26760b57cec5SDimitry Andric 
26770fca6ea1SDimitry Andric     DbgValReplacement DVRepl = RewriteDVRExpr(*DVR);
26780fca6ea1SDimitry Andric     if (!DVRepl)
26795f757f3fSDimitry Andric       continue;
26805f757f3fSDimitry Andric 
26810fca6ea1SDimitry Andric     DVR->replaceVariableLocationOp(&From, &To);
26820fca6ea1SDimitry Andric     DVR->setExpression(*DVRepl);
26830fca6ea1SDimitry Andric     LLVM_DEBUG(dbgs() << "REWRITE:  " << DVR << '\n');
26845f757f3fSDimitry Andric     Changed = true;
26855f757f3fSDimitry Andric   }
26865f757f3fSDimitry Andric 
26870fca6ea1SDimitry Andric   if (!UndefOrSalvage.empty() || !UndefOrSalvageDVR.empty()) {
26880b57cec5SDimitry Andric     // Try to salvage the remaining debug users.
26895ffd83dbSDimitry Andric     salvageDebugInfo(From);
26900b57cec5SDimitry Andric     Changed = true;
26910b57cec5SDimitry Andric   }
26920b57cec5SDimitry Andric 
26930b57cec5SDimitry Andric   return Changed;
26940b57cec5SDimitry Andric }
26950b57cec5SDimitry Andric 
26960b57cec5SDimitry Andric /// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
26970b57cec5SDimitry Andric /// losslessly preserve the bits and semantics of the value. This predicate is
26980b57cec5SDimitry Andric /// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
26990b57cec5SDimitry Andric ///
27000b57cec5SDimitry Andric /// Note that Type::canLosslesslyBitCastTo is not suitable here because it
27010b57cec5SDimitry Andric /// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
27020b57cec5SDimitry Andric /// and also does not allow lossless pointer <-> integer conversions.
27030b57cec5SDimitry Andric static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
27040b57cec5SDimitry Andric                                          Type *ToTy) {
27050b57cec5SDimitry Andric   // Trivially compatible types.
27060b57cec5SDimitry Andric   if (FromTy == ToTy)
27070b57cec5SDimitry Andric     return true;
27080b57cec5SDimitry Andric 
27090b57cec5SDimitry Andric   // Handle compatible pointer <-> integer conversions.
27100b57cec5SDimitry Andric   if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
27110b57cec5SDimitry Andric     bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
27120b57cec5SDimitry Andric     bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
27130b57cec5SDimitry Andric                               !DL.isNonIntegralPointerType(ToTy);
27140b57cec5SDimitry Andric     return SameSize && LosslessConversion;
27150b57cec5SDimitry Andric   }
27160b57cec5SDimitry Andric 
27170b57cec5SDimitry Andric   // TODO: This is not exhaustive.
27180b57cec5SDimitry Andric   return false;
27190b57cec5SDimitry Andric }
27200b57cec5SDimitry Andric 
27210b57cec5SDimitry Andric bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
27220b57cec5SDimitry Andric                                  Instruction &DomPoint, DominatorTree &DT) {
27230b57cec5SDimitry Andric   // Exit early if From has no debug users.
27240b57cec5SDimitry Andric   if (!From.isUsedByMetadata())
27250b57cec5SDimitry Andric     return false;
27260b57cec5SDimitry Andric 
27270b57cec5SDimitry Andric   assert(&From != &To && "Can't replace something with itself");
27280b57cec5SDimitry Andric 
27290b57cec5SDimitry Andric   Type *FromTy = From.getType();
27300b57cec5SDimitry Andric   Type *ToTy = To.getType();
27310b57cec5SDimitry Andric 
27320b57cec5SDimitry Andric   auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
27330b57cec5SDimitry Andric     return DII.getExpression();
27340b57cec5SDimitry Andric   };
27350fca6ea1SDimitry Andric   auto IdentityDVR = [&](DbgVariableRecord &DVR) -> DbgValReplacement {
27360fca6ea1SDimitry Andric     return DVR.getExpression();
27375f757f3fSDimitry Andric   };
27380b57cec5SDimitry Andric 
27390b57cec5SDimitry Andric   // Handle no-op conversions.
27400b57cec5SDimitry Andric   Module &M = *From.getModule();
27410b57cec5SDimitry Andric   const DataLayout &DL = M.getDataLayout();
27420b57cec5SDimitry Andric   if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
27430fca6ea1SDimitry Andric     return rewriteDebugUsers(From, To, DomPoint, DT, Identity, IdentityDVR);
27440b57cec5SDimitry Andric 
27450b57cec5SDimitry Andric   // Handle integer-to-integer widening and narrowing.
27460b57cec5SDimitry Andric   // FIXME: Use DW_OP_convert when it's available everywhere.
27470b57cec5SDimitry Andric   if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
27480b57cec5SDimitry Andric     uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
27490b57cec5SDimitry Andric     uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
27500b57cec5SDimitry Andric     assert(FromBits != ToBits && "Unexpected no-op conversion");
27510b57cec5SDimitry Andric 
27520b57cec5SDimitry Andric     // When the width of the result grows, assume that a debugger will only
27530b57cec5SDimitry Andric     // access the low `FromBits` bits when inspecting the source variable.
27540b57cec5SDimitry Andric     if (FromBits < ToBits)
27550fca6ea1SDimitry Andric       return rewriteDebugUsers(From, To, DomPoint, DT, Identity, IdentityDVR);
27560b57cec5SDimitry Andric 
27570b57cec5SDimitry Andric     // The width of the result has shrunk. Use sign/zero extension to describe
27580b57cec5SDimitry Andric     // the source variable's high bits.
27590b57cec5SDimitry Andric     auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
27600b57cec5SDimitry Andric       DILocalVariable *Var = DII.getVariable();
27610b57cec5SDimitry Andric 
27620b57cec5SDimitry Andric       // Without knowing signedness, sign/zero extension isn't possible.
27630b57cec5SDimitry Andric       auto Signedness = Var->getSignedness();
27640b57cec5SDimitry Andric       if (!Signedness)
2765bdd1243dSDimitry Andric         return std::nullopt;
27660b57cec5SDimitry Andric 
27670b57cec5SDimitry Andric       bool Signed = *Signedness == DIBasicType::Signedness::Signed;
2768480093f4SDimitry Andric       return DIExpression::appendExt(DII.getExpression(), ToBits, FromBits,
2769480093f4SDimitry Andric                                      Signed);
27700b57cec5SDimitry Andric     };
27710fca6ea1SDimitry Andric     // RemoveDIs: duplicate implementation working on DbgVariableRecords rather
27720fca6ea1SDimitry Andric     // than on dbg.value intrinsics.
27730fca6ea1SDimitry Andric     auto SignOrZeroExtDVR = [&](DbgVariableRecord &DVR) -> DbgValReplacement {
27740fca6ea1SDimitry Andric       DILocalVariable *Var = DVR.getVariable();
27755f757f3fSDimitry Andric 
27765f757f3fSDimitry Andric       // Without knowing signedness, sign/zero extension isn't possible.
27775f757f3fSDimitry Andric       auto Signedness = Var->getSignedness();
27785f757f3fSDimitry Andric       if (!Signedness)
27795f757f3fSDimitry Andric         return std::nullopt;
27805f757f3fSDimitry Andric 
27815f757f3fSDimitry Andric       bool Signed = *Signedness == DIBasicType::Signedness::Signed;
27820fca6ea1SDimitry Andric       return DIExpression::appendExt(DVR.getExpression(), ToBits, FromBits,
27835f757f3fSDimitry Andric                                      Signed);
27845f757f3fSDimitry Andric     };
27855f757f3fSDimitry Andric     return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt,
27860fca6ea1SDimitry Andric                              SignOrZeroExtDVR);
27870b57cec5SDimitry Andric   }
27880b57cec5SDimitry Andric 
27890b57cec5SDimitry Andric   // TODO: Floating-point conversions, vectors.
27900b57cec5SDimitry Andric   return false;
27910b57cec5SDimitry Andric }
27920b57cec5SDimitry Andric 
27930fca6ea1SDimitry Andric bool llvm::handleUnreachableTerminator(
27940fca6ea1SDimitry Andric     Instruction *I, SmallVectorImpl<Value *> &PoisonedValues) {
27950fca6ea1SDimitry Andric   bool Changed = false;
27960fca6ea1SDimitry Andric   // RemoveDIs: erase debug-info on this instruction manually.
27970fca6ea1SDimitry Andric   I->dropDbgRecords();
27980fca6ea1SDimitry Andric   for (Use &U : I->operands()) {
27990fca6ea1SDimitry Andric     Value *Op = U.get();
28000fca6ea1SDimitry Andric     if (isa<Instruction>(Op) && !Op->getType()->isTokenTy()) {
28010fca6ea1SDimitry Andric       U.set(PoisonValue::get(Op->getType()));
28020fca6ea1SDimitry Andric       PoisonedValues.push_back(Op);
28030fca6ea1SDimitry Andric       Changed = true;
28040fca6ea1SDimitry Andric     }
28050fca6ea1SDimitry Andric   }
28060fca6ea1SDimitry Andric 
28070fca6ea1SDimitry Andric   return Changed;
28080fca6ea1SDimitry Andric }
28090fca6ea1SDimitry Andric 
2810e8d8bef9SDimitry Andric std::pair<unsigned, unsigned>
2811e8d8bef9SDimitry Andric llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
28120b57cec5SDimitry Andric   unsigned NumDeadInst = 0;
2813e8d8bef9SDimitry Andric   unsigned NumDeadDbgInst = 0;
28140b57cec5SDimitry Andric   // Delete the instructions backwards, as it has a reduced likelihood of
28150b57cec5SDimitry Andric   // having to update as many def-use and use-def chains.
28160b57cec5SDimitry Andric   Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
28170fca6ea1SDimitry Andric   SmallVector<Value *> Uses;
28180fca6ea1SDimitry Andric   handleUnreachableTerminator(EndInst, Uses);
28190fca6ea1SDimitry Andric 
28200b57cec5SDimitry Andric   while (EndInst != &BB->front()) {
28210b57cec5SDimitry Andric     // Delete the next to last instruction.
28220b57cec5SDimitry Andric     Instruction *Inst = &*--EndInst->getIterator();
28230b57cec5SDimitry Andric     if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
2824fcaf7f86SDimitry Andric       Inst->replaceAllUsesWith(PoisonValue::get(Inst->getType()));
28250b57cec5SDimitry Andric     if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
28260fca6ea1SDimitry Andric       // EHPads can't have DbgVariableRecords attached to them, but it might be
28270fca6ea1SDimitry Andric       // possible for things with token type.
28280fca6ea1SDimitry Andric       Inst->dropDbgRecords();
28290b57cec5SDimitry Andric       EndInst = Inst;
28300b57cec5SDimitry Andric       continue;
28310b57cec5SDimitry Andric     }
2832e8d8bef9SDimitry Andric     if (isa<DbgInfoIntrinsic>(Inst))
2833e8d8bef9SDimitry Andric       ++NumDeadDbgInst;
2834e8d8bef9SDimitry Andric     else
28350b57cec5SDimitry Andric       ++NumDeadInst;
28365f757f3fSDimitry Andric     // RemoveDIs: erasing debug-info must be done manually.
28370fca6ea1SDimitry Andric     Inst->dropDbgRecords();
28380b57cec5SDimitry Andric     Inst->eraseFromParent();
28390b57cec5SDimitry Andric   }
2840e8d8bef9SDimitry Andric   return {NumDeadInst, NumDeadDbgInst};
28410b57cec5SDimitry Andric }
28420b57cec5SDimitry Andric 
2843fe6060f1SDimitry Andric unsigned llvm::changeToUnreachable(Instruction *I, bool PreserveLCSSA,
2844fe6060f1SDimitry Andric                                    DomTreeUpdater *DTU,
28450b57cec5SDimitry Andric                                    MemorySSAUpdater *MSSAU) {
28460b57cec5SDimitry Andric   BasicBlock *BB = I->getParent();
28470b57cec5SDimitry Andric 
28480b57cec5SDimitry Andric   if (MSSAU)
28490b57cec5SDimitry Andric     MSSAU->changeToUnreachable(I);
28500b57cec5SDimitry Andric 
2851fe6060f1SDimitry Andric   SmallSet<BasicBlock *, 8> UniqueSuccessors;
2852e8d8bef9SDimitry Andric 
28530b57cec5SDimitry Andric   // Loop over all of the successors, removing BB's entry from any PHI
28540b57cec5SDimitry Andric   // nodes.
28550b57cec5SDimitry Andric   for (BasicBlock *Successor : successors(BB)) {
28560b57cec5SDimitry Andric     Successor->removePredecessor(BB, PreserveLCSSA);
28570b57cec5SDimitry Andric     if (DTU)
2858e8d8bef9SDimitry Andric       UniqueSuccessors.insert(Successor);
28590b57cec5SDimitry Andric   }
28600fca6ea1SDimitry Andric   auto *UI = new UnreachableInst(I->getContext(), I->getIterator());
28610b57cec5SDimitry Andric   UI->setDebugLoc(I->getDebugLoc());
28620b57cec5SDimitry Andric 
28630b57cec5SDimitry Andric   // All instructions after this are dead.
28640b57cec5SDimitry Andric   unsigned NumInstrsRemoved = 0;
28650b57cec5SDimitry Andric   BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
28660b57cec5SDimitry Andric   while (BBI != BBE) {
28670b57cec5SDimitry Andric     if (!BBI->use_empty())
2868fcaf7f86SDimitry Andric       BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
2869bdd1243dSDimitry Andric     BBI++->eraseFromParent();
28700b57cec5SDimitry Andric     ++NumInstrsRemoved;
28710b57cec5SDimitry Andric   }
2872e8d8bef9SDimitry Andric   if (DTU) {
2873e8d8bef9SDimitry Andric     SmallVector<DominatorTree::UpdateType, 8> Updates;
2874e8d8bef9SDimitry Andric     Updates.reserve(UniqueSuccessors.size());
2875e8d8bef9SDimitry Andric     for (BasicBlock *UniqueSuccessor : UniqueSuccessors)
2876e8d8bef9SDimitry Andric       Updates.push_back({DominatorTree::Delete, BB, UniqueSuccessor});
2877e8d8bef9SDimitry Andric     DTU->applyUpdates(Updates);
2878e8d8bef9SDimitry Andric   }
28790fca6ea1SDimitry Andric   BB->flushTerminatorDbgRecords();
28800b57cec5SDimitry Andric   return NumInstrsRemoved;
28810b57cec5SDimitry Andric }
28820b57cec5SDimitry Andric 
28838bcb0991SDimitry Andric CallInst *llvm::createCallMatchingInvoke(InvokeInst *II) {
2884e8d8bef9SDimitry Andric   SmallVector<Value *, 8> Args(II->args());
28850b57cec5SDimitry Andric   SmallVector<OperandBundleDef, 1> OpBundles;
28860b57cec5SDimitry Andric   II->getOperandBundlesAsDefs(OpBundles);
28878bcb0991SDimitry Andric   CallInst *NewCall = CallInst::Create(II->getFunctionType(),
28885ffd83dbSDimitry Andric                                        II->getCalledOperand(), Args, OpBundles);
28890b57cec5SDimitry Andric   NewCall->setCallingConv(II->getCallingConv());
28900b57cec5SDimitry Andric   NewCall->setAttributes(II->getAttributes());
28910b57cec5SDimitry Andric   NewCall->setDebugLoc(II->getDebugLoc());
28920b57cec5SDimitry Andric   NewCall->copyMetadata(*II);
28935ffd83dbSDimitry Andric 
28945ffd83dbSDimitry Andric   // If the invoke had profile metadata, try converting them for CallInst.
28955ffd83dbSDimitry Andric   uint64_t TotalWeight;
28965ffd83dbSDimitry Andric   if (NewCall->extractProfTotalWeight(TotalWeight)) {
28975ffd83dbSDimitry Andric     // Set the total weight if it fits into i32, otherwise reset.
28985ffd83dbSDimitry Andric     MDBuilder MDB(NewCall->getContext());
28995ffd83dbSDimitry Andric     auto NewWeights = uint32_t(TotalWeight) != TotalWeight
29005ffd83dbSDimitry Andric                           ? nullptr
29015ffd83dbSDimitry Andric                           : MDB.createBranchWeights({uint32_t(TotalWeight)});
29025ffd83dbSDimitry Andric     NewCall->setMetadata(LLVMContext::MD_prof, NewWeights);
29035ffd83dbSDimitry Andric   }
29045ffd83dbSDimitry Andric 
29058bcb0991SDimitry Andric   return NewCall;
29068bcb0991SDimitry Andric }
29078bcb0991SDimitry Andric 
290804eeddc0SDimitry Andric // changeToCall - Convert the specified invoke into a normal call.
290904eeddc0SDimitry Andric CallInst *llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) {
29108bcb0991SDimitry Andric   CallInst *NewCall = createCallMatchingInvoke(II);
29118bcb0991SDimitry Andric   NewCall->takeName(II);
29128bcb0991SDimitry Andric   NewCall->insertBefore(II);
29130b57cec5SDimitry Andric   II->replaceAllUsesWith(NewCall);
29140b57cec5SDimitry Andric 
29150b57cec5SDimitry Andric   // Follow the call by a branch to the normal destination.
29160b57cec5SDimitry Andric   BasicBlock *NormalDestBB = II->getNormalDest();
29170fca6ea1SDimitry Andric   BranchInst::Create(NormalDestBB, II->getIterator());
29180b57cec5SDimitry Andric 
29190b57cec5SDimitry Andric   // Update PHI nodes in the unwind destination
29200b57cec5SDimitry Andric   BasicBlock *BB = II->getParent();
29210b57cec5SDimitry Andric   BasicBlock *UnwindDestBB = II->getUnwindDest();
29220b57cec5SDimitry Andric   UnwindDestBB->removePredecessor(BB);
29230b57cec5SDimitry Andric   II->eraseFromParent();
29240b57cec5SDimitry Andric   if (DTU)
2925e8d8bef9SDimitry Andric     DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});
292604eeddc0SDimitry Andric   return NewCall;
29270b57cec5SDimitry Andric }
29280b57cec5SDimitry Andric 
29290b57cec5SDimitry Andric BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
2930fe6060f1SDimitry Andric                                                    BasicBlock *UnwindEdge,
2931fe6060f1SDimitry Andric                                                    DomTreeUpdater *DTU) {
29320b57cec5SDimitry Andric   BasicBlock *BB = CI->getParent();
29330b57cec5SDimitry Andric 
29340b57cec5SDimitry Andric   // Convert this function call into an invoke instruction.  First, split the
29350b57cec5SDimitry Andric   // basic block.
2936fe6060f1SDimitry Andric   BasicBlock *Split = SplitBlock(BB, CI, DTU, /*LI=*/nullptr, /*MSSAU*/ nullptr,
2937fe6060f1SDimitry Andric                                  CI->getName() + ".noexc");
29380b57cec5SDimitry Andric 
2939fe6060f1SDimitry Andric   // Delete the unconditional branch inserted by SplitBlock
2940bdd1243dSDimitry Andric   BB->back().eraseFromParent();
29410b57cec5SDimitry Andric 
29420b57cec5SDimitry Andric   // Create the new invoke instruction.
2943e8d8bef9SDimitry Andric   SmallVector<Value *, 8> InvokeArgs(CI->args());
29440b57cec5SDimitry Andric   SmallVector<OperandBundleDef, 1> OpBundles;
29450b57cec5SDimitry Andric 
29460b57cec5SDimitry Andric   CI->getOperandBundlesAsDefs(OpBundles);
29470b57cec5SDimitry Andric 
29480b57cec5SDimitry Andric   // Note: we're round tripping operand bundles through memory here, and that
29490b57cec5SDimitry Andric   // can potentially be avoided with a cleverer API design that we do not have
29500b57cec5SDimitry Andric   // as of this time.
29510b57cec5SDimitry Andric 
29520b57cec5SDimitry Andric   InvokeInst *II =
29535ffd83dbSDimitry Andric       InvokeInst::Create(CI->getFunctionType(), CI->getCalledOperand(), Split,
29540b57cec5SDimitry Andric                          UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);
29550b57cec5SDimitry Andric   II->setDebugLoc(CI->getDebugLoc());
29560b57cec5SDimitry Andric   II->setCallingConv(CI->getCallingConv());
29570b57cec5SDimitry Andric   II->setAttributes(CI->getAttributes());
295881ad6265SDimitry Andric   II->setMetadata(LLVMContext::MD_prof, CI->getMetadata(LLVMContext::MD_prof));
29590b57cec5SDimitry Andric 
2960fe6060f1SDimitry Andric   if (DTU)
2961fe6060f1SDimitry Andric     DTU->applyUpdates({{DominatorTree::Insert, BB, UnwindEdge}});
2962fe6060f1SDimitry Andric 
29630b57cec5SDimitry Andric   // Make sure that anything using the call now uses the invoke!  This also
29640b57cec5SDimitry Andric   // updates the CallGraph if present, because it uses a WeakTrackingVH.
29650b57cec5SDimitry Andric   CI->replaceAllUsesWith(II);
29660b57cec5SDimitry Andric 
29670b57cec5SDimitry Andric   // Delete the original call
2968bdd1243dSDimitry Andric   Split->front().eraseFromParent();
29690b57cec5SDimitry Andric   return Split;
29700b57cec5SDimitry Andric }
29710b57cec5SDimitry Andric 
29720b57cec5SDimitry Andric static bool markAliveBlocks(Function &F,
29730b57cec5SDimitry Andric                             SmallPtrSetImpl<BasicBlock *> &Reachable,
29740b57cec5SDimitry Andric                             DomTreeUpdater *DTU = nullptr) {
29750b57cec5SDimitry Andric   SmallVector<BasicBlock*, 128> Worklist;
29760b57cec5SDimitry Andric   BasicBlock *BB = &F.front();
29770b57cec5SDimitry Andric   Worklist.push_back(BB);
29780b57cec5SDimitry Andric   Reachable.insert(BB);
29790b57cec5SDimitry Andric   bool Changed = false;
29800b57cec5SDimitry Andric   do {
29810b57cec5SDimitry Andric     BB = Worklist.pop_back_val();
29820b57cec5SDimitry Andric 
29830b57cec5SDimitry Andric     // Do a quick scan of the basic block, turning any obviously unreachable
29840b57cec5SDimitry Andric     // instructions into LLVM unreachable insts.  The instruction combining pass
29850b57cec5SDimitry Andric     // canonicalizes unreachable insts into stores to null or undef.
29860b57cec5SDimitry Andric     for (Instruction &I : *BB) {
29870b57cec5SDimitry Andric       if (auto *CI = dyn_cast<CallInst>(&I)) {
29885ffd83dbSDimitry Andric         Value *Callee = CI->getCalledOperand();
29890b57cec5SDimitry Andric         // Handle intrinsic calls.
29900b57cec5SDimitry Andric         if (Function *F = dyn_cast<Function>(Callee)) {
29910b57cec5SDimitry Andric           auto IntrinsicID = F->getIntrinsicID();
29920b57cec5SDimitry Andric           // Assumptions that are known to be false are equivalent to
29930b57cec5SDimitry Andric           // unreachable. Also, if the condition is undefined, then we make the
29940b57cec5SDimitry Andric           // choice most beneficial to the optimizer, and choose that to also be
29950b57cec5SDimitry Andric           // unreachable.
29960b57cec5SDimitry Andric           if (IntrinsicID == Intrinsic::assume) {
29970b57cec5SDimitry Andric             if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
29980b57cec5SDimitry Andric               // Don't insert a call to llvm.trap right before the unreachable.
2999fe6060f1SDimitry Andric               changeToUnreachable(CI, false, DTU);
30000b57cec5SDimitry Andric               Changed = true;
30010b57cec5SDimitry Andric               break;
30020b57cec5SDimitry Andric             }
30030b57cec5SDimitry Andric           } else if (IntrinsicID == Intrinsic::experimental_guard) {
30040b57cec5SDimitry Andric             // A call to the guard intrinsic bails out of the current
30050b57cec5SDimitry Andric             // compilation unit if the predicate passed to it is false. If the
30060b57cec5SDimitry Andric             // predicate is a constant false, then we know the guard will bail
30070b57cec5SDimitry Andric             // out of the current compile unconditionally, so all code following
30080b57cec5SDimitry Andric             // it is dead.
30090b57cec5SDimitry Andric             //
30100b57cec5SDimitry Andric             // Note: unlike in llvm.assume, it is not "obviously profitable" for
30110b57cec5SDimitry Andric             // guards to treat `undef` as `false` since a guard on `undef` can
30120b57cec5SDimitry Andric             // still be useful for widening.
30130b57cec5SDimitry Andric             if (match(CI->getArgOperand(0), m_Zero()))
30140b57cec5SDimitry Andric               if (!isa<UnreachableInst>(CI->getNextNode())) {
3015fe6060f1SDimitry Andric                 changeToUnreachable(CI->getNextNode(), false, DTU);
30160b57cec5SDimitry Andric                 Changed = true;
30170b57cec5SDimitry Andric                 break;
30180b57cec5SDimitry Andric               }
30190b57cec5SDimitry Andric           }
30200b57cec5SDimitry Andric         } else if ((isa<ConstantPointerNull>(Callee) &&
3021bdd1243dSDimitry Andric                     !NullPointerIsDefined(CI->getFunction(),
3022bdd1243dSDimitry Andric                                           cast<PointerType>(Callee->getType())
3023bdd1243dSDimitry Andric                                               ->getAddressSpace())) ||
30240b57cec5SDimitry Andric                    isa<UndefValue>(Callee)) {
3025fe6060f1SDimitry Andric           changeToUnreachable(CI, false, DTU);
30260b57cec5SDimitry Andric           Changed = true;
30270b57cec5SDimitry Andric           break;
30280b57cec5SDimitry Andric         }
30290b57cec5SDimitry Andric         if (CI->doesNotReturn() && !CI->isMustTailCall()) {
30300b57cec5SDimitry Andric           // If we found a call to a no-return function, insert an unreachable
30310b57cec5SDimitry Andric           // instruction after it.  Make sure there isn't *already* one there
30320b57cec5SDimitry Andric           // though.
30335f757f3fSDimitry Andric           if (!isa<UnreachableInst>(CI->getNextNonDebugInstruction())) {
30340b57cec5SDimitry Andric             // Don't insert a call to llvm.trap right before the unreachable.
30355f757f3fSDimitry Andric             changeToUnreachable(CI->getNextNonDebugInstruction(), false, DTU);
30360b57cec5SDimitry Andric             Changed = true;
30370b57cec5SDimitry Andric           }
30380b57cec5SDimitry Andric           break;
30390b57cec5SDimitry Andric         }
30400b57cec5SDimitry Andric       } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
30410b57cec5SDimitry Andric         // Store to undef and store to null are undefined and used to signal
30420b57cec5SDimitry Andric         // that they should be changed to unreachable by passes that can't
30430b57cec5SDimitry Andric         // modify the CFG.
30440b57cec5SDimitry Andric 
30450b57cec5SDimitry Andric         // Don't touch volatile stores.
30460b57cec5SDimitry Andric         if (SI->isVolatile()) continue;
30470b57cec5SDimitry Andric 
30480b57cec5SDimitry Andric         Value *Ptr = SI->getOperand(1);
30490b57cec5SDimitry Andric 
30500b57cec5SDimitry Andric         if (isa<UndefValue>(Ptr) ||
30510b57cec5SDimitry Andric             (isa<ConstantPointerNull>(Ptr) &&
30520b57cec5SDimitry Andric              !NullPointerIsDefined(SI->getFunction(),
30530b57cec5SDimitry Andric                                    SI->getPointerAddressSpace()))) {
3054fe6060f1SDimitry Andric           changeToUnreachable(SI, false, DTU);
30550b57cec5SDimitry Andric           Changed = true;
30560b57cec5SDimitry Andric           break;
30570b57cec5SDimitry Andric         }
30580b57cec5SDimitry Andric       }
30590b57cec5SDimitry Andric     }
30600b57cec5SDimitry Andric 
30610b57cec5SDimitry Andric     Instruction *Terminator = BB->getTerminator();
30620b57cec5SDimitry Andric     if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
30630b57cec5SDimitry Andric       // Turn invokes that call 'nounwind' functions into ordinary calls.
30645ffd83dbSDimitry Andric       Value *Callee = II->getCalledOperand();
30650b57cec5SDimitry Andric       if ((isa<ConstantPointerNull>(Callee) &&
30660b57cec5SDimitry Andric            !NullPointerIsDefined(BB->getParent())) ||
30670b57cec5SDimitry Andric           isa<UndefValue>(Callee)) {
3068fe6060f1SDimitry Andric         changeToUnreachable(II, false, DTU);
30690b57cec5SDimitry Andric         Changed = true;
307081ad6265SDimitry Andric       } else {
307181ad6265SDimitry Andric         if (II->doesNotReturn() &&
307281ad6265SDimitry Andric             !isa<UnreachableInst>(II->getNormalDest()->front())) {
307381ad6265SDimitry Andric           // If we found an invoke of a no-return function,
307481ad6265SDimitry Andric           // create a new empty basic block with an `unreachable` terminator,
307581ad6265SDimitry Andric           // and set it as the normal destination for the invoke,
307681ad6265SDimitry Andric           // unless that is already the case.
307781ad6265SDimitry Andric           // Note that the original normal destination could have other uses.
307881ad6265SDimitry Andric           BasicBlock *OrigNormalDest = II->getNormalDest();
307981ad6265SDimitry Andric           OrigNormalDest->removePredecessor(II->getParent());
308081ad6265SDimitry Andric           LLVMContext &Ctx = II->getContext();
308181ad6265SDimitry Andric           BasicBlock *UnreachableNormalDest = BasicBlock::Create(
308281ad6265SDimitry Andric               Ctx, OrigNormalDest->getName() + ".unreachable",
308381ad6265SDimitry Andric               II->getFunction(), OrigNormalDest);
308481ad6265SDimitry Andric           new UnreachableInst(Ctx, UnreachableNormalDest);
308581ad6265SDimitry Andric           II->setNormalDest(UnreachableNormalDest);
308681ad6265SDimitry Andric           if (DTU)
308781ad6265SDimitry Andric             DTU->applyUpdates(
308881ad6265SDimitry Andric                 {{DominatorTree::Delete, BB, OrigNormalDest},
308981ad6265SDimitry Andric                  {DominatorTree::Insert, BB, UnreachableNormalDest}});
309081ad6265SDimitry Andric           Changed = true;
309181ad6265SDimitry Andric         }
309281ad6265SDimitry Andric         if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
309356f451bbSDimitry Andric           if (II->use_empty() && !II->mayHaveSideEffects()) {
30940b57cec5SDimitry Andric             // jump to the normal destination branch.
30950b57cec5SDimitry Andric             BasicBlock *NormalDestBB = II->getNormalDest();
30960b57cec5SDimitry Andric             BasicBlock *UnwindDestBB = II->getUnwindDest();
30970fca6ea1SDimitry Andric             BranchInst::Create(NormalDestBB, II->getIterator());
30980b57cec5SDimitry Andric             UnwindDestBB->removePredecessor(II->getParent());
30990b57cec5SDimitry Andric             II->eraseFromParent();
31000b57cec5SDimitry Andric             if (DTU)
3101e8d8bef9SDimitry Andric               DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});
31020b57cec5SDimitry Andric           } else
31030b57cec5SDimitry Andric             changeToCall(II, DTU);
31040b57cec5SDimitry Andric           Changed = true;
31050b57cec5SDimitry Andric         }
310681ad6265SDimitry Andric       }
31070b57cec5SDimitry Andric     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
31080b57cec5SDimitry Andric       // Remove catchpads which cannot be reached.
31090b57cec5SDimitry Andric       struct CatchPadDenseMapInfo {
31100b57cec5SDimitry Andric         static CatchPadInst *getEmptyKey() {
31110b57cec5SDimitry Andric           return DenseMapInfo<CatchPadInst *>::getEmptyKey();
31120b57cec5SDimitry Andric         }
31130b57cec5SDimitry Andric 
31140b57cec5SDimitry Andric         static CatchPadInst *getTombstoneKey() {
31150b57cec5SDimitry Andric           return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
31160b57cec5SDimitry Andric         }
31170b57cec5SDimitry Andric 
31180b57cec5SDimitry Andric         static unsigned getHashValue(CatchPadInst *CatchPad) {
31190b57cec5SDimitry Andric           return static_cast<unsigned>(hash_combine_range(
31200b57cec5SDimitry Andric               CatchPad->value_op_begin(), CatchPad->value_op_end()));
31210b57cec5SDimitry Andric         }
31220b57cec5SDimitry Andric 
31230b57cec5SDimitry Andric         static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
31240b57cec5SDimitry Andric           if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
31250b57cec5SDimitry Andric               RHS == getEmptyKey() || RHS == getTombstoneKey())
31260b57cec5SDimitry Andric             return LHS == RHS;
31270b57cec5SDimitry Andric           return LHS->isIdenticalTo(RHS);
31280b57cec5SDimitry Andric         }
31290b57cec5SDimitry Andric       };
31300b57cec5SDimitry Andric 
3131fe6060f1SDimitry Andric       SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
31320b57cec5SDimitry Andric       // Set of unique CatchPads.
31330b57cec5SDimitry Andric       SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
31340b57cec5SDimitry Andric                     CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
31350b57cec5SDimitry Andric           HandlerSet;
31360b57cec5SDimitry Andric       detail::DenseSetEmpty Empty;
31370b57cec5SDimitry Andric       for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
31380b57cec5SDimitry Andric                                              E = CatchSwitch->handler_end();
31390b57cec5SDimitry Andric            I != E; ++I) {
31400b57cec5SDimitry Andric         BasicBlock *HandlerBB = *I;
3141fe6060f1SDimitry Andric         if (DTU)
3142e8d8bef9SDimitry Andric           ++NumPerSuccessorCases[HandlerBB];
31430b57cec5SDimitry Andric         auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
31440b57cec5SDimitry Andric         if (!HandlerSet.insert({CatchPad, Empty}).second) {
3145fe6060f1SDimitry Andric           if (DTU)
3146e8d8bef9SDimitry Andric             --NumPerSuccessorCases[HandlerBB];
31470b57cec5SDimitry Andric           CatchSwitch->removeHandler(I);
31480b57cec5SDimitry Andric           --I;
31490b57cec5SDimitry Andric           --E;
31500b57cec5SDimitry Andric           Changed = true;
31510b57cec5SDimitry Andric         }
31520b57cec5SDimitry Andric       }
3153fe6060f1SDimitry Andric       if (DTU) {
3154e8d8bef9SDimitry Andric         std::vector<DominatorTree::UpdateType> Updates;
3155e8d8bef9SDimitry Andric         for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
3156e8d8bef9SDimitry Andric           if (I.second == 0)
3157e8d8bef9SDimitry Andric             Updates.push_back({DominatorTree::Delete, BB, I.first});
3158e8d8bef9SDimitry Andric         DTU->applyUpdates(Updates);
31590b57cec5SDimitry Andric       }
3160fe6060f1SDimitry Andric     }
31610b57cec5SDimitry Andric 
31620b57cec5SDimitry Andric     Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
31630b57cec5SDimitry Andric     for (BasicBlock *Successor : successors(BB))
31640b57cec5SDimitry Andric       if (Reachable.insert(Successor).second)
31650b57cec5SDimitry Andric         Worklist.push_back(Successor);
31660b57cec5SDimitry Andric   } while (!Worklist.empty());
31670b57cec5SDimitry Andric   return Changed;
31680b57cec5SDimitry Andric }
31690b57cec5SDimitry Andric 
3170bdd1243dSDimitry Andric Instruction *llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
31710b57cec5SDimitry Andric   Instruction *TI = BB->getTerminator();
31720b57cec5SDimitry Andric 
3173bdd1243dSDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(TI))
3174bdd1243dSDimitry Andric     return changeToCall(II, DTU);
31750b57cec5SDimitry Andric 
31760b57cec5SDimitry Andric   Instruction *NewTI;
31770b57cec5SDimitry Andric   BasicBlock *UnwindDest;
31780b57cec5SDimitry Andric 
31790b57cec5SDimitry Andric   if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
31800fca6ea1SDimitry Andric     NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI->getIterator());
31810b57cec5SDimitry Andric     UnwindDest = CRI->getUnwindDest();
31820b57cec5SDimitry Andric   } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
31830b57cec5SDimitry Andric     auto *NewCatchSwitch = CatchSwitchInst::Create(
31840b57cec5SDimitry Andric         CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
31850fca6ea1SDimitry Andric         CatchSwitch->getName(), CatchSwitch->getIterator());
31860b57cec5SDimitry Andric     for (BasicBlock *PadBB : CatchSwitch->handlers())
31870b57cec5SDimitry Andric       NewCatchSwitch->addHandler(PadBB);
31880b57cec5SDimitry Andric 
31890b57cec5SDimitry Andric     NewTI = NewCatchSwitch;
31900b57cec5SDimitry Andric     UnwindDest = CatchSwitch->getUnwindDest();
31910b57cec5SDimitry Andric   } else {
31920b57cec5SDimitry Andric     llvm_unreachable("Could not find unwind successor");
31930b57cec5SDimitry Andric   }
31940b57cec5SDimitry Andric 
31950b57cec5SDimitry Andric   NewTI->takeName(TI);
31960b57cec5SDimitry Andric   NewTI->setDebugLoc(TI->getDebugLoc());
31970b57cec5SDimitry Andric   UnwindDest->removePredecessor(BB);
31980b57cec5SDimitry Andric   TI->replaceAllUsesWith(NewTI);
31990b57cec5SDimitry Andric   TI->eraseFromParent();
32000b57cec5SDimitry Andric   if (DTU)
3201e8d8bef9SDimitry Andric     DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDest}});
3202bdd1243dSDimitry Andric   return NewTI;
32030b57cec5SDimitry Andric }
32040b57cec5SDimitry Andric 
32050b57cec5SDimitry Andric /// removeUnreachableBlocks - Remove blocks that are not reachable, even
32060b57cec5SDimitry Andric /// if they are in a dead cycle.  Return true if a change was made, false
32078bcb0991SDimitry Andric /// otherwise.
32088bcb0991SDimitry Andric bool llvm::removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
32090b57cec5SDimitry Andric                                    MemorySSAUpdater *MSSAU) {
32100b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> Reachable;
32110b57cec5SDimitry Andric   bool Changed = markAliveBlocks(F, Reachable, DTU);
32120b57cec5SDimitry Andric 
32130b57cec5SDimitry Andric   // If there are unreachable blocks in the CFG...
32140b57cec5SDimitry Andric   if (Reachable.size() == F.size())
32150b57cec5SDimitry Andric     return Changed;
32160b57cec5SDimitry Andric 
32170b57cec5SDimitry Andric   assert(Reachable.size() < F.size());
32180b57cec5SDimitry Andric 
3219e8d8bef9SDimitry Andric   // Are there any blocks left to actually delete?
3220e8d8bef9SDimitry Andric   SmallSetVector<BasicBlock *, 8> BlocksToRemove;
32218bcb0991SDimitry Andric   for (BasicBlock &BB : F) {
32228bcb0991SDimitry Andric     // Skip reachable basic blocks
32235ffd83dbSDimitry Andric     if (Reachable.count(&BB))
32240b57cec5SDimitry Andric       continue;
3225e8d8bef9SDimitry Andric     // Skip already-deleted blocks
3226e8d8bef9SDimitry Andric     if (DTU && DTU->isBBPendingDeletion(&BB))
3227e8d8bef9SDimitry Andric       continue;
3228e8d8bef9SDimitry Andric     BlocksToRemove.insert(&BB);
32290b57cec5SDimitry Andric   }
32300b57cec5SDimitry Andric 
3231e8d8bef9SDimitry Andric   if (BlocksToRemove.empty())
3232e8d8bef9SDimitry Andric     return Changed;
32330b57cec5SDimitry Andric 
3234e8d8bef9SDimitry Andric   Changed = true;
3235e8d8bef9SDimitry Andric   NumRemoved += BlocksToRemove.size();
3236e8d8bef9SDimitry Andric 
3237e8d8bef9SDimitry Andric   if (MSSAU)
3238e8d8bef9SDimitry Andric     MSSAU->removeBlocks(BlocksToRemove);
3239e8d8bef9SDimitry Andric 
3240fe6060f1SDimitry Andric   DeleteDeadBlocks(BlocksToRemove.takeVector(), DTU);
32418bcb0991SDimitry Andric 
3242e8d8bef9SDimitry Andric   return Changed;
32430b57cec5SDimitry Andric }
32440b57cec5SDimitry Andric 
32450b57cec5SDimitry Andric void llvm::combineMetadata(Instruction *K, const Instruction *J,
32460b57cec5SDimitry Andric                            ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
32470b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
32480b57cec5SDimitry Andric   K->dropUnknownNonDebugMetadata(KnownIDs);
32490b57cec5SDimitry Andric   K->getAllMetadataOtherThanDebugLoc(Metadata);
32500b57cec5SDimitry Andric   for (const auto &MD : Metadata) {
32510b57cec5SDimitry Andric     unsigned Kind = MD.first;
32520b57cec5SDimitry Andric     MDNode *JMD = J->getMetadata(Kind);
32530b57cec5SDimitry Andric     MDNode *KMD = MD.second;
32540b57cec5SDimitry Andric 
32550b57cec5SDimitry Andric     switch (Kind) {
32560b57cec5SDimitry Andric       default:
32570b57cec5SDimitry Andric         K->setMetadata(Kind, nullptr); // Remove unknown metadata
32580b57cec5SDimitry Andric         break;
32590b57cec5SDimitry Andric       case LLVMContext::MD_dbg:
32600b57cec5SDimitry Andric         llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
3261bdd1243dSDimitry Andric       case LLVMContext::MD_DIAssignID:
3262bdd1243dSDimitry Andric         K->mergeDIAssignID(J);
3263bdd1243dSDimitry Andric         break;
32640b57cec5SDimitry Andric       case LLVMContext::MD_tbaa:
32650b57cec5SDimitry Andric         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
32660b57cec5SDimitry Andric         break;
32670b57cec5SDimitry Andric       case LLVMContext::MD_alias_scope:
32680b57cec5SDimitry Andric         K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
32690b57cec5SDimitry Andric         break;
32700b57cec5SDimitry Andric       case LLVMContext::MD_noalias:
32710b57cec5SDimitry Andric       case LLVMContext::MD_mem_parallel_loop_access:
32720b57cec5SDimitry Andric         K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
32730b57cec5SDimitry Andric         break;
32740b57cec5SDimitry Andric       case LLVMContext::MD_access_group:
32750b57cec5SDimitry Andric         K->setMetadata(LLVMContext::MD_access_group,
32760b57cec5SDimitry Andric                        intersectAccessGroups(K, J));
32770b57cec5SDimitry Andric         break;
32780b57cec5SDimitry Andric       case LLVMContext::MD_range:
327906c3fb27SDimitry Andric         if (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef))
32800b57cec5SDimitry Andric           K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
32810b57cec5SDimitry Andric         break;
32820b57cec5SDimitry Andric       case LLVMContext::MD_fpmath:
32830b57cec5SDimitry Andric         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
32840b57cec5SDimitry Andric         break;
32850b57cec5SDimitry Andric       case LLVMContext::MD_invariant_load:
328606c3fb27SDimitry Andric         // If K moves, only set the !invariant.load if it is present in both
328706c3fb27SDimitry Andric         // instructions.
328806c3fb27SDimitry Andric         if (DoesKMove)
32890b57cec5SDimitry Andric           K->setMetadata(Kind, JMD);
32900b57cec5SDimitry Andric         break;
32910b57cec5SDimitry Andric       case LLVMContext::MD_nonnull:
329206c3fb27SDimitry Andric         if (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef))
32930b57cec5SDimitry Andric           K->setMetadata(Kind, JMD);
32940b57cec5SDimitry Andric         break;
32950b57cec5SDimitry Andric       case LLVMContext::MD_invariant_group:
32960b57cec5SDimitry Andric         // Preserve !invariant.group in K.
32970b57cec5SDimitry Andric         break;
32980fca6ea1SDimitry Andric       case LLVMContext::MD_mmra:
32990fca6ea1SDimitry Andric         // Combine MMRAs
33000fca6ea1SDimitry Andric         break;
33010b57cec5SDimitry Andric       case LLVMContext::MD_align:
330206c3fb27SDimitry Andric         if (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef))
330306c3fb27SDimitry Andric           K->setMetadata(
330406c3fb27SDimitry Andric               Kind, MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
33050b57cec5SDimitry Andric         break;
33060b57cec5SDimitry Andric       case LLVMContext::MD_dereferenceable:
33070b57cec5SDimitry Andric       case LLVMContext::MD_dereferenceable_or_null:
330806c3fb27SDimitry Andric         if (DoesKMove)
33090b57cec5SDimitry Andric           K->setMetadata(Kind,
33100b57cec5SDimitry Andric             MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
33110b57cec5SDimitry Andric         break;
33128bcb0991SDimitry Andric       case LLVMContext::MD_preserve_access_index:
33138bcb0991SDimitry Andric         // Preserve !preserve.access.index in K.
33148bcb0991SDimitry Andric         break;
331506c3fb27SDimitry Andric       case LLVMContext::MD_noundef:
331606c3fb27SDimitry Andric         // If K does move, keep noundef if it is present in both instructions.
331706c3fb27SDimitry Andric         if (DoesKMove)
331806c3fb27SDimitry Andric           K->setMetadata(Kind, JMD);
331906c3fb27SDimitry Andric         break;
332006c3fb27SDimitry Andric       case LLVMContext::MD_nontemporal:
332106c3fb27SDimitry Andric         // Preserve !nontemporal if it is present on both instructions.
332206c3fb27SDimitry Andric         K->setMetadata(Kind, JMD);
332306c3fb27SDimitry Andric         break;
332406c3fb27SDimitry Andric       case LLVMContext::MD_prof:
332506c3fb27SDimitry Andric         if (DoesKMove)
332606c3fb27SDimitry Andric           K->setMetadata(Kind, MDNode::getMergedProfMetadata(KMD, JMD, K, J));
332706c3fb27SDimitry Andric         break;
33280b57cec5SDimitry Andric     }
33290b57cec5SDimitry Andric   }
33300b57cec5SDimitry Andric   // Set !invariant.group from J if J has it. If both instructions have it
33310b57cec5SDimitry Andric   // then we will just pick it from J - even when they are different.
33320b57cec5SDimitry Andric   // Also make sure that K is load or store - f.e. combining bitcast with load
33330b57cec5SDimitry Andric   // could produce bitcast with invariant.group metadata, which is invalid.
33340b57cec5SDimitry Andric   // FIXME: we should try to preserve both invariant.group md if they are
33350b57cec5SDimitry Andric   // different, but right now instruction can only have one invariant.group.
33360b57cec5SDimitry Andric   if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
33370b57cec5SDimitry Andric     if (isa<LoadInst>(K) || isa<StoreInst>(K))
33380b57cec5SDimitry Andric       K->setMetadata(LLVMContext::MD_invariant_group, JMD);
33390fca6ea1SDimitry Andric 
33400fca6ea1SDimitry Andric   // Merge MMRAs.
33410fca6ea1SDimitry Andric   // This is handled separately because we also want to handle cases where K
33420fca6ea1SDimitry Andric   // doesn't have tags but J does.
33430fca6ea1SDimitry Andric   auto JMMRA = J->getMetadata(LLVMContext::MD_mmra);
33440fca6ea1SDimitry Andric   auto KMMRA = K->getMetadata(LLVMContext::MD_mmra);
33450fca6ea1SDimitry Andric   if (JMMRA || KMMRA) {
33460fca6ea1SDimitry Andric     K->setMetadata(LLVMContext::MD_mmra,
33470fca6ea1SDimitry Andric                    MMRAMetadata::combine(K->getContext(), JMMRA, KMMRA));
33480fca6ea1SDimitry Andric   }
33490b57cec5SDimitry Andric }
33500b57cec5SDimitry Andric 
33510b57cec5SDimitry Andric void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
33520b57cec5SDimitry Andric                                  bool KDominatesJ) {
335306c3fb27SDimitry Andric   unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
335406c3fb27SDimitry Andric                          LLVMContext::MD_alias_scope,
335506c3fb27SDimitry Andric                          LLVMContext::MD_noalias,
335606c3fb27SDimitry Andric                          LLVMContext::MD_range,
335706c3fb27SDimitry Andric                          LLVMContext::MD_fpmath,
335806c3fb27SDimitry Andric                          LLVMContext::MD_invariant_load,
335906c3fb27SDimitry Andric                          LLVMContext::MD_nonnull,
336006c3fb27SDimitry Andric                          LLVMContext::MD_invariant_group,
336106c3fb27SDimitry Andric                          LLVMContext::MD_align,
33620b57cec5SDimitry Andric                          LLVMContext::MD_dereferenceable,
33630b57cec5SDimitry Andric                          LLVMContext::MD_dereferenceable_or_null,
336406c3fb27SDimitry Andric                          LLVMContext::MD_access_group,
336506c3fb27SDimitry Andric                          LLVMContext::MD_preserve_access_index,
336606c3fb27SDimitry Andric                          LLVMContext::MD_prof,
336706c3fb27SDimitry Andric                          LLVMContext::MD_nontemporal,
33680fca6ea1SDimitry Andric                          LLVMContext::MD_noundef,
33690fca6ea1SDimitry Andric                          LLVMContext::MD_mmra};
33700b57cec5SDimitry Andric   combineMetadata(K, J, KnownIDs, KDominatesJ);
33710b57cec5SDimitry Andric }
33720b57cec5SDimitry Andric 
33738bcb0991SDimitry Andric void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) {
33748bcb0991SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
33758bcb0991SDimitry Andric   Source.getAllMetadata(MD);
33768bcb0991SDimitry Andric   MDBuilder MDB(Dest.getContext());
33778bcb0991SDimitry Andric   Type *NewType = Dest.getType();
33780fca6ea1SDimitry Andric   const DataLayout &DL = Source.getDataLayout();
33798bcb0991SDimitry Andric   for (const auto &MDPair : MD) {
33808bcb0991SDimitry Andric     unsigned ID = MDPair.first;
33818bcb0991SDimitry Andric     MDNode *N = MDPair.second;
33828bcb0991SDimitry Andric     // Note, essentially every kind of metadata should be preserved here! This
33838bcb0991SDimitry Andric     // routine is supposed to clone a load instruction changing *only its type*.
33848bcb0991SDimitry Andric     // The only metadata it makes sense to drop is metadata which is invalidated
33858bcb0991SDimitry Andric     // when the pointer type changes. This should essentially never be the case
33868bcb0991SDimitry Andric     // in LLVM, but we explicitly switch over only known metadata to be
33878bcb0991SDimitry Andric     // conservatively correct. If you are adding metadata to LLVM which pertains
33888bcb0991SDimitry Andric     // to loads, you almost certainly want to add it here.
33898bcb0991SDimitry Andric     switch (ID) {
33908bcb0991SDimitry Andric     case LLVMContext::MD_dbg:
33918bcb0991SDimitry Andric     case LLVMContext::MD_tbaa:
33928bcb0991SDimitry Andric     case LLVMContext::MD_prof:
33938bcb0991SDimitry Andric     case LLVMContext::MD_fpmath:
33948bcb0991SDimitry Andric     case LLVMContext::MD_tbaa_struct:
33958bcb0991SDimitry Andric     case LLVMContext::MD_invariant_load:
33968bcb0991SDimitry Andric     case LLVMContext::MD_alias_scope:
33978bcb0991SDimitry Andric     case LLVMContext::MD_noalias:
33988bcb0991SDimitry Andric     case LLVMContext::MD_nontemporal:
33998bcb0991SDimitry Andric     case LLVMContext::MD_mem_parallel_loop_access:
34008bcb0991SDimitry Andric     case LLVMContext::MD_access_group:
3401bdd1243dSDimitry Andric     case LLVMContext::MD_noundef:
34028bcb0991SDimitry Andric       // All of these directly apply.
34038bcb0991SDimitry Andric       Dest.setMetadata(ID, N);
34048bcb0991SDimitry Andric       break;
34058bcb0991SDimitry Andric 
34068bcb0991SDimitry Andric     case LLVMContext::MD_nonnull:
34078bcb0991SDimitry Andric       copyNonnullMetadata(Source, N, Dest);
34088bcb0991SDimitry Andric       break;
34098bcb0991SDimitry Andric 
34108bcb0991SDimitry Andric     case LLVMContext::MD_align:
34118bcb0991SDimitry Andric     case LLVMContext::MD_dereferenceable:
34128bcb0991SDimitry Andric     case LLVMContext::MD_dereferenceable_or_null:
34138bcb0991SDimitry Andric       // These only directly apply if the new type is also a pointer.
34148bcb0991SDimitry Andric       if (NewType->isPointerTy())
34158bcb0991SDimitry Andric         Dest.setMetadata(ID, N);
34168bcb0991SDimitry Andric       break;
34178bcb0991SDimitry Andric 
34188bcb0991SDimitry Andric     case LLVMContext::MD_range:
34198bcb0991SDimitry Andric       copyRangeMetadata(DL, Source, N, Dest);
34208bcb0991SDimitry Andric       break;
34218bcb0991SDimitry Andric     }
34228bcb0991SDimitry Andric   }
34238bcb0991SDimitry Andric }
34248bcb0991SDimitry Andric 
34250b57cec5SDimitry Andric void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
34260b57cec5SDimitry Andric   auto *ReplInst = dyn_cast<Instruction>(Repl);
34270b57cec5SDimitry Andric   if (!ReplInst)
34280b57cec5SDimitry Andric     return;
34290b57cec5SDimitry Andric 
34300b57cec5SDimitry Andric   // Patch the replacement so that it is not more restrictive than the value
34310b57cec5SDimitry Andric   // being replaced.
34324c2d3b02SDimitry Andric   WithOverflowInst *UnusedWO;
34334c2d3b02SDimitry Andric   // When replacing the result of a llvm.*.with.overflow intrinsic with a
34344c2d3b02SDimitry Andric   // overflowing binary operator, nuw/nsw flags may no longer hold.
34354c2d3b02SDimitry Andric   if (isa<OverflowingBinaryOperator>(ReplInst) &&
34364c2d3b02SDimitry Andric       match(I, m_ExtractValue<0>(m_WithOverflowInst(UnusedWO))))
34374c2d3b02SDimitry Andric     ReplInst->dropPoisonGeneratingFlags();
34380b57cec5SDimitry Andric   // Note that if 'I' is a load being replaced by some operation,
34390b57cec5SDimitry Andric   // for example, by an arithmetic operation, then andIRFlags()
34400b57cec5SDimitry Andric   // would just erase all math flags from the original arithmetic
34410b57cec5SDimitry Andric   // operation, which is clearly not wanted and not needed.
34424c2d3b02SDimitry Andric   else if (!isa<LoadInst>(I))
34430b57cec5SDimitry Andric     ReplInst->andIRFlags(I);
34440b57cec5SDimitry Andric 
34450b57cec5SDimitry Andric   // FIXME: If both the original and replacement value are part of the
34460b57cec5SDimitry Andric   // same control-flow region (meaning that the execution of one
34470b57cec5SDimitry Andric   // guarantees the execution of the other), then we can combine the
34480b57cec5SDimitry Andric   // noalias scopes here and do better than the general conservative
34490b57cec5SDimitry Andric   // answer used in combineMetadata().
34500b57cec5SDimitry Andric 
34510b57cec5SDimitry Andric   // In general, GVN unifies expressions over different control-flow
34520b57cec5SDimitry Andric   // regions, and so we need a conservative combination of the noalias
34530b57cec5SDimitry Andric   // scopes.
345406c3fb27SDimitry Andric   combineMetadataForCSE(ReplInst, I, false);
34550b57cec5SDimitry Andric }
34560b57cec5SDimitry Andric 
34570fca6ea1SDimitry Andric template <typename RootType, typename ShouldReplaceFn>
34580b57cec5SDimitry Andric static unsigned replaceDominatedUsesWith(Value *From, Value *To,
34590b57cec5SDimitry Andric                                          const RootType &Root,
34600fca6ea1SDimitry Andric                                          const ShouldReplaceFn &ShouldReplace) {
34610b57cec5SDimitry Andric   assert(From->getType() == To->getType());
34620b57cec5SDimitry Andric 
34630b57cec5SDimitry Andric   unsigned Count = 0;
3464349cc55cSDimitry Andric   for (Use &U : llvm::make_early_inc_range(From->uses())) {
34650fca6ea1SDimitry Andric     if (!ShouldReplace(Root, U))
34660b57cec5SDimitry Andric       continue;
34675f757f3fSDimitry Andric     LLVM_DEBUG(dbgs() << "Replace dominated use of '";
34685f757f3fSDimitry Andric                From->printAsOperand(dbgs());
34695f757f3fSDimitry Andric                dbgs() << "' with " << *To << " in " << *U.getUser() << "\n");
34700b57cec5SDimitry Andric     U.set(To);
34710b57cec5SDimitry Andric     ++Count;
34720b57cec5SDimitry Andric   }
34730b57cec5SDimitry Andric   return Count;
34740b57cec5SDimitry Andric }
34750b57cec5SDimitry Andric 
34760b57cec5SDimitry Andric unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
34770b57cec5SDimitry Andric    assert(From->getType() == To->getType());
34780b57cec5SDimitry Andric    auto *BB = From->getParent();
34790b57cec5SDimitry Andric    unsigned Count = 0;
34800b57cec5SDimitry Andric 
3481349cc55cSDimitry Andric    for (Use &U : llvm::make_early_inc_range(From->uses())) {
34820b57cec5SDimitry Andric     auto *I = cast<Instruction>(U.getUser());
34830b57cec5SDimitry Andric     if (I->getParent() == BB)
34840b57cec5SDimitry Andric       continue;
34850b57cec5SDimitry Andric     U.set(To);
34860b57cec5SDimitry Andric     ++Count;
34870b57cec5SDimitry Andric   }
34880b57cec5SDimitry Andric   return Count;
34890b57cec5SDimitry Andric }
34900b57cec5SDimitry Andric 
34910b57cec5SDimitry Andric unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
34920b57cec5SDimitry Andric                                         DominatorTree &DT,
34930b57cec5SDimitry Andric                                         const BasicBlockEdge &Root) {
34940b57cec5SDimitry Andric   auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
34950b57cec5SDimitry Andric     return DT.dominates(Root, U);
34960b57cec5SDimitry Andric   };
34970b57cec5SDimitry Andric   return ::replaceDominatedUsesWith(From, To, Root, Dominates);
34980b57cec5SDimitry Andric }
34990b57cec5SDimitry Andric 
35000b57cec5SDimitry Andric unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
35010b57cec5SDimitry Andric                                         DominatorTree &DT,
35020b57cec5SDimitry Andric                                         const BasicBlock *BB) {
3503fe6060f1SDimitry Andric   auto Dominates = [&DT](const BasicBlock *BB, const Use &U) {
3504fe6060f1SDimitry Andric     return DT.dominates(BB, U);
35050b57cec5SDimitry Andric   };
3506fe6060f1SDimitry Andric   return ::replaceDominatedUsesWith(From, To, BB, Dominates);
35070b57cec5SDimitry Andric }
35080b57cec5SDimitry Andric 
35090fca6ea1SDimitry Andric unsigned llvm::replaceDominatedUsesWithIf(
35100fca6ea1SDimitry Andric     Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Root,
35110fca6ea1SDimitry Andric     function_ref<bool(const Use &U, const Value *To)> ShouldReplace) {
35120fca6ea1SDimitry Andric   auto DominatesAndShouldReplace =
35130fca6ea1SDimitry Andric       [&DT, &ShouldReplace, To](const BasicBlockEdge &Root, const Use &U) {
35140fca6ea1SDimitry Andric         return DT.dominates(Root, U) && ShouldReplace(U, To);
35150fca6ea1SDimitry Andric       };
35160fca6ea1SDimitry Andric   return ::replaceDominatedUsesWith(From, To, Root, DominatesAndShouldReplace);
35170fca6ea1SDimitry Andric }
35180fca6ea1SDimitry Andric 
35190fca6ea1SDimitry Andric unsigned llvm::replaceDominatedUsesWithIf(
35200fca6ea1SDimitry Andric     Value *From, Value *To, DominatorTree &DT, const BasicBlock *BB,
35210fca6ea1SDimitry Andric     function_ref<bool(const Use &U, const Value *To)> ShouldReplace) {
35220fca6ea1SDimitry Andric   auto DominatesAndShouldReplace = [&DT, &ShouldReplace,
35230fca6ea1SDimitry Andric                                     To](const BasicBlock *BB, const Use &U) {
35240fca6ea1SDimitry Andric     return DT.dominates(BB, U) && ShouldReplace(U, To);
35250fca6ea1SDimitry Andric   };
35260fca6ea1SDimitry Andric   return ::replaceDominatedUsesWith(From, To, BB, DominatesAndShouldReplace);
35270fca6ea1SDimitry Andric }
35280fca6ea1SDimitry Andric 
35290b57cec5SDimitry Andric bool llvm::callsGCLeafFunction(const CallBase *Call,
35300b57cec5SDimitry Andric                                const TargetLibraryInfo &TLI) {
35310b57cec5SDimitry Andric   // Check if the function is specifically marked as a gc leaf function.
35320b57cec5SDimitry Andric   if (Call->hasFnAttr("gc-leaf-function"))
35330b57cec5SDimitry Andric     return true;
35340b57cec5SDimitry Andric   if (const Function *F = Call->getCalledFunction()) {
35350b57cec5SDimitry Andric     if (F->hasFnAttribute("gc-leaf-function"))
35360b57cec5SDimitry Andric       return true;
35370b57cec5SDimitry Andric 
3538e8d8bef9SDimitry Andric     if (auto IID = F->getIntrinsicID()) {
35390b57cec5SDimitry Andric       // Most LLVM intrinsics do not take safepoints.
35400b57cec5SDimitry Andric       return IID != Intrinsic::experimental_gc_statepoint &&
3541e8d8bef9SDimitry Andric              IID != Intrinsic::experimental_deoptimize &&
3542e8d8bef9SDimitry Andric              IID != Intrinsic::memcpy_element_unordered_atomic &&
3543e8d8bef9SDimitry Andric              IID != Intrinsic::memmove_element_unordered_atomic;
3544e8d8bef9SDimitry Andric     }
35450b57cec5SDimitry Andric   }
35460b57cec5SDimitry Andric 
35470b57cec5SDimitry Andric   // Lib calls can be materialized by some passes, and won't be
35480b57cec5SDimitry Andric   // marked as 'gc-leaf-function.' All available Libcalls are
35490b57cec5SDimitry Andric   // GC-leaf.
35500b57cec5SDimitry Andric   LibFunc LF;
35515ffd83dbSDimitry Andric   if (TLI.getLibFunc(*Call, LF)) {
35520b57cec5SDimitry Andric     return TLI.has(LF);
35530b57cec5SDimitry Andric   }
35540b57cec5SDimitry Andric 
35550b57cec5SDimitry Andric   return false;
35560b57cec5SDimitry Andric }
35570b57cec5SDimitry Andric 
35580b57cec5SDimitry Andric void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
35590b57cec5SDimitry Andric                                LoadInst &NewLI) {
35600b57cec5SDimitry Andric   auto *NewTy = NewLI.getType();
35610b57cec5SDimitry Andric 
35620b57cec5SDimitry Andric   // This only directly applies if the new type is also a pointer.
35630b57cec5SDimitry Andric   if (NewTy->isPointerTy()) {
35640b57cec5SDimitry Andric     NewLI.setMetadata(LLVMContext::MD_nonnull, N);
35650b57cec5SDimitry Andric     return;
35660b57cec5SDimitry Andric   }
35670b57cec5SDimitry Andric 
35680b57cec5SDimitry Andric   // The only other translation we can do is to integral loads with !range
35690b57cec5SDimitry Andric   // metadata.
35700b57cec5SDimitry Andric   if (!NewTy->isIntegerTy())
35710b57cec5SDimitry Andric     return;
35720b57cec5SDimitry Andric 
35730b57cec5SDimitry Andric   MDBuilder MDB(NewLI.getContext());
35740b57cec5SDimitry Andric   const Value *Ptr = OldLI.getPointerOperand();
35750b57cec5SDimitry Andric   auto *ITy = cast<IntegerType>(NewTy);
35760b57cec5SDimitry Andric   auto *NullInt = ConstantExpr::getPtrToInt(
35770b57cec5SDimitry Andric       ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
35780b57cec5SDimitry Andric   auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
35790b57cec5SDimitry Andric   NewLI.setMetadata(LLVMContext::MD_range,
35800b57cec5SDimitry Andric                     MDB.createRange(NonNullInt, NullInt));
35810b57cec5SDimitry Andric }
35820b57cec5SDimitry Andric 
35830b57cec5SDimitry Andric void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
35840b57cec5SDimitry Andric                              MDNode *N, LoadInst &NewLI) {
35850b57cec5SDimitry Andric   auto *NewTy = NewLI.getType();
3586bdd1243dSDimitry Andric   // Simply copy the metadata if the type did not change.
3587bdd1243dSDimitry Andric   if (NewTy == OldLI.getType()) {
3588bdd1243dSDimitry Andric     NewLI.setMetadata(LLVMContext::MD_range, N);
3589bdd1243dSDimitry Andric     return;
3590bdd1243dSDimitry Andric   }
35910b57cec5SDimitry Andric 
35920b57cec5SDimitry Andric   // Give up unless it is converted to a pointer where there is a single very
35930b57cec5SDimitry Andric   // valuable mapping we can do reliably.
35940b57cec5SDimitry Andric   // FIXME: It would be nice to propagate this in more ways, but the type
35950b57cec5SDimitry Andric   // conversions make it hard.
35960b57cec5SDimitry Andric   if (!NewTy->isPointerTy())
35970b57cec5SDimitry Andric     return;
35980b57cec5SDimitry Andric 
3599480093f4SDimitry Andric   unsigned BitWidth = DL.getPointerTypeSizeInBits(NewTy);
36001ac55f4cSDimitry Andric   if (BitWidth == OldLI.getType()->getScalarSizeInBits() &&
36011ac55f4cSDimitry Andric       !getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
3602bdd1243dSDimitry Andric     MDNode *NN = MDNode::get(OldLI.getContext(), std::nullopt);
36030b57cec5SDimitry Andric     NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
36040b57cec5SDimitry Andric   }
36050b57cec5SDimitry Andric }
36060b57cec5SDimitry Andric 
36070b57cec5SDimitry Andric void llvm::dropDebugUsers(Instruction &I) {
36080b57cec5SDimitry Andric   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
36090fca6ea1SDimitry Andric   SmallVector<DbgVariableRecord *, 1> DPUsers;
36105f757f3fSDimitry Andric   findDbgUsers(DbgUsers, &I, &DPUsers);
36110b57cec5SDimitry Andric   for (auto *DII : DbgUsers)
36120b57cec5SDimitry Andric     DII->eraseFromParent();
36130fca6ea1SDimitry Andric   for (auto *DVR : DPUsers)
36140fca6ea1SDimitry Andric     DVR->eraseFromParent();
36150b57cec5SDimitry Andric }
36160b57cec5SDimitry Andric 
36170b57cec5SDimitry Andric void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
36180b57cec5SDimitry Andric                                     BasicBlock *BB) {
36190b57cec5SDimitry Andric   // Since we are moving the instructions out of its basic block, we do not
36200b57cec5SDimitry Andric   // retain their original debug locations (DILocations) and debug intrinsic
36210b57cec5SDimitry Andric   // instructions.
36220b57cec5SDimitry Andric   //
36230b57cec5SDimitry Andric   // Doing so would degrade the debugging experience and adversely affect the
36240b57cec5SDimitry Andric   // accuracy of profiling information.
36250b57cec5SDimitry Andric   //
36260b57cec5SDimitry Andric   // Currently, when hoisting the instructions, we take the following actions:
36270b57cec5SDimitry Andric   // - Remove their debug intrinsic instructions.
36280b57cec5SDimitry Andric   // - Set their debug locations to the values from the insertion point.
36290b57cec5SDimitry Andric   //
36300b57cec5SDimitry Andric   // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
36310b57cec5SDimitry Andric   // need to be deleted, is because there will not be any instructions with a
36320b57cec5SDimitry Andric   // DILocation in either branch left after performing the transformation. We
36330b57cec5SDimitry Andric   // can only insert a dbg.value after the two branches are joined again.
36340b57cec5SDimitry Andric   //
36350b57cec5SDimitry Andric   // See PR38762, PR39243 for more details.
36360b57cec5SDimitry Andric   //
36370b57cec5SDimitry Andric   // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
36380b57cec5SDimitry Andric   // encode predicated DIExpressions that yield different results on different
36390b57cec5SDimitry Andric   // code paths.
3640fe6060f1SDimitry Andric 
36410b57cec5SDimitry Andric   for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
36420b57cec5SDimitry Andric     Instruction *I = &*II;
364306c3fb27SDimitry Andric     I->dropUBImplyingAttrsAndMetadata();
36440b57cec5SDimitry Andric     if (I->isUsedByMetadata())
36450b57cec5SDimitry Andric       dropDebugUsers(*I);
36465f757f3fSDimitry Andric     // RemoveDIs: drop debug-info too as the following code does.
36470fca6ea1SDimitry Andric     I->dropDbgRecords();
3648fe6060f1SDimitry Andric     if (I->isDebugOrPseudoInst()) {
3649fe6060f1SDimitry Andric       // Remove DbgInfo and pseudo probe Intrinsics.
36500b57cec5SDimitry Andric       II = I->eraseFromParent();
36510b57cec5SDimitry Andric       continue;
36520b57cec5SDimitry Andric     }
36530b57cec5SDimitry Andric     I->setDebugLoc(InsertPt->getDebugLoc());
36540b57cec5SDimitry Andric     ++II;
36550b57cec5SDimitry Andric   }
3656bdd1243dSDimitry Andric   DomBlock->splice(InsertPt->getIterator(), BB, BB->begin(),
36570b57cec5SDimitry Andric                    BB->getTerminator()->getIterator());
36580b57cec5SDimitry Andric }
36590b57cec5SDimitry Andric 
36605f757f3fSDimitry Andric DIExpression *llvm::getExpressionForConstant(DIBuilder &DIB, const Constant &C,
36615f757f3fSDimitry Andric                                              Type &Ty) {
36625f757f3fSDimitry Andric   // Create integer constant expression.
36635f757f3fSDimitry Andric   auto createIntegerExpression = [&DIB](const Constant &CV) -> DIExpression * {
36645f757f3fSDimitry Andric     const APInt &API = cast<ConstantInt>(&CV)->getValue();
36655f757f3fSDimitry Andric     std::optional<int64_t> InitIntOpt = API.trySExtValue();
36665f757f3fSDimitry Andric     return InitIntOpt ? DIB.createConstantValueExpression(
36675f757f3fSDimitry Andric                             static_cast<uint64_t>(*InitIntOpt))
36685f757f3fSDimitry Andric                       : nullptr;
36695f757f3fSDimitry Andric   };
36705f757f3fSDimitry Andric 
36715f757f3fSDimitry Andric   if (isa<ConstantInt>(C))
36725f757f3fSDimitry Andric     return createIntegerExpression(C);
36735f757f3fSDimitry Andric 
3674647cbc5dSDimitry Andric   auto *FP = dyn_cast<ConstantFP>(&C);
36750fca6ea1SDimitry Andric   if (FP && Ty.isFloatingPointTy() && Ty.getScalarSizeInBits() <= 64) {
3676647cbc5dSDimitry Andric     const APFloat &APF = FP->getValueAPF();
36770fca6ea1SDimitry Andric     APInt const &API = APF.bitcastToAPInt();
36780fca6ea1SDimitry Andric     if (auto Temp = API.getZExtValue())
36790fca6ea1SDimitry Andric       return DIB.createConstantValueExpression(static_cast<uint64_t>(Temp));
36800fca6ea1SDimitry Andric     return DIB.createConstantValueExpression(*API.getRawData());
36815f757f3fSDimitry Andric   }
36825f757f3fSDimitry Andric 
36835f757f3fSDimitry Andric   if (!Ty.isPointerTy())
36845f757f3fSDimitry Andric     return nullptr;
36855f757f3fSDimitry Andric 
36865f757f3fSDimitry Andric   if (isa<ConstantPointerNull>(C))
36875f757f3fSDimitry Andric     return DIB.createConstantValueExpression(0);
36885f757f3fSDimitry Andric 
36895f757f3fSDimitry Andric   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(&C))
36905f757f3fSDimitry Andric     if (CE->getOpcode() == Instruction::IntToPtr) {
36915f757f3fSDimitry Andric       const Value *V = CE->getOperand(0);
36925f757f3fSDimitry Andric       if (auto CI = dyn_cast_or_null<ConstantInt>(V))
36935f757f3fSDimitry Andric         return createIntegerExpression(*CI);
36945f757f3fSDimitry Andric     }
36955f757f3fSDimitry Andric   return nullptr;
36965f757f3fSDimitry Andric }
36975f757f3fSDimitry Andric 
36980fca6ea1SDimitry Andric void llvm::remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst) {
36990fca6ea1SDimitry Andric   auto RemapDebugOperands = [&Mapping](auto *DV, auto Set) {
37000fca6ea1SDimitry Andric     for (auto *Op : Set) {
37010fca6ea1SDimitry Andric       auto I = Mapping.find(Op);
37020fca6ea1SDimitry Andric       if (I != Mapping.end())
37030fca6ea1SDimitry Andric         DV->replaceVariableLocationOp(Op, I->second, /*AllowEmpty=*/true);
37040fca6ea1SDimitry Andric     }
37050fca6ea1SDimitry Andric   };
37060fca6ea1SDimitry Andric   auto RemapAssignAddress = [&Mapping](auto *DA) {
37070fca6ea1SDimitry Andric     auto I = Mapping.find(DA->getAddress());
37080fca6ea1SDimitry Andric     if (I != Mapping.end())
37090fca6ea1SDimitry Andric       DA->setAddress(I->second);
37100fca6ea1SDimitry Andric   };
37110fca6ea1SDimitry Andric   if (auto DVI = dyn_cast<DbgVariableIntrinsic>(Inst))
37120fca6ea1SDimitry Andric     RemapDebugOperands(DVI, DVI->location_ops());
37130fca6ea1SDimitry Andric   if (auto DAI = dyn_cast<DbgAssignIntrinsic>(Inst))
37140fca6ea1SDimitry Andric     RemapAssignAddress(DAI);
37150fca6ea1SDimitry Andric   for (DbgVariableRecord &DVR : filterDbgVars(Inst->getDbgRecordRange())) {
37160fca6ea1SDimitry Andric     RemapDebugOperands(&DVR, DVR.location_ops());
37170fca6ea1SDimitry Andric     if (DVR.isDbgAssign())
37180fca6ea1SDimitry Andric       RemapAssignAddress(&DVR);
37190fca6ea1SDimitry Andric   }
37200fca6ea1SDimitry Andric }
37210fca6ea1SDimitry Andric 
37220b57cec5SDimitry Andric namespace {
37230b57cec5SDimitry Andric 
37240b57cec5SDimitry Andric /// A potential constituent of a bitreverse or bswap expression. See
37250b57cec5SDimitry Andric /// collectBitParts for a fuller explanation.
37260b57cec5SDimitry Andric struct BitPart {
37270b57cec5SDimitry Andric   BitPart(Value *P, unsigned BW) : Provider(P) {
37280b57cec5SDimitry Andric     Provenance.resize(BW);
37290b57cec5SDimitry Andric   }
37300b57cec5SDimitry Andric 
37310b57cec5SDimitry Andric   /// The Value that this is a bitreverse/bswap of.
37320b57cec5SDimitry Andric   Value *Provider;
37330b57cec5SDimitry Andric 
37340b57cec5SDimitry Andric   /// The "provenance" of each bit. Provenance[A] = B means that bit A
37350b57cec5SDimitry Andric   /// in Provider becomes bit B in the result of this expression.
37360b57cec5SDimitry Andric   SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
37370b57cec5SDimitry Andric 
37380b57cec5SDimitry Andric   enum { Unset = -1 };
37390b57cec5SDimitry Andric };
37400b57cec5SDimitry Andric 
37410b57cec5SDimitry Andric } // end anonymous namespace
37420b57cec5SDimitry Andric 
37430b57cec5SDimitry Andric /// Analyze the specified subexpression and see if it is capable of providing
37440b57cec5SDimitry Andric /// pieces of a bswap or bitreverse. The subexpression provides a potential
3745e8d8bef9SDimitry Andric /// piece of a bswap or bitreverse if it can be proved that each non-zero bit in
37460b57cec5SDimitry Andric /// the output of the expression came from a corresponding bit in some other
37470b57cec5SDimitry Andric /// value. This function is recursive, and the end result is a mapping of
37480b57cec5SDimitry Andric /// bitnumber to bitnumber. It is the caller's responsibility to validate that
37490b57cec5SDimitry Andric /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
37500b57cec5SDimitry Andric ///
37510b57cec5SDimitry Andric /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
37520b57cec5SDimitry Andric /// that the expression deposits the low byte of %X into the high byte of the
37530b57cec5SDimitry Andric /// result and that all other bits are zero. This expression is accepted and a
37540b57cec5SDimitry Andric /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
37550b57cec5SDimitry Andric /// [0-7].
37560b57cec5SDimitry Andric ///
3757e8d8bef9SDimitry Andric /// For vector types, all analysis is performed at the per-element level. No
3758e8d8bef9SDimitry Andric /// cross-element analysis is supported (shuffle/insertion/reduction), and all
3759e8d8bef9SDimitry Andric /// constant masks must be splatted across all elements.
3760e8d8bef9SDimitry Andric ///
37610b57cec5SDimitry Andric /// To avoid revisiting values, the BitPart results are memoized into the
37620b57cec5SDimitry Andric /// provided map. To avoid unnecessary copying of BitParts, BitParts are
37630b57cec5SDimitry Andric /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
37640b57cec5SDimitry Andric /// store BitParts objects, not pointers. As we need the concept of a nullptr
37650b57cec5SDimitry Andric /// BitParts (Value has been analyzed and the analysis failed), we an Optional
37660b57cec5SDimitry Andric /// type instead to provide the same functionality.
37670b57cec5SDimitry Andric ///
37680b57cec5SDimitry Andric /// Because we pass around references into \c BPS, we must use a container that
37690b57cec5SDimitry Andric /// does not invalidate internal references (std::map instead of DenseMap).
3770bdd1243dSDimitry Andric static const std::optional<BitPart> &
37710b57cec5SDimitry Andric collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
3772bdd1243dSDimitry Andric                 std::map<Value *, std::optional<BitPart>> &BPS, int Depth,
3773fe6060f1SDimitry Andric                 bool &FoundRoot) {
37740b57cec5SDimitry Andric   auto I = BPS.find(V);
37750b57cec5SDimitry Andric   if (I != BPS.end())
37760b57cec5SDimitry Andric     return I->second;
37770b57cec5SDimitry Andric 
3778bdd1243dSDimitry Andric   auto &Result = BPS[V] = std::nullopt;
3779e8d8bef9SDimitry Andric   auto BitWidth = V->getType()->getScalarSizeInBits();
37800b57cec5SDimitry Andric 
3781fe6060f1SDimitry Andric   // Can't do integer/elements > 128 bits.
3782fe6060f1SDimitry Andric   if (BitWidth > 128)
3783fe6060f1SDimitry Andric     return Result;
3784fe6060f1SDimitry Andric 
37850b57cec5SDimitry Andric   // Prevent stack overflow by limiting the recursion depth
37860b57cec5SDimitry Andric   if (Depth == BitPartRecursionMaxDepth) {
37870b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n");
37880b57cec5SDimitry Andric     return Result;
37890b57cec5SDimitry Andric   }
37900b57cec5SDimitry Andric 
3791e8d8bef9SDimitry Andric   if (auto *I = dyn_cast<Instruction>(V)) {
3792e8d8bef9SDimitry Andric     Value *X, *Y;
3793e8d8bef9SDimitry Andric     const APInt *C;
3794e8d8bef9SDimitry Andric 
37950b57cec5SDimitry Andric     // If this is an or instruction, it may be an inner node of the bswap.
3796e8d8bef9SDimitry Andric     if (match(V, m_Or(m_Value(X), m_Value(Y)))) {
3797fe6060f1SDimitry Andric       // Check we have both sources and they are from the same provider.
3798fe6060f1SDimitry Andric       const auto &A = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3799fe6060f1SDimitry Andric                                       Depth + 1, FoundRoot);
3800fe6060f1SDimitry Andric       if (!A || !A->Provider)
3801fe6060f1SDimitry Andric         return Result;
3802fe6060f1SDimitry Andric 
3803fe6060f1SDimitry Andric       const auto &B = collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS,
3804fe6060f1SDimitry Andric                                       Depth + 1, FoundRoot);
3805fe6060f1SDimitry Andric       if (!B || A->Provider != B->Provider)
38060b57cec5SDimitry Andric         return Result;
38070b57cec5SDimitry Andric 
38080b57cec5SDimitry Andric       // Try and merge the two together.
38090b57cec5SDimitry Andric       Result = BitPart(A->Provider, BitWidth);
3810e8d8bef9SDimitry Andric       for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx) {
3811e8d8bef9SDimitry Andric         if (A->Provenance[BitIdx] != BitPart::Unset &&
3812e8d8bef9SDimitry Andric             B->Provenance[BitIdx] != BitPart::Unset &&
3813e8d8bef9SDimitry Andric             A->Provenance[BitIdx] != B->Provenance[BitIdx])
3814bdd1243dSDimitry Andric           return Result = std::nullopt;
38150b57cec5SDimitry Andric 
3816e8d8bef9SDimitry Andric         if (A->Provenance[BitIdx] == BitPart::Unset)
3817e8d8bef9SDimitry Andric           Result->Provenance[BitIdx] = B->Provenance[BitIdx];
38180b57cec5SDimitry Andric         else
3819e8d8bef9SDimitry Andric           Result->Provenance[BitIdx] = A->Provenance[BitIdx];
38200b57cec5SDimitry Andric       }
38210b57cec5SDimitry Andric 
38220b57cec5SDimitry Andric       return Result;
38230b57cec5SDimitry Andric     }
38240b57cec5SDimitry Andric 
38250b57cec5SDimitry Andric     // If this is a logical shift by a constant, recurse then shift the result.
3826e8d8bef9SDimitry Andric     if (match(V, m_LogicalShift(m_Value(X), m_APInt(C)))) {
3827e8d8bef9SDimitry Andric       const APInt &BitShift = *C;
3828e8d8bef9SDimitry Andric 
38290b57cec5SDimitry Andric       // Ensure the shift amount is defined.
3830e8d8bef9SDimitry Andric       if (BitShift.uge(BitWidth))
38310b57cec5SDimitry Andric         return Result;
38320b57cec5SDimitry Andric 
3833fe6060f1SDimitry Andric       // For bswap-only, limit shift amounts to whole bytes, for an early exit.
3834fe6060f1SDimitry Andric       if (!MatchBitReversals && (BitShift.getZExtValue() % 8) != 0)
3835fe6060f1SDimitry Andric         return Result;
3836fe6060f1SDimitry Andric 
3837fe6060f1SDimitry Andric       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3838fe6060f1SDimitry Andric                                         Depth + 1, FoundRoot);
38390b57cec5SDimitry Andric       if (!Res)
38400b57cec5SDimitry Andric         return Result;
38410b57cec5SDimitry Andric       Result = Res;
38420b57cec5SDimitry Andric 
38430b57cec5SDimitry Andric       // Perform the "shift" on BitProvenance.
38440b57cec5SDimitry Andric       auto &P = Result->Provenance;
38450b57cec5SDimitry Andric       if (I->getOpcode() == Instruction::Shl) {
3846e8d8bef9SDimitry Andric         P.erase(std::prev(P.end(), BitShift.getZExtValue()), P.end());
3847e8d8bef9SDimitry Andric         P.insert(P.begin(), BitShift.getZExtValue(), BitPart::Unset);
38480b57cec5SDimitry Andric       } else {
3849e8d8bef9SDimitry Andric         P.erase(P.begin(), std::next(P.begin(), BitShift.getZExtValue()));
3850e8d8bef9SDimitry Andric         P.insert(P.end(), BitShift.getZExtValue(), BitPart::Unset);
38510b57cec5SDimitry Andric       }
38520b57cec5SDimitry Andric 
38530b57cec5SDimitry Andric       return Result;
38540b57cec5SDimitry Andric     }
38550b57cec5SDimitry Andric 
38560b57cec5SDimitry Andric     // If this is a logical 'and' with a mask that clears bits, recurse then
38570b57cec5SDimitry Andric     // unset the appropriate bits.
3858e8d8bef9SDimitry Andric     if (match(V, m_And(m_Value(X), m_APInt(C)))) {
3859e8d8bef9SDimitry Andric       const APInt &AndMask = *C;
38600b57cec5SDimitry Andric 
38610b57cec5SDimitry Andric       // Check that the mask allows a multiple of 8 bits for a bswap, for an
38620b57cec5SDimitry Andric       // early exit.
386306c3fb27SDimitry Andric       unsigned NumMaskedBits = AndMask.popcount();
3864e8d8bef9SDimitry Andric       if (!MatchBitReversals && (NumMaskedBits % 8) != 0)
38650b57cec5SDimitry Andric         return Result;
38660b57cec5SDimitry Andric 
3867fe6060f1SDimitry Andric       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3868fe6060f1SDimitry Andric                                         Depth + 1, FoundRoot);
38690b57cec5SDimitry Andric       if (!Res)
38700b57cec5SDimitry Andric         return Result;
38710b57cec5SDimitry Andric       Result = Res;
38720b57cec5SDimitry Andric 
3873e8d8bef9SDimitry Andric       for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
38740b57cec5SDimitry Andric         // If the AndMask is zero for this bit, clear the bit.
3875e8d8bef9SDimitry Andric         if (AndMask[BitIdx] == 0)
3876e8d8bef9SDimitry Andric           Result->Provenance[BitIdx] = BitPart::Unset;
38770b57cec5SDimitry Andric       return Result;
38780b57cec5SDimitry Andric     }
38790b57cec5SDimitry Andric 
38800b57cec5SDimitry Andric     // If this is a zext instruction zero extend the result.
3881e8d8bef9SDimitry Andric     if (match(V, m_ZExt(m_Value(X)))) {
3882fe6060f1SDimitry Andric       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3883fe6060f1SDimitry Andric                                         Depth + 1, FoundRoot);
38840b57cec5SDimitry Andric       if (!Res)
38850b57cec5SDimitry Andric         return Result;
38860b57cec5SDimitry Andric 
38870b57cec5SDimitry Andric       Result = BitPart(Res->Provider, BitWidth);
3888e8d8bef9SDimitry Andric       auto NarrowBitWidth = X->getType()->getScalarSizeInBits();
3889e8d8bef9SDimitry Andric       for (unsigned BitIdx = 0; BitIdx < NarrowBitWidth; ++BitIdx)
3890e8d8bef9SDimitry Andric         Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3891e8d8bef9SDimitry Andric       for (unsigned BitIdx = NarrowBitWidth; BitIdx < BitWidth; ++BitIdx)
3892e8d8bef9SDimitry Andric         Result->Provenance[BitIdx] = BitPart::Unset;
3893e8d8bef9SDimitry Andric       return Result;
3894e8d8bef9SDimitry Andric     }
3895e8d8bef9SDimitry Andric 
3896fe6060f1SDimitry Andric     // If this is a truncate instruction, extract the lower bits.
3897fe6060f1SDimitry Andric     if (match(V, m_Trunc(m_Value(X)))) {
3898fe6060f1SDimitry Andric       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3899fe6060f1SDimitry Andric                                         Depth + 1, FoundRoot);
3900fe6060f1SDimitry Andric       if (!Res)
3901fe6060f1SDimitry Andric         return Result;
3902fe6060f1SDimitry Andric 
3903fe6060f1SDimitry Andric       Result = BitPart(Res->Provider, BitWidth);
3904fe6060f1SDimitry Andric       for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3905fe6060f1SDimitry Andric         Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3906fe6060f1SDimitry Andric       return Result;
3907fe6060f1SDimitry Andric     }
3908fe6060f1SDimitry Andric 
3909e8d8bef9SDimitry Andric     // BITREVERSE - most likely due to us previous matching a partial
3910e8d8bef9SDimitry Andric     // bitreverse.
3911e8d8bef9SDimitry Andric     if (match(V, m_BitReverse(m_Value(X)))) {
3912fe6060f1SDimitry Andric       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3913fe6060f1SDimitry Andric                                         Depth + 1, FoundRoot);
3914e8d8bef9SDimitry Andric       if (!Res)
3915e8d8bef9SDimitry Andric         return Result;
3916e8d8bef9SDimitry Andric 
3917e8d8bef9SDimitry Andric       Result = BitPart(Res->Provider, BitWidth);
3918e8d8bef9SDimitry Andric       for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3919e8d8bef9SDimitry Andric         Result->Provenance[(BitWidth - 1) - BitIdx] = Res->Provenance[BitIdx];
3920e8d8bef9SDimitry Andric       return Result;
3921e8d8bef9SDimitry Andric     }
3922e8d8bef9SDimitry Andric 
3923e8d8bef9SDimitry Andric     // BSWAP - most likely due to us previous matching a partial bswap.
3924e8d8bef9SDimitry Andric     if (match(V, m_BSwap(m_Value(X)))) {
3925fe6060f1SDimitry Andric       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3926fe6060f1SDimitry Andric                                         Depth + 1, FoundRoot);
3927e8d8bef9SDimitry Andric       if (!Res)
3928e8d8bef9SDimitry Andric         return Result;
3929e8d8bef9SDimitry Andric 
3930e8d8bef9SDimitry Andric       unsigned ByteWidth = BitWidth / 8;
3931e8d8bef9SDimitry Andric       Result = BitPart(Res->Provider, BitWidth);
3932e8d8bef9SDimitry Andric       for (unsigned ByteIdx = 0; ByteIdx < ByteWidth; ++ByteIdx) {
3933e8d8bef9SDimitry Andric         unsigned ByteBitOfs = ByteIdx * 8;
3934e8d8bef9SDimitry Andric         for (unsigned BitIdx = 0; BitIdx < 8; ++BitIdx)
3935e8d8bef9SDimitry Andric           Result->Provenance[(BitWidth - 8 - ByteBitOfs) + BitIdx] =
3936e8d8bef9SDimitry Andric               Res->Provenance[ByteBitOfs + BitIdx];
3937e8d8bef9SDimitry Andric       }
3938e8d8bef9SDimitry Andric       return Result;
3939e8d8bef9SDimitry Andric     }
3940e8d8bef9SDimitry Andric 
3941e8d8bef9SDimitry Andric     // Funnel 'double' shifts take 3 operands, 2 inputs and the shift
3942e8d8bef9SDimitry Andric     // amount (modulo).
3943e8d8bef9SDimitry Andric     // fshl(X,Y,Z): (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3944e8d8bef9SDimitry Andric     // fshr(X,Y,Z): (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3945e8d8bef9SDimitry Andric     if (match(V, m_FShl(m_Value(X), m_Value(Y), m_APInt(C))) ||
3946e8d8bef9SDimitry Andric         match(V, m_FShr(m_Value(X), m_Value(Y), m_APInt(C)))) {
3947e8d8bef9SDimitry Andric       // We can treat fshr as a fshl by flipping the modulo amount.
3948e8d8bef9SDimitry Andric       unsigned ModAmt = C->urem(BitWidth);
3949e8d8bef9SDimitry Andric       if (cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::fshr)
3950e8d8bef9SDimitry Andric         ModAmt = BitWidth - ModAmt;
3951e8d8bef9SDimitry Andric 
3952fe6060f1SDimitry Andric       // For bswap-only, limit shift amounts to whole bytes, for an early exit.
3953fe6060f1SDimitry Andric       if (!MatchBitReversals && (ModAmt % 8) != 0)
3954fe6060f1SDimitry Andric         return Result;
3955e8d8bef9SDimitry Andric 
3956e8d8bef9SDimitry Andric       // Check we have both sources and they are from the same provider.
3957fe6060f1SDimitry Andric       const auto &LHS = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3958fe6060f1SDimitry Andric                                         Depth + 1, FoundRoot);
3959fe6060f1SDimitry Andric       if (!LHS || !LHS->Provider)
3960fe6060f1SDimitry Andric         return Result;
3961fe6060f1SDimitry Andric 
3962fe6060f1SDimitry Andric       const auto &RHS = collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS,
3963fe6060f1SDimitry Andric                                         Depth + 1, FoundRoot);
3964fe6060f1SDimitry Andric       if (!RHS || LHS->Provider != RHS->Provider)
3965e8d8bef9SDimitry Andric         return Result;
3966e8d8bef9SDimitry Andric 
3967e8d8bef9SDimitry Andric       unsigned StartBitRHS = BitWidth - ModAmt;
3968e8d8bef9SDimitry Andric       Result = BitPart(LHS->Provider, BitWidth);
3969e8d8bef9SDimitry Andric       for (unsigned BitIdx = 0; BitIdx < StartBitRHS; ++BitIdx)
3970e8d8bef9SDimitry Andric         Result->Provenance[BitIdx + ModAmt] = LHS->Provenance[BitIdx];
3971e8d8bef9SDimitry Andric       for (unsigned BitIdx = 0; BitIdx < ModAmt; ++BitIdx)
3972e8d8bef9SDimitry Andric         Result->Provenance[BitIdx] = RHS->Provenance[BitIdx + StartBitRHS];
39730b57cec5SDimitry Andric       return Result;
39740b57cec5SDimitry Andric     }
39750b57cec5SDimitry Andric   }
39760b57cec5SDimitry Andric 
3977fe6060f1SDimitry Andric   // If we've already found a root input value then we're never going to merge
3978fe6060f1SDimitry Andric   // these back together.
3979fe6060f1SDimitry Andric   if (FoundRoot)
3980fe6060f1SDimitry Andric     return Result;
3981fe6060f1SDimitry Andric 
3982fe6060f1SDimitry Andric   // Okay, we got to something that isn't a shift, 'or', 'and', etc. This must
3983fe6060f1SDimitry Andric   // be the root input value to the bswap/bitreverse.
3984fe6060f1SDimitry Andric   FoundRoot = true;
39850b57cec5SDimitry Andric   Result = BitPart(V, BitWidth);
3986e8d8bef9SDimitry Andric   for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3987e8d8bef9SDimitry Andric     Result->Provenance[BitIdx] = BitIdx;
39880b57cec5SDimitry Andric   return Result;
39890b57cec5SDimitry Andric }
39900b57cec5SDimitry Andric 
39910b57cec5SDimitry Andric static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
39920b57cec5SDimitry Andric                                           unsigned BitWidth) {
39930b57cec5SDimitry Andric   if (From % 8 != To % 8)
39940b57cec5SDimitry Andric     return false;
39950b57cec5SDimitry Andric   // Convert from bit indices to byte indices and check for a byte reversal.
39960b57cec5SDimitry Andric   From >>= 3;
39970b57cec5SDimitry Andric   To >>= 3;
39980b57cec5SDimitry Andric   BitWidth >>= 3;
39990b57cec5SDimitry Andric   return From == BitWidth - To - 1;
40000b57cec5SDimitry Andric }
40010b57cec5SDimitry Andric 
40020b57cec5SDimitry Andric static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
40030b57cec5SDimitry Andric                                                unsigned BitWidth) {
40040b57cec5SDimitry Andric   return From == BitWidth - To - 1;
40050b57cec5SDimitry Andric }
40060b57cec5SDimitry Andric 
40070b57cec5SDimitry Andric bool llvm::recognizeBSwapOrBitReverseIdiom(
40080b57cec5SDimitry Andric     Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
40090b57cec5SDimitry Andric     SmallVectorImpl<Instruction *> &InsertedInsts) {
4010fe6060f1SDimitry Andric   if (!match(I, m_Or(m_Value(), m_Value())) &&
4011fe6060f1SDimitry Andric       !match(I, m_FShl(m_Value(), m_Value(), m_Value())) &&
4012297eecfbSDimitry Andric       !match(I, m_FShr(m_Value(), m_Value(), m_Value())) &&
4013297eecfbSDimitry Andric       !match(I, m_BSwap(m_Value())))
40140b57cec5SDimitry Andric     return false;
40150b57cec5SDimitry Andric   if (!MatchBSwaps && !MatchBitReversals)
40160b57cec5SDimitry Andric     return false;
4017e8d8bef9SDimitry Andric   Type *ITy = I->getType();
4018e8d8bef9SDimitry Andric   if (!ITy->isIntOrIntVectorTy() || ITy->getScalarSizeInBits() > 128)
4019e8d8bef9SDimitry Andric     return false;  // Can't do integer/elements > 128 bits.
40200b57cec5SDimitry Andric 
40210b57cec5SDimitry Andric   // Try to find all the pieces corresponding to the bswap.
4022fe6060f1SDimitry Andric   bool FoundRoot = false;
4023bdd1243dSDimitry Andric   std::map<Value *, std::optional<BitPart>> BPS;
4024fe6060f1SDimitry Andric   const auto &Res =
4025fe6060f1SDimitry Andric       collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0, FoundRoot);
40260b57cec5SDimitry Andric   if (!Res)
40270b57cec5SDimitry Andric     return false;
4028e8d8bef9SDimitry Andric   ArrayRef<int8_t> BitProvenance = Res->Provenance;
4029e8d8bef9SDimitry Andric   assert(all_of(BitProvenance,
4030e8d8bef9SDimitry Andric                 [](int8_t I) { return I == BitPart::Unset || 0 <= I; }) &&
4031e8d8bef9SDimitry Andric          "Illegal bit provenance index");
4032e8d8bef9SDimitry Andric 
4033e8d8bef9SDimitry Andric   // If the upper bits are zero, then attempt to perform as a truncated op.
403404eeddc0SDimitry Andric   Type *DemandedTy = ITy;
4035e8d8bef9SDimitry Andric   if (BitProvenance.back() == BitPart::Unset) {
4036e8d8bef9SDimitry Andric     while (!BitProvenance.empty() && BitProvenance.back() == BitPart::Unset)
4037e8d8bef9SDimitry Andric       BitProvenance = BitProvenance.drop_back();
4038e8d8bef9SDimitry Andric     if (BitProvenance.empty())
4039e8d8bef9SDimitry Andric       return false; // TODO - handle null value?
4040e8d8bef9SDimitry Andric     DemandedTy = Type::getIntNTy(I->getContext(), BitProvenance.size());
4041e8d8bef9SDimitry Andric     if (auto *IVecTy = dyn_cast<VectorType>(ITy))
4042e8d8bef9SDimitry Andric       DemandedTy = VectorType::get(DemandedTy, IVecTy);
4043e8d8bef9SDimitry Andric   }
4044e8d8bef9SDimitry Andric 
4045e8d8bef9SDimitry Andric   // Check BitProvenance hasn't found a source larger than the result type.
4046e8d8bef9SDimitry Andric   unsigned DemandedBW = DemandedTy->getScalarSizeInBits();
4047e8d8bef9SDimitry Andric   if (DemandedBW > ITy->getScalarSizeInBits())
4048e8d8bef9SDimitry Andric     return false;
40490b57cec5SDimitry Andric 
40500b57cec5SDimitry Andric   // Now, is the bit permutation correct for a bswap or a bitreverse? We can
40510b57cec5SDimitry Andric   // only byteswap values with an even number of bytes.
4052349cc55cSDimitry Andric   APInt DemandedMask = APInt::getAllOnes(DemandedBW);
4053e8d8bef9SDimitry Andric   bool OKForBSwap = MatchBSwaps && (DemandedBW % 16) == 0;
4054e8d8bef9SDimitry Andric   bool OKForBitReverse = MatchBitReversals;
4055e8d8bef9SDimitry Andric   for (unsigned BitIdx = 0;
4056e8d8bef9SDimitry Andric        (BitIdx < DemandedBW) && (OKForBSwap || OKForBitReverse); ++BitIdx) {
4057e8d8bef9SDimitry Andric     if (BitProvenance[BitIdx] == BitPart::Unset) {
4058e8d8bef9SDimitry Andric       DemandedMask.clearBit(BitIdx);
4059e8d8bef9SDimitry Andric       continue;
4060e8d8bef9SDimitry Andric     }
4061e8d8bef9SDimitry Andric     OKForBSwap &= bitTransformIsCorrectForBSwap(BitProvenance[BitIdx], BitIdx,
4062e8d8bef9SDimitry Andric                                                 DemandedBW);
4063e8d8bef9SDimitry Andric     OKForBitReverse &= bitTransformIsCorrectForBitReverse(BitProvenance[BitIdx],
4064e8d8bef9SDimitry Andric                                                           BitIdx, DemandedBW);
40650b57cec5SDimitry Andric   }
40660b57cec5SDimitry Andric 
40670b57cec5SDimitry Andric   Intrinsic::ID Intrin;
4068e8d8bef9SDimitry Andric   if (OKForBSwap)
40690b57cec5SDimitry Andric     Intrin = Intrinsic::bswap;
4070e8d8bef9SDimitry Andric   else if (OKForBitReverse)
40710b57cec5SDimitry Andric     Intrin = Intrinsic::bitreverse;
40720b57cec5SDimitry Andric   else
40730b57cec5SDimitry Andric     return false;
40740b57cec5SDimitry Andric 
40750b57cec5SDimitry Andric   Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
40760b57cec5SDimitry Andric   Value *Provider = Res->Provider;
4077e8d8bef9SDimitry Andric 
40780b57cec5SDimitry Andric   // We may need to truncate the provider.
4079e8d8bef9SDimitry Andric   if (DemandedTy != Provider->getType()) {
4080e8d8bef9SDimitry Andric     auto *Trunc =
40810fca6ea1SDimitry Andric         CastInst::CreateIntegerCast(Provider, DemandedTy, false, "trunc", I->getIterator());
40820b57cec5SDimitry Andric     InsertedInsts.push_back(Trunc);
40830b57cec5SDimitry Andric     Provider = Trunc;
40840b57cec5SDimitry Andric   }
4085e8d8bef9SDimitry Andric 
40860fca6ea1SDimitry Andric   Instruction *Result = CallInst::Create(F, Provider, "rev", I->getIterator());
4087e8d8bef9SDimitry Andric   InsertedInsts.push_back(Result);
4088e8d8bef9SDimitry Andric 
4089349cc55cSDimitry Andric   if (!DemandedMask.isAllOnes()) {
4090e8d8bef9SDimitry Andric     auto *Mask = ConstantInt::get(DemandedTy, DemandedMask);
40910fca6ea1SDimitry Andric     Result = BinaryOperator::Create(Instruction::And, Result, Mask, "mask", I->getIterator());
4092e8d8bef9SDimitry Andric     InsertedInsts.push_back(Result);
40930b57cec5SDimitry Andric   }
40940b57cec5SDimitry Andric 
4095e8d8bef9SDimitry Andric   // We may need to zeroextend back to the result type.
4096e8d8bef9SDimitry Andric   if (ITy != Result->getType()) {
40970fca6ea1SDimitry Andric     auto *ExtInst = CastInst::CreateIntegerCast(Result, ITy, false, "zext", I->getIterator());
4098e8d8bef9SDimitry Andric     InsertedInsts.push_back(ExtInst);
4099e8d8bef9SDimitry Andric   }
4100e8d8bef9SDimitry Andric 
41010b57cec5SDimitry Andric   return true;
41020b57cec5SDimitry Andric }
41030b57cec5SDimitry Andric 
41040b57cec5SDimitry Andric // CodeGen has special handling for some string functions that may replace
41050b57cec5SDimitry Andric // them with target-specific intrinsics.  Since that'd skip our interceptors
41060b57cec5SDimitry Andric // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
41070b57cec5SDimitry Andric // we mark affected calls as NoBuiltin, which will disable optimization
41080b57cec5SDimitry Andric // in CodeGen.
41090b57cec5SDimitry Andric void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
41100b57cec5SDimitry Andric     CallInst *CI, const TargetLibraryInfo *TLI) {
41110b57cec5SDimitry Andric   Function *F = CI->getCalledFunction();
41120b57cec5SDimitry Andric   LibFunc Func;
41130b57cec5SDimitry Andric   if (F && !F->hasLocalLinkage() && F->hasName() &&
41140b57cec5SDimitry Andric       TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
41150b57cec5SDimitry Andric       !F->doesNotAccessMemory())
4116349cc55cSDimitry Andric     CI->addFnAttr(Attribute::NoBuiltin);
41170b57cec5SDimitry Andric }
41180b57cec5SDimitry Andric 
41190b57cec5SDimitry Andric bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
41200b57cec5SDimitry Andric   // We can't have a PHI with a metadata type.
41210b57cec5SDimitry Andric   if (I->getOperand(OpIdx)->getType()->isMetadataTy())
41220b57cec5SDimitry Andric     return false;
41230b57cec5SDimitry Andric 
41240b57cec5SDimitry Andric   // Early exit.
41250b57cec5SDimitry Andric   if (!isa<Constant>(I->getOperand(OpIdx)))
41260b57cec5SDimitry Andric     return true;
41270b57cec5SDimitry Andric 
41280b57cec5SDimitry Andric   switch (I->getOpcode()) {
41290b57cec5SDimitry Andric   default:
41300b57cec5SDimitry Andric     return true;
41310b57cec5SDimitry Andric   case Instruction::Call:
41325ffd83dbSDimitry Andric   case Instruction::Invoke: {
41335ffd83dbSDimitry Andric     const auto &CB = cast<CallBase>(*I);
41345ffd83dbSDimitry Andric 
41350b57cec5SDimitry Andric     // Can't handle inline asm. Skip it.
41365ffd83dbSDimitry Andric     if (CB.isInlineAsm())
41370b57cec5SDimitry Andric       return false;
41380b57cec5SDimitry Andric 
41390b57cec5SDimitry Andric     // Constant bundle operands may need to retain their constant-ness for
41400b57cec5SDimitry Andric     // correctness.
41415ffd83dbSDimitry Andric     if (CB.isBundleOperand(OpIdx))
41420b57cec5SDimitry Andric       return false;
41435ffd83dbSDimitry Andric 
4144349cc55cSDimitry Andric     if (OpIdx < CB.arg_size()) {
41455ffd83dbSDimitry Andric       // Some variadic intrinsics require constants in the variadic arguments,
41465ffd83dbSDimitry Andric       // which currently aren't markable as immarg.
41475ffd83dbSDimitry Andric       if (isa<IntrinsicInst>(CB) &&
41485ffd83dbSDimitry Andric           OpIdx >= CB.getFunctionType()->getNumParams()) {
41495ffd83dbSDimitry Andric         // This is known to be OK for stackmap.
41505ffd83dbSDimitry Andric         return CB.getIntrinsicID() == Intrinsic::experimental_stackmap;
41515ffd83dbSDimitry Andric       }
41525ffd83dbSDimitry Andric 
41535ffd83dbSDimitry Andric       // gcroot is a special case, since it requires a constant argument which
41545ffd83dbSDimitry Andric       // isn't also required to be a simple ConstantInt.
41555ffd83dbSDimitry Andric       if (CB.getIntrinsicID() == Intrinsic::gcroot)
41565ffd83dbSDimitry Andric         return false;
41575ffd83dbSDimitry Andric 
41585ffd83dbSDimitry Andric       // Some intrinsic operands are required to be immediates.
41595ffd83dbSDimitry Andric       return !CB.paramHasAttr(OpIdx, Attribute::ImmArg);
41605ffd83dbSDimitry Andric     }
41615ffd83dbSDimitry Andric 
41625ffd83dbSDimitry Andric     // It is never allowed to replace the call argument to an intrinsic, but it
41635ffd83dbSDimitry Andric     // may be possible for a call.
41645ffd83dbSDimitry Andric     return !isa<IntrinsicInst>(CB);
41655ffd83dbSDimitry Andric   }
41660b57cec5SDimitry Andric   case Instruction::ShuffleVector:
41670b57cec5SDimitry Andric     // Shufflevector masks are constant.
41680b57cec5SDimitry Andric     return OpIdx != 2;
41690b57cec5SDimitry Andric   case Instruction::Switch:
41700b57cec5SDimitry Andric   case Instruction::ExtractValue:
41710b57cec5SDimitry Andric     // All operands apart from the first are constant.
41720b57cec5SDimitry Andric     return OpIdx == 0;
41730b57cec5SDimitry Andric   case Instruction::InsertValue:
41740b57cec5SDimitry Andric     // All operands apart from the first and the second are constant.
41750b57cec5SDimitry Andric     return OpIdx < 2;
41760b57cec5SDimitry Andric   case Instruction::Alloca:
41770b57cec5SDimitry Andric     // Static allocas (constant size in the entry block) are handled by
41780b57cec5SDimitry Andric     // prologue/epilogue insertion so they're free anyway. We definitely don't
41790b57cec5SDimitry Andric     // want to make them non-constant.
41800b57cec5SDimitry Andric     return !cast<AllocaInst>(I)->isStaticAlloca();
41810b57cec5SDimitry Andric   case Instruction::GetElementPtr:
41820b57cec5SDimitry Andric     if (OpIdx == 0)
41830b57cec5SDimitry Andric       return true;
41840b57cec5SDimitry Andric     gep_type_iterator It = gep_type_begin(I);
41850b57cec5SDimitry Andric     for (auto E = std::next(It, OpIdx); It != E; ++It)
41860b57cec5SDimitry Andric       if (It.isStruct())
41870b57cec5SDimitry Andric         return false;
41880b57cec5SDimitry Andric     return true;
41890b57cec5SDimitry Andric   }
41900b57cec5SDimitry Andric }
41910b57cec5SDimitry Andric 
41925ffd83dbSDimitry Andric Value *llvm::invertCondition(Value *Condition) {
41935ffd83dbSDimitry Andric   // First: Check if it's a constant
41945ffd83dbSDimitry Andric   if (Constant *C = dyn_cast<Constant>(Condition))
41955ffd83dbSDimitry Andric     return ConstantExpr::getNot(C);
41965ffd83dbSDimitry Andric 
41975ffd83dbSDimitry Andric   // Second: If the condition is already inverted, return the original value
41985ffd83dbSDimitry Andric   Value *NotCondition;
41995ffd83dbSDimitry Andric   if (match(Condition, m_Not(m_Value(NotCondition))))
42005ffd83dbSDimitry Andric     return NotCondition;
42015ffd83dbSDimitry Andric 
42025ffd83dbSDimitry Andric   BasicBlock *Parent = nullptr;
42035ffd83dbSDimitry Andric   Instruction *Inst = dyn_cast<Instruction>(Condition);
42045ffd83dbSDimitry Andric   if (Inst)
42055ffd83dbSDimitry Andric     Parent = Inst->getParent();
42065ffd83dbSDimitry Andric   else if (Argument *Arg = dyn_cast<Argument>(Condition))
42075ffd83dbSDimitry Andric     Parent = &Arg->getParent()->getEntryBlock();
42085ffd83dbSDimitry Andric   assert(Parent && "Unsupported condition to invert");
42095ffd83dbSDimitry Andric 
42105ffd83dbSDimitry Andric   // Third: Check all the users for an invert
42115ffd83dbSDimitry Andric   for (User *U : Condition->users())
42125ffd83dbSDimitry Andric     if (Instruction *I = dyn_cast<Instruction>(U))
42135ffd83dbSDimitry Andric       if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
42145ffd83dbSDimitry Andric         return I;
42155ffd83dbSDimitry Andric 
42165ffd83dbSDimitry Andric   // Last option: Create a new instruction
42175ffd83dbSDimitry Andric   auto *Inverted =
42185ffd83dbSDimitry Andric       BinaryOperator::CreateNot(Condition, Condition->getName() + ".inv");
42195ffd83dbSDimitry Andric   if (Inst && !isa<PHINode>(Inst))
42205ffd83dbSDimitry Andric     Inverted->insertAfter(Inst);
42215ffd83dbSDimitry Andric   else
42225ffd83dbSDimitry Andric     Inverted->insertBefore(&*Parent->getFirstInsertionPt());
42235ffd83dbSDimitry Andric   return Inverted;
42245ffd83dbSDimitry Andric }
4225fe6060f1SDimitry Andric 
4226fe6060f1SDimitry Andric bool llvm::inferAttributesFromOthers(Function &F) {
4227fe6060f1SDimitry Andric   // Note: We explicitly check for attributes rather than using cover functions
4228fe6060f1SDimitry Andric   // because some of the cover functions include the logic being implemented.
4229fe6060f1SDimitry Andric 
4230fe6060f1SDimitry Andric   bool Changed = false;
4231fe6060f1SDimitry Andric   // readnone + not convergent implies nosync
4232fe6060f1SDimitry Andric   if (!F.hasFnAttribute(Attribute::NoSync) &&
4233fe6060f1SDimitry Andric       F.doesNotAccessMemory() && !F.isConvergent()) {
4234fe6060f1SDimitry Andric     F.setNoSync();
4235fe6060f1SDimitry Andric     Changed = true;
4236fe6060f1SDimitry Andric   }
4237fe6060f1SDimitry Andric 
4238fe6060f1SDimitry Andric   // readonly implies nofree
4239fe6060f1SDimitry Andric   if (!F.hasFnAttribute(Attribute::NoFree) && F.onlyReadsMemory()) {
4240fe6060f1SDimitry Andric     F.setDoesNotFreeMemory();
4241fe6060f1SDimitry Andric     Changed = true;
4242fe6060f1SDimitry Andric   }
4243fe6060f1SDimitry Andric 
4244fe6060f1SDimitry Andric   // willreturn implies mustprogress
4245fe6060f1SDimitry Andric   if (!F.hasFnAttribute(Attribute::MustProgress) && F.willReturn()) {
4246fe6060f1SDimitry Andric     F.setMustProgress();
4247fe6060f1SDimitry Andric     Changed = true;
4248fe6060f1SDimitry Andric   }
4249fe6060f1SDimitry Andric 
4250fe6060f1SDimitry Andric   // TODO: There are a bunch of cases of restrictive memory effects we
4251fe6060f1SDimitry Andric   // can infer by inspecting arguments of argmemonly-ish functions.
4252fe6060f1SDimitry Andric 
4253fe6060f1SDimitry Andric   return Changed;
4254fe6060f1SDimitry Andric }
4255