xref: /llvm-project/llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp (revision 72b115301d1c0d56f40f5030bb8d16f422ac211b)
1 //===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements the IRTranslator class.
10 //===----------------------------------------------------------------------===//
11 
12 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
13 #include "llvm/ADT/PostOrderIterator.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/ScopeExit.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/AssumptionCache.h"
20 #include "llvm/Analysis/BranchProbabilityInfo.h"
21 #include "llvm/Analysis/Loads.h"
22 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/Analysis/VectorUtils.h"
25 #include "llvm/CodeGen/Analysis.h"
26 #include "llvm/CodeGen/GlobalISel/CSEInfo.h"
27 #include "llvm/CodeGen/GlobalISel/CSEMIRBuilder.h"
28 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
29 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
30 #include "llvm/CodeGen/GlobalISel/InlineAsmLowering.h"
31 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
32 #include "llvm/CodeGen/LowLevelTypeUtils.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/MachineModuleInfo.h"
39 #include "llvm/CodeGen/MachineOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/RuntimeLibcallUtil.h"
42 #include "llvm/CodeGen/StackProtector.h"
43 #include "llvm/CodeGen/SwitchLoweringUtils.h"
44 #include "llvm/CodeGen/TargetFrameLowering.h"
45 #include "llvm/CodeGen/TargetInstrInfo.h"
46 #include "llvm/CodeGen/TargetLowering.h"
47 #include "llvm/CodeGen/TargetOpcodes.h"
48 #include "llvm/CodeGen/TargetPassConfig.h"
49 #include "llvm/CodeGen/TargetRegisterInfo.h"
50 #include "llvm/CodeGen/TargetSubtargetInfo.h"
51 #include "llvm/CodeGenTypes/LowLevelType.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/CFG.h"
54 #include "llvm/IR/Constant.h"
55 #include "llvm/IR/Constants.h"
56 #include "llvm/IR/DataLayout.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/DiagnosticInfo.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/GetElementPtrTypeIterator.h"
61 #include "llvm/IR/InlineAsm.h"
62 #include "llvm/IR/InstrTypes.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/IntrinsicsAMDGPU.h"
67 #include "llvm/IR/LLVMContext.h"
68 #include "llvm/IR/Metadata.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/IR/Statepoint.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/User.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/InitializePasses.h"
75 #include "llvm/MC/MCContext.h"
76 #include "llvm/Pass.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CodeGen.h"
79 #include "llvm/Support/Debug.h"
80 #include "llvm/Support/ErrorHandling.h"
81 #include "llvm/Support/MathExtras.h"
82 #include "llvm/Support/raw_ostream.h"
83 #include "llvm/Target/TargetIntrinsicInfo.h"
84 #include "llvm/Target/TargetMachine.h"
85 #include "llvm/Transforms/Utils/Local.h"
86 #include "llvm/Transforms/Utils/MemoryOpRemark.h"
87 #include <algorithm>
88 #include <cassert>
89 #include <cstdint>
90 #include <iterator>
91 #include <optional>
92 #include <string>
93 #include <utility>
94 #include <vector>
95 
96 #define DEBUG_TYPE "irtranslator"
97 
98 using namespace llvm;
99 
100 static cl::opt<bool>
101     EnableCSEInIRTranslator("enable-cse-in-irtranslator",
102                             cl::desc("Should enable CSE in irtranslator"),
103                             cl::Optional, cl::init(false));
104 char IRTranslator::ID = 0;
105 
106 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
107                 false, false)
108 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
109 INITIALIZE_PASS_DEPENDENCY(GISelCSEAnalysisWrapperPass)
110 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
111 INITIALIZE_PASS_DEPENDENCY(StackProtector)
112 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
113 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
114                 false, false)
115 
116 static void reportTranslationError(MachineFunction &MF,
117                                    const TargetPassConfig &TPC,
118                                    OptimizationRemarkEmitter &ORE,
119                                    OptimizationRemarkMissed &R) {
120   MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
121 
122   // Print the function name explicitly if we don't have a debug location (which
123   // makes the diagnostic less useful) or if we're going to emit a raw error.
124   if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
125     R << (" (in function: " + MF.getName() + ")").str();
126 
127   if (TPC.isGlobalISelAbortEnabled())
128     report_fatal_error(Twine(R.getMsg()));
129   else
130     ORE.emit(R);
131 }
132 
133 IRTranslator::IRTranslator(CodeGenOptLevel optlevel)
134     : MachineFunctionPass(ID), OptLevel(optlevel) {}
135 
136 #ifndef NDEBUG
137 namespace {
138 /// Verify that every instruction created has the same DILocation as the
139 /// instruction being translated.
140 class DILocationVerifier : public GISelChangeObserver {
141   const Instruction *CurrInst = nullptr;
142 
143 public:
144   DILocationVerifier() = default;
145   ~DILocationVerifier() = default;
146 
147   const Instruction *getCurrentInst() const { return CurrInst; }
148   void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; }
149 
150   void erasingInstr(MachineInstr &MI) override {}
151   void changingInstr(MachineInstr &MI) override {}
152   void changedInstr(MachineInstr &MI) override {}
153 
154   void createdInstr(MachineInstr &MI) override {
155     assert(getCurrentInst() && "Inserted instruction without a current MI");
156 
157     // Only print the check message if we're actually checking it.
158 #ifndef NDEBUG
159     LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst
160                       << " was copied to " << MI);
161 #endif
162     // We allow insts in the entry block to have no debug loc because
163     // they could have originated from constants, and we don't want a jumpy
164     // debug experience.
165     assert((CurrInst->getDebugLoc() == MI.getDebugLoc() ||
166             (MI.getParent()->isEntryBlock() && !MI.getDebugLoc()) ||
167             (MI.isDebugInstr())) &&
168            "Line info was not transferred to all instructions");
169   }
170 };
171 } // namespace
172 #endif // ifndef NDEBUG
173 
174 
175 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
176   AU.addRequired<StackProtector>();
177   AU.addRequired<TargetPassConfig>();
178   AU.addRequired<GISelCSEAnalysisWrapperPass>();
179   AU.addRequired<AssumptionCacheTracker>();
180   if (OptLevel != CodeGenOptLevel::None) {
181     AU.addRequired<BranchProbabilityInfoWrapperPass>();
182     AU.addRequired<AAResultsWrapperPass>();
183   }
184   AU.addRequired<TargetLibraryInfoWrapperPass>();
185   AU.addPreserved<TargetLibraryInfoWrapperPass>();
186   getSelectionDAGFallbackAnalysisUsage(AU);
187   MachineFunctionPass::getAnalysisUsage(AU);
188 }
189 
190 IRTranslator::ValueToVRegInfo::VRegListT &
191 IRTranslator::allocateVRegs(const Value &Val) {
192   auto VRegsIt = VMap.findVRegs(Val);
193   if (VRegsIt != VMap.vregs_end())
194     return *VRegsIt->second;
195   auto *Regs = VMap.getVRegs(Val);
196   auto *Offsets = VMap.getOffsets(Val);
197   SmallVector<LLT, 4> SplitTys;
198   computeValueLLTs(*DL, *Val.getType(), SplitTys,
199                    Offsets->empty() ? Offsets : nullptr);
200   for (unsigned i = 0; i < SplitTys.size(); ++i)
201     Regs->push_back(0);
202   return *Regs;
203 }
204 
205 ArrayRef<Register> IRTranslator::getOrCreateVRegs(const Value &Val) {
206   auto VRegsIt = VMap.findVRegs(Val);
207   if (VRegsIt != VMap.vregs_end())
208     return *VRegsIt->second;
209 
210   if (Val.getType()->isVoidTy())
211     return *VMap.getVRegs(Val);
212 
213   // Create entry for this type.
214   auto *VRegs = VMap.getVRegs(Val);
215   auto *Offsets = VMap.getOffsets(Val);
216 
217   if (!Val.getType()->isTokenTy())
218     assert(Val.getType()->isSized() &&
219            "Don't know how to create an empty vreg");
220 
221   SmallVector<LLT, 4> SplitTys;
222   computeValueLLTs(*DL, *Val.getType(), SplitTys,
223                    Offsets->empty() ? Offsets : nullptr);
224 
225   if (!isa<Constant>(Val)) {
226     for (auto Ty : SplitTys)
227       VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
228     return *VRegs;
229   }
230 
231   if (Val.getType()->isAggregateType()) {
232     // UndefValue, ConstantAggregateZero
233     auto &C = cast<Constant>(Val);
234     unsigned Idx = 0;
235     while (auto Elt = C.getAggregateElement(Idx++)) {
236       auto EltRegs = getOrCreateVRegs(*Elt);
237       llvm::copy(EltRegs, std::back_inserter(*VRegs));
238     }
239   } else {
240     assert(SplitTys.size() == 1 && "unexpectedly split LLT");
241     VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
242     bool Success = translate(cast<Constant>(Val), VRegs->front());
243     if (!Success) {
244       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
245                                  MF->getFunction().getSubprogram(),
246                                  &MF->getFunction().getEntryBlock());
247       R << "unable to translate constant: " << ore::NV("Type", Val.getType());
248       reportTranslationError(*MF, *TPC, *ORE, R);
249       return *VRegs;
250     }
251   }
252 
253   return *VRegs;
254 }
255 
256 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
257   auto MapEntry = FrameIndices.find(&AI);
258   if (MapEntry != FrameIndices.end())
259     return MapEntry->second;
260 
261   uint64_t ElementSize = DL->getTypeAllocSize(AI.getAllocatedType());
262   uint64_t Size =
263       ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
264 
265   // Always allocate at least one byte.
266   Size = std::max<uint64_t>(Size, 1u);
267 
268   int &FI = FrameIndices[&AI];
269   FI = MF->getFrameInfo().CreateStackObject(Size, AI.getAlign(), false, &AI);
270   return FI;
271 }
272 
273 Align IRTranslator::getMemOpAlign(const Instruction &I) {
274   if (const StoreInst *SI = dyn_cast<StoreInst>(&I))
275     return SI->getAlign();
276   if (const LoadInst *LI = dyn_cast<LoadInst>(&I))
277     return LI->getAlign();
278   if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I))
279     return AI->getAlign();
280   if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I))
281     return AI->getAlign();
282 
283   OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
284   R << "unable to translate memop: " << ore::NV("Opcode", &I);
285   reportTranslationError(*MF, *TPC, *ORE, R);
286   return Align(1);
287 }
288 
289 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
290   MachineBasicBlock *MBB = FuncInfo.getMBB(&BB);
291   assert(MBB && "BasicBlock was not encountered before");
292   return *MBB;
293 }
294 
295 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
296   assert(NewPred && "new predecessor must be a real MachineBasicBlock");
297   MachinePreds[Edge].push_back(NewPred);
298 }
299 
300 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
301                                      MachineIRBuilder &MIRBuilder) {
302   // Get or create a virtual register for each value.
303   // Unless the value is a Constant => loadimm cst?
304   // or inline constant each time?
305   // Creation of a virtual register needs to have a size.
306   Register Op0 = getOrCreateVReg(*U.getOperand(0));
307   Register Op1 = getOrCreateVReg(*U.getOperand(1));
308   Register Res = getOrCreateVReg(U);
309   uint32_t Flags = 0;
310   if (isa<Instruction>(U)) {
311     const Instruction &I = cast<Instruction>(U);
312     Flags = MachineInstr::copyFlagsFromInstruction(I);
313   }
314 
315   MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags);
316   return true;
317 }
318 
319 bool IRTranslator::translateUnaryOp(unsigned Opcode, const User &U,
320                                     MachineIRBuilder &MIRBuilder) {
321   Register Op0 = getOrCreateVReg(*U.getOperand(0));
322   Register Res = getOrCreateVReg(U);
323   uint32_t Flags = 0;
324   if (isa<Instruction>(U)) {
325     const Instruction &I = cast<Instruction>(U);
326     Flags = MachineInstr::copyFlagsFromInstruction(I);
327   }
328   MIRBuilder.buildInstr(Opcode, {Res}, {Op0}, Flags);
329   return true;
330 }
331 
332 bool IRTranslator::translateFNeg(const User &U, MachineIRBuilder &MIRBuilder) {
333   return translateUnaryOp(TargetOpcode::G_FNEG, U, MIRBuilder);
334 }
335 
336 bool IRTranslator::translateCompare(const User &U,
337                                     MachineIRBuilder &MIRBuilder) {
338   auto *CI = cast<CmpInst>(&U);
339   Register Op0 = getOrCreateVReg(*U.getOperand(0));
340   Register Op1 = getOrCreateVReg(*U.getOperand(1));
341   Register Res = getOrCreateVReg(U);
342   CmpInst::Predicate Pred = CI->getPredicate();
343   uint32_t Flags = MachineInstr::copyFlagsFromInstruction(*CI);
344   if (CmpInst::isIntPredicate(Pred))
345     MIRBuilder.buildICmp(Pred, Res, Op0, Op1, Flags);
346   else if (Pred == CmpInst::FCMP_FALSE)
347     MIRBuilder.buildCopy(
348         Res, getOrCreateVReg(*Constant::getNullValue(U.getType())));
349   else if (Pred == CmpInst::FCMP_TRUE)
350     MIRBuilder.buildCopy(
351         Res, getOrCreateVReg(*Constant::getAllOnesValue(U.getType())));
352   else
353     MIRBuilder.buildFCmp(Pred, Res, Op0, Op1, Flags);
354 
355   return true;
356 }
357 
358 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
359   const ReturnInst &RI = cast<ReturnInst>(U);
360   const Value *Ret = RI.getReturnValue();
361   if (Ret && DL->getTypeStoreSize(Ret->getType()).isZero())
362     Ret = nullptr;
363 
364   ArrayRef<Register> VRegs;
365   if (Ret)
366     VRegs = getOrCreateVRegs(*Ret);
367 
368   Register SwiftErrorVReg = 0;
369   if (CLI->supportSwiftError() && SwiftError.getFunctionArg()) {
370     SwiftErrorVReg = SwiftError.getOrCreateVRegUseAt(
371         &RI, &MIRBuilder.getMBB(), SwiftError.getFunctionArg());
372   }
373 
374   // The target may mess up with the insertion point, but
375   // this is not important as a return is the last instruction
376   // of the block anyway.
377   return CLI->lowerReturn(MIRBuilder, Ret, VRegs, FuncInfo, SwiftErrorVReg);
378 }
379 
380 void IRTranslator::emitBranchForMergedCondition(
381     const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB,
382     MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB,
383     BranchProbability TProb, BranchProbability FProb, bool InvertCond) {
384   // If the leaf of the tree is a comparison, merge the condition into
385   // the caseblock.
386   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
387     CmpInst::Predicate Condition;
388     if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
389       Condition = InvertCond ? IC->getInversePredicate() : IC->getPredicate();
390     } else {
391       const FCmpInst *FC = cast<FCmpInst>(Cond);
392       Condition = InvertCond ? FC->getInversePredicate() : FC->getPredicate();
393     }
394 
395     SwitchCG::CaseBlock CB(Condition, false, BOp->getOperand(0),
396                            BOp->getOperand(1), nullptr, TBB, FBB, CurBB,
397                            CurBuilder->getDebugLoc(), TProb, FProb);
398     SL->SwitchCases.push_back(CB);
399     return;
400   }
401 
402   // Create a CaseBlock record representing this branch.
403   CmpInst::Predicate Pred = InvertCond ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
404   SwitchCG::CaseBlock CB(
405       Pred, false, Cond, ConstantInt::getTrue(MF->getFunction().getContext()),
406       nullptr, TBB, FBB, CurBB, CurBuilder->getDebugLoc(), TProb, FProb);
407   SL->SwitchCases.push_back(CB);
408 }
409 
410 static bool isValInBlock(const Value *V, const BasicBlock *BB) {
411   if (const Instruction *I = dyn_cast<Instruction>(V))
412     return I->getParent() == BB;
413   return true;
414 }
415 
416 void IRTranslator::findMergedConditions(
417     const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB,
418     MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB,
419     Instruction::BinaryOps Opc, BranchProbability TProb,
420     BranchProbability FProb, bool InvertCond) {
421   using namespace PatternMatch;
422   assert((Opc == Instruction::And || Opc == Instruction::Or) &&
423          "Expected Opc to be AND/OR");
424   // Skip over not part of the tree and remember to invert op and operands at
425   // next level.
426   Value *NotCond;
427   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
428       isValInBlock(NotCond, CurBB->getBasicBlock())) {
429     findMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
430                          !InvertCond);
431     return;
432   }
433 
434   const Instruction *BOp = dyn_cast<Instruction>(Cond);
435   const Value *BOpOp0, *BOpOp1;
436   // Compute the effective opcode for Cond, taking into account whether it needs
437   // to be inverted, e.g.
438   //   and (not (or A, B)), C
439   // gets lowered as
440   //   and (and (not A, not B), C)
441   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
442   if (BOp) {
443     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
444                ? Instruction::And
445                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
446                       ? Instruction::Or
447                       : (Instruction::BinaryOps)0);
448     if (InvertCond) {
449       if (BOpc == Instruction::And)
450         BOpc = Instruction::Or;
451       else if (BOpc == Instruction::Or)
452         BOpc = Instruction::And;
453     }
454   }
455 
456   // If this node is not part of the or/and tree, emit it as a branch.
457   // Note that all nodes in the tree should have same opcode.
458   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
459   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
460       !isValInBlock(BOpOp0, CurBB->getBasicBlock()) ||
461       !isValInBlock(BOpOp1, CurBB->getBasicBlock())) {
462     emitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, TProb, FProb,
463                                  InvertCond);
464     return;
465   }
466 
467   //  Create TmpBB after CurBB.
468   MachineFunction::iterator BBI(CurBB);
469   MachineBasicBlock *TmpBB =
470       MF->CreateMachineBasicBlock(CurBB->getBasicBlock());
471   CurBB->getParent()->insert(++BBI, TmpBB);
472 
473   if (Opc == Instruction::Or) {
474     // Codegen X | Y as:
475     // BB1:
476     //   jmp_if_X TBB
477     //   jmp TmpBB
478     // TmpBB:
479     //   jmp_if_Y TBB
480     //   jmp FBB
481     //
482 
483     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
484     // The requirement is that
485     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
486     //     = TrueProb for original BB.
487     // Assuming the original probabilities are A and B, one choice is to set
488     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
489     // A/(1+B) and 2B/(1+B). This choice assumes that
490     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
491     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
492     // TmpBB, but the math is more complicated.
493 
494     auto NewTrueProb = TProb / 2;
495     auto NewFalseProb = TProb / 2 + FProb;
496     // Emit the LHS condition.
497     findMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
498                          NewFalseProb, InvertCond);
499 
500     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
501     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
502     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
503     // Emit the RHS condition into TmpBB.
504     findMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
505                          Probs[1], InvertCond);
506   } else {
507     assert(Opc == Instruction::And && "Unknown merge op!");
508     // Codegen X & Y as:
509     // BB1:
510     //   jmp_if_X TmpBB
511     //   jmp FBB
512     // TmpBB:
513     //   jmp_if_Y TBB
514     //   jmp FBB
515     //
516     //  This requires creation of TmpBB after CurBB.
517 
518     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
519     // The requirement is that
520     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
521     //     = FalseProb for original BB.
522     // Assuming the original probabilities are A and B, one choice is to set
523     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
524     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
525     // TrueProb for BB1 * FalseProb for TmpBB.
526 
527     auto NewTrueProb = TProb + FProb / 2;
528     auto NewFalseProb = FProb / 2;
529     // Emit the LHS condition.
530     findMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
531                          NewFalseProb, InvertCond);
532 
533     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
534     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
535     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
536     // Emit the RHS condition into TmpBB.
537     findMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
538                          Probs[1], InvertCond);
539   }
540 }
541 
542 bool IRTranslator::shouldEmitAsBranches(
543     const std::vector<SwitchCG::CaseBlock> &Cases) {
544   // For multiple cases, it's better to emit as branches.
545   if (Cases.size() != 2)
546     return true;
547 
548   // If this is two comparisons of the same values or'd or and'd together, they
549   // will get folded into a single comparison, so don't emit two blocks.
550   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
551        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
552       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
553        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
554     return false;
555   }
556 
557   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
558   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
559   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
560       Cases[0].PredInfo.Pred == Cases[1].PredInfo.Pred &&
561       isa<Constant>(Cases[0].CmpRHS) &&
562       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
563     if (Cases[0].PredInfo.Pred == CmpInst::ICMP_EQ &&
564         Cases[0].TrueBB == Cases[1].ThisBB)
565       return false;
566     if (Cases[0].PredInfo.Pred == CmpInst::ICMP_NE &&
567         Cases[0].FalseBB == Cases[1].ThisBB)
568       return false;
569   }
570 
571   return true;
572 }
573 
574 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
575   const BranchInst &BrInst = cast<BranchInst>(U);
576   auto &CurMBB = MIRBuilder.getMBB();
577   auto *Succ0MBB = &getMBB(*BrInst.getSuccessor(0));
578 
579   if (BrInst.isUnconditional()) {
580     // If the unconditional target is the layout successor, fallthrough.
581     if (OptLevel == CodeGenOptLevel::None ||
582         !CurMBB.isLayoutSuccessor(Succ0MBB))
583       MIRBuilder.buildBr(*Succ0MBB);
584 
585     // Link successors.
586     for (const BasicBlock *Succ : successors(&BrInst))
587       CurMBB.addSuccessor(&getMBB(*Succ));
588     return true;
589   }
590 
591   // If this condition is one of the special cases we handle, do special stuff
592   // now.
593   const Value *CondVal = BrInst.getCondition();
594   MachineBasicBlock *Succ1MBB = &getMBB(*BrInst.getSuccessor(1));
595 
596   // If this is a series of conditions that are or'd or and'd together, emit
597   // this as a sequence of branches instead of setcc's with and/or operations.
598   // As long as jumps are not expensive (exceptions for multi-use logic ops,
599   // unpredictable branches, and vector extracts because those jumps are likely
600   // expensive for any target), this should improve performance.
601   // For example, instead of something like:
602   //     cmp A, B
603   //     C = seteq
604   //     cmp D, E
605   //     F = setle
606   //     or C, F
607   //     jnz foo
608   // Emit:
609   //     cmp A, B
610   //     je foo
611   //     cmp D, E
612   //     jle foo
613   using namespace PatternMatch;
614   const Instruction *CondI = dyn_cast<Instruction>(CondVal);
615   if (!TLI->isJumpExpensive() && CondI && CondI->hasOneUse() &&
616       !BrInst.hasMetadata(LLVMContext::MD_unpredictable)) {
617     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
618     Value *Vec;
619     const Value *BOp0, *BOp1;
620     if (match(CondI, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
621       Opcode = Instruction::And;
622     else if (match(CondI, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
623       Opcode = Instruction::Or;
624 
625     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
626                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
627       findMergedConditions(CondI, Succ0MBB, Succ1MBB, &CurMBB, &CurMBB, Opcode,
628                            getEdgeProbability(&CurMBB, Succ0MBB),
629                            getEdgeProbability(&CurMBB, Succ1MBB),
630                            /*InvertCond=*/false);
631       assert(SL->SwitchCases[0].ThisBB == &CurMBB && "Unexpected lowering!");
632 
633       // Allow some cases to be rejected.
634       if (shouldEmitAsBranches(SL->SwitchCases)) {
635         // Emit the branch for this block.
636         emitSwitchCase(SL->SwitchCases[0], &CurMBB, *CurBuilder);
637         SL->SwitchCases.erase(SL->SwitchCases.begin());
638         return true;
639       }
640 
641       // Okay, we decided not to do this, remove any inserted MBB's and clear
642       // SwitchCases.
643       for (unsigned I = 1, E = SL->SwitchCases.size(); I != E; ++I)
644         MF->erase(SL->SwitchCases[I].ThisBB);
645 
646       SL->SwitchCases.clear();
647     }
648   }
649 
650   // Create a CaseBlock record representing this branch.
651   SwitchCG::CaseBlock CB(CmpInst::ICMP_EQ, false, CondVal,
652                          ConstantInt::getTrue(MF->getFunction().getContext()),
653                          nullptr, Succ0MBB, Succ1MBB, &CurMBB,
654                          CurBuilder->getDebugLoc());
655 
656   // Use emitSwitchCase to actually insert the fast branch sequence for this
657   // cond branch.
658   emitSwitchCase(CB, &CurMBB, *CurBuilder);
659   return true;
660 }
661 
662 void IRTranslator::addSuccessorWithProb(MachineBasicBlock *Src,
663                                         MachineBasicBlock *Dst,
664                                         BranchProbability Prob) {
665   if (!FuncInfo.BPI) {
666     Src->addSuccessorWithoutProb(Dst);
667     return;
668   }
669   if (Prob.isUnknown())
670     Prob = getEdgeProbability(Src, Dst);
671   Src->addSuccessor(Dst, Prob);
672 }
673 
674 BranchProbability
675 IRTranslator::getEdgeProbability(const MachineBasicBlock *Src,
676                                  const MachineBasicBlock *Dst) const {
677   const BasicBlock *SrcBB = Src->getBasicBlock();
678   const BasicBlock *DstBB = Dst->getBasicBlock();
679   if (!FuncInfo.BPI) {
680     // If BPI is not available, set the default probability as 1 / N, where N is
681     // the number of successors.
682     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
683     return BranchProbability(1, SuccSize);
684   }
685   return FuncInfo.BPI->getEdgeProbability(SrcBB, DstBB);
686 }
687 
688 bool IRTranslator::translateSwitch(const User &U, MachineIRBuilder &MIB) {
689   using namespace SwitchCG;
690   // Extract cases from the switch.
691   const SwitchInst &SI = cast<SwitchInst>(U);
692   BranchProbabilityInfo *BPI = FuncInfo.BPI;
693   CaseClusterVector Clusters;
694   Clusters.reserve(SI.getNumCases());
695   for (const auto &I : SI.cases()) {
696     MachineBasicBlock *Succ = &getMBB(*I.getCaseSuccessor());
697     assert(Succ && "Could not find successor mbb in mapping");
698     const ConstantInt *CaseVal = I.getCaseValue();
699     BranchProbability Prob =
700         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
701             : BranchProbability(1, SI.getNumCases() + 1);
702     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
703   }
704 
705   MachineBasicBlock *DefaultMBB = &getMBB(*SI.getDefaultDest());
706 
707   // Cluster adjacent cases with the same destination. We do this at all
708   // optimization levels because it's cheap to do and will make codegen faster
709   // if there are many clusters.
710   sortAndRangeify(Clusters);
711 
712   MachineBasicBlock *SwitchMBB = &getMBB(*SI.getParent());
713 
714   // If there is only the default destination, jump there directly.
715   if (Clusters.empty()) {
716     SwitchMBB->addSuccessor(DefaultMBB);
717     if (DefaultMBB != SwitchMBB->getNextNode())
718       MIB.buildBr(*DefaultMBB);
719     return true;
720   }
721 
722   SL->findJumpTables(Clusters, &SI, std::nullopt, DefaultMBB, nullptr, nullptr);
723   SL->findBitTestClusters(Clusters, &SI);
724 
725   LLVM_DEBUG({
726     dbgs() << "Case clusters: ";
727     for (const CaseCluster &C : Clusters) {
728       if (C.Kind == CC_JumpTable)
729         dbgs() << "JT:";
730       if (C.Kind == CC_BitTests)
731         dbgs() << "BT:";
732 
733       C.Low->getValue().print(dbgs(), true);
734       if (C.Low != C.High) {
735         dbgs() << '-';
736         C.High->getValue().print(dbgs(), true);
737       }
738       dbgs() << ' ';
739     }
740     dbgs() << '\n';
741   });
742 
743   assert(!Clusters.empty());
744   SwitchWorkList WorkList;
745   CaseClusterIt First = Clusters.begin();
746   CaseClusterIt Last = Clusters.end() - 1;
747   auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
748   WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
749 
750   while (!WorkList.empty()) {
751     SwitchWorkListItem W = WorkList.pop_back_val();
752 
753     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
754     // For optimized builds, lower large range as a balanced binary tree.
755     if (NumClusters > 3 &&
756         MF->getTarget().getOptLevel() != CodeGenOptLevel::None &&
757         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
758       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB, MIB);
759       continue;
760     }
761 
762     if (!lowerSwitchWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB, MIB))
763       return false;
764   }
765   return true;
766 }
767 
768 void IRTranslator::splitWorkItem(SwitchCG::SwitchWorkList &WorkList,
769                                  const SwitchCG::SwitchWorkListItem &W,
770                                  Value *Cond, MachineBasicBlock *SwitchMBB,
771                                  MachineIRBuilder &MIB) {
772   using namespace SwitchCG;
773   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
774          "Clusters not sorted?");
775   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
776 
777   auto [LastLeft, FirstRight, LeftProb, RightProb] =
778       SL->computeSplitWorkItemInfo(W);
779 
780   // Use the first element on the right as pivot since we will make less-than
781   // comparisons against it.
782   CaseClusterIt PivotCluster = FirstRight;
783   assert(PivotCluster > W.FirstCluster);
784   assert(PivotCluster <= W.LastCluster);
785 
786   CaseClusterIt FirstLeft = W.FirstCluster;
787   CaseClusterIt LastRight = W.LastCluster;
788 
789   const ConstantInt *Pivot = PivotCluster->Low;
790 
791   // New blocks will be inserted immediately after the current one.
792   MachineFunction::iterator BBI(W.MBB);
793   ++BBI;
794 
795   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
796   // we can branch to its destination directly if it's squeezed exactly in
797   // between the known lower bound and Pivot - 1.
798   MachineBasicBlock *LeftMBB;
799   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
800       FirstLeft->Low == W.GE &&
801       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
802     LeftMBB = FirstLeft->MBB;
803   } else {
804     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
805     FuncInfo.MF->insert(BBI, LeftMBB);
806     WorkList.push_back(
807         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
808   }
809 
810   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
811   // single cluster, RHS.Low == Pivot, and we can branch to its destination
812   // directly if RHS.High equals the current upper bound.
813   MachineBasicBlock *RightMBB;
814   if (FirstRight == LastRight && FirstRight->Kind == CC_Range && W.LT &&
815       (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
816     RightMBB = FirstRight->MBB;
817   } else {
818     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
819     FuncInfo.MF->insert(BBI, RightMBB);
820     WorkList.push_back(
821         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
822   }
823 
824   // Create the CaseBlock record that will be used to lower the branch.
825   CaseBlock CB(ICmpInst::Predicate::ICMP_SLT, false, Cond, Pivot, nullptr,
826                LeftMBB, RightMBB, W.MBB, MIB.getDebugLoc(), LeftProb,
827                RightProb);
828 
829   if (W.MBB == SwitchMBB)
830     emitSwitchCase(CB, SwitchMBB, MIB);
831   else
832     SL->SwitchCases.push_back(CB);
833 }
834 
835 void IRTranslator::emitJumpTable(SwitchCG::JumpTable &JT,
836                                  MachineBasicBlock *MBB) {
837   // Emit the code for the jump table
838   assert(JT.Reg && "Should lower JT Header first!");
839   MachineIRBuilder MIB(*MBB->getParent());
840   MIB.setMBB(*MBB);
841   MIB.setDebugLoc(CurBuilder->getDebugLoc());
842 
843   Type *PtrIRTy = PointerType::getUnqual(MF->getFunction().getContext());
844   const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
845 
846   auto Table = MIB.buildJumpTable(PtrTy, JT.JTI);
847   MIB.buildBrJT(Table.getReg(0), JT.JTI, JT.Reg);
848 }
849 
850 bool IRTranslator::emitJumpTableHeader(SwitchCG::JumpTable &JT,
851                                        SwitchCG::JumpTableHeader &JTH,
852                                        MachineBasicBlock *HeaderBB) {
853   MachineIRBuilder MIB(*HeaderBB->getParent());
854   MIB.setMBB(*HeaderBB);
855   MIB.setDebugLoc(CurBuilder->getDebugLoc());
856 
857   const Value &SValue = *JTH.SValue;
858   // Subtract the lowest switch case value from the value being switched on.
859   const LLT SwitchTy = getLLTForType(*SValue.getType(), *DL);
860   Register SwitchOpReg = getOrCreateVReg(SValue);
861   auto FirstCst = MIB.buildConstant(SwitchTy, JTH.First);
862   auto Sub = MIB.buildSub({SwitchTy}, SwitchOpReg, FirstCst);
863 
864   // This value may be smaller or larger than the target's pointer type, and
865   // therefore require extension or truncating.
866   auto *PtrIRTy = PointerType::getUnqual(SValue.getContext());
867   const LLT PtrScalarTy = LLT::scalar(DL->getTypeSizeInBits(PtrIRTy));
868   Sub = MIB.buildZExtOrTrunc(PtrScalarTy, Sub);
869 
870   JT.Reg = Sub.getReg(0);
871 
872   if (JTH.FallthroughUnreachable) {
873     if (JT.MBB != HeaderBB->getNextNode())
874       MIB.buildBr(*JT.MBB);
875     return true;
876   }
877 
878   // Emit the range check for the jump table, and branch to the default block
879   // for the switch statement if the value being switched on exceeds the
880   // largest case in the switch.
881   auto Cst = getOrCreateVReg(
882       *ConstantInt::get(SValue.getType(), JTH.Last - JTH.First));
883   Cst = MIB.buildZExtOrTrunc(PtrScalarTy, Cst).getReg(0);
884   auto Cmp = MIB.buildICmp(CmpInst::ICMP_UGT, LLT::scalar(1), Sub, Cst);
885 
886   auto BrCond = MIB.buildBrCond(Cmp.getReg(0), *JT.Default);
887 
888   // Avoid emitting unnecessary branches to the next block.
889   if (JT.MBB != HeaderBB->getNextNode())
890     BrCond = MIB.buildBr(*JT.MBB);
891   return true;
892 }
893 
894 void IRTranslator::emitSwitchCase(SwitchCG::CaseBlock &CB,
895                                   MachineBasicBlock *SwitchBB,
896                                   MachineIRBuilder &MIB) {
897   Register CondLHS = getOrCreateVReg(*CB.CmpLHS);
898   Register Cond;
899   DebugLoc OldDbgLoc = MIB.getDebugLoc();
900   MIB.setDebugLoc(CB.DbgLoc);
901   MIB.setMBB(*CB.ThisBB);
902 
903   if (CB.PredInfo.NoCmp) {
904     // Branch or fall through to TrueBB.
905     addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
906     addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
907                       CB.ThisBB);
908     CB.ThisBB->normalizeSuccProbs();
909     if (CB.TrueBB != CB.ThisBB->getNextNode())
910       MIB.buildBr(*CB.TrueBB);
911     MIB.setDebugLoc(OldDbgLoc);
912     return;
913   }
914 
915   const LLT i1Ty = LLT::scalar(1);
916   // Build the compare.
917   if (!CB.CmpMHS) {
918     const auto *CI = dyn_cast<ConstantInt>(CB.CmpRHS);
919     // For conditional branch lowering, we might try to do something silly like
920     // emit an G_ICMP to compare an existing G_ICMP i1 result with true. If so,
921     // just re-use the existing condition vreg.
922     if (MRI->getType(CondLHS).getSizeInBits() == 1 && CI && CI->isOne() &&
923         CB.PredInfo.Pred == CmpInst::ICMP_EQ) {
924       Cond = CondLHS;
925     } else {
926       Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
927       if (CmpInst::isFPPredicate(CB.PredInfo.Pred))
928         Cond =
929             MIB.buildFCmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0);
930       else
931         Cond =
932             MIB.buildICmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0);
933     }
934   } else {
935     assert(CB.PredInfo.Pred == CmpInst::ICMP_SLE &&
936            "Can only handle SLE ranges");
937 
938     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
939     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
940 
941     Register CmpOpReg = getOrCreateVReg(*CB.CmpMHS);
942     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
943       Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
944       Cond =
945           MIB.buildICmp(CmpInst::ICMP_SLE, i1Ty, CmpOpReg, CondRHS).getReg(0);
946     } else {
947       const LLT CmpTy = MRI->getType(CmpOpReg);
948       auto Sub = MIB.buildSub({CmpTy}, CmpOpReg, CondLHS);
949       auto Diff = MIB.buildConstant(CmpTy, High - Low);
950       Cond = MIB.buildICmp(CmpInst::ICMP_ULE, i1Ty, Sub, Diff).getReg(0);
951     }
952   }
953 
954   // Update successor info
955   addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
956 
957   addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
958                     CB.ThisBB);
959 
960   // TrueBB and FalseBB are always different unless the incoming IR is
961   // degenerate. This only happens when running llc on weird IR.
962   if (CB.TrueBB != CB.FalseBB)
963     addSuccessorWithProb(CB.ThisBB, CB.FalseBB, CB.FalseProb);
964   CB.ThisBB->normalizeSuccProbs();
965 
966   addMachineCFGPred({SwitchBB->getBasicBlock(), CB.FalseBB->getBasicBlock()},
967                     CB.ThisBB);
968 
969   MIB.buildBrCond(Cond, *CB.TrueBB);
970   MIB.buildBr(*CB.FalseBB);
971   MIB.setDebugLoc(OldDbgLoc);
972 }
973 
974 bool IRTranslator::lowerJumpTableWorkItem(SwitchCG::SwitchWorkListItem W,
975                                           MachineBasicBlock *SwitchMBB,
976                                           MachineBasicBlock *CurMBB,
977                                           MachineBasicBlock *DefaultMBB,
978                                           MachineIRBuilder &MIB,
979                                           MachineFunction::iterator BBI,
980                                           BranchProbability UnhandledProbs,
981                                           SwitchCG::CaseClusterIt I,
982                                           MachineBasicBlock *Fallthrough,
983                                           bool FallthroughUnreachable) {
984   using namespace SwitchCG;
985   MachineFunction *CurMF = SwitchMBB->getParent();
986   // FIXME: Optimize away range check based on pivot comparisons.
987   JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
988   SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
989   BranchProbability DefaultProb = W.DefaultProb;
990 
991   // The jump block hasn't been inserted yet; insert it here.
992   MachineBasicBlock *JumpMBB = JT->MBB;
993   CurMF->insert(BBI, JumpMBB);
994 
995   // Since the jump table block is separate from the switch block, we need
996   // to keep track of it as a machine predecessor to the default block,
997   // otherwise we lose the phi edges.
998   addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
999                     CurMBB);
1000   addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
1001                     JumpMBB);
1002 
1003   auto JumpProb = I->Prob;
1004   auto FallthroughProb = UnhandledProbs;
1005 
1006   // If the default statement is a target of the jump table, we evenly
1007   // distribute the default probability to successors of CurMBB. Also
1008   // update the probability on the edge from JumpMBB to Fallthrough.
1009   for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
1010                                         SE = JumpMBB->succ_end();
1011        SI != SE; ++SI) {
1012     if (*SI == DefaultMBB) {
1013       JumpProb += DefaultProb / 2;
1014       FallthroughProb -= DefaultProb / 2;
1015       JumpMBB->setSuccProbability(SI, DefaultProb / 2);
1016       JumpMBB->normalizeSuccProbs();
1017     } else {
1018       // Also record edges from the jump table block to it's successors.
1019       addMachineCFGPred({SwitchMBB->getBasicBlock(), (*SI)->getBasicBlock()},
1020                         JumpMBB);
1021     }
1022   }
1023 
1024   if (FallthroughUnreachable)
1025     JTH->FallthroughUnreachable = true;
1026 
1027   if (!JTH->FallthroughUnreachable)
1028     addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
1029   addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
1030   CurMBB->normalizeSuccProbs();
1031 
1032   // The jump table header will be inserted in our current block, do the
1033   // range check, and fall through to our fallthrough block.
1034   JTH->HeaderBB = CurMBB;
1035   JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
1036 
1037   // If we're in the right place, emit the jump table header right now.
1038   if (CurMBB == SwitchMBB) {
1039     if (!emitJumpTableHeader(*JT, *JTH, CurMBB))
1040       return false;
1041     JTH->Emitted = true;
1042   }
1043   return true;
1044 }
1045 bool IRTranslator::lowerSwitchRangeWorkItem(SwitchCG::CaseClusterIt I,
1046                                             Value *Cond,
1047                                             MachineBasicBlock *Fallthrough,
1048                                             bool FallthroughUnreachable,
1049                                             BranchProbability UnhandledProbs,
1050                                             MachineBasicBlock *CurMBB,
1051                                             MachineIRBuilder &MIB,
1052                                             MachineBasicBlock *SwitchMBB) {
1053   using namespace SwitchCG;
1054   const Value *RHS, *LHS, *MHS;
1055   CmpInst::Predicate Pred;
1056   if (I->Low == I->High) {
1057     // Check Cond == I->Low.
1058     Pred = CmpInst::ICMP_EQ;
1059     LHS = Cond;
1060     RHS = I->Low;
1061     MHS = nullptr;
1062   } else {
1063     // Check I->Low <= Cond <= I->High.
1064     Pred = CmpInst::ICMP_SLE;
1065     LHS = I->Low;
1066     MHS = Cond;
1067     RHS = I->High;
1068   }
1069 
1070   // If Fallthrough is unreachable, fold away the comparison.
1071   // The false probability is the sum of all unhandled cases.
1072   CaseBlock CB(Pred, FallthroughUnreachable, LHS, RHS, MHS, I->MBB, Fallthrough,
1073                CurMBB, MIB.getDebugLoc(), I->Prob, UnhandledProbs);
1074 
1075   emitSwitchCase(CB, SwitchMBB, MIB);
1076   return true;
1077 }
1078 
1079 void IRTranslator::emitBitTestHeader(SwitchCG::BitTestBlock &B,
1080                                      MachineBasicBlock *SwitchBB) {
1081   MachineIRBuilder &MIB = *CurBuilder;
1082   MIB.setMBB(*SwitchBB);
1083 
1084   // Subtract the minimum value.
1085   Register SwitchOpReg = getOrCreateVReg(*B.SValue);
1086 
1087   LLT SwitchOpTy = MRI->getType(SwitchOpReg);
1088   Register MinValReg = MIB.buildConstant(SwitchOpTy, B.First).getReg(0);
1089   auto RangeSub = MIB.buildSub(SwitchOpTy, SwitchOpReg, MinValReg);
1090 
1091   Type *PtrIRTy = PointerType::getUnqual(MF->getFunction().getContext());
1092   const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
1093 
1094   LLT MaskTy = SwitchOpTy;
1095   if (MaskTy.getSizeInBits() > PtrTy.getSizeInBits() ||
1096       !llvm::has_single_bit<uint32_t>(MaskTy.getSizeInBits()))
1097     MaskTy = LLT::scalar(PtrTy.getSizeInBits());
1098   else {
1099     // Ensure that the type will fit the mask value.
1100     for (unsigned I = 0, E = B.Cases.size(); I != E; ++I) {
1101       if (!isUIntN(SwitchOpTy.getSizeInBits(), B.Cases[I].Mask)) {
1102         // Switch table case range are encoded into series of masks.
1103         // Just use pointer type, it's guaranteed to fit.
1104         MaskTy = LLT::scalar(PtrTy.getSizeInBits());
1105         break;
1106       }
1107     }
1108   }
1109   Register SubReg = RangeSub.getReg(0);
1110   if (SwitchOpTy != MaskTy)
1111     SubReg = MIB.buildZExtOrTrunc(MaskTy, SubReg).getReg(0);
1112 
1113   B.RegVT = getMVTForLLT(MaskTy);
1114   B.Reg = SubReg;
1115 
1116   MachineBasicBlock *MBB = B.Cases[0].ThisBB;
1117 
1118   if (!B.FallthroughUnreachable)
1119     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
1120   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
1121 
1122   SwitchBB->normalizeSuccProbs();
1123 
1124   if (!B.FallthroughUnreachable) {
1125     // Conditional branch to the default block.
1126     auto RangeCst = MIB.buildConstant(SwitchOpTy, B.Range);
1127     auto RangeCmp = MIB.buildICmp(CmpInst::Predicate::ICMP_UGT, LLT::scalar(1),
1128                                   RangeSub, RangeCst);
1129     MIB.buildBrCond(RangeCmp, *B.Default);
1130   }
1131 
1132   // Avoid emitting unnecessary branches to the next block.
1133   if (MBB != SwitchBB->getNextNode())
1134     MIB.buildBr(*MBB);
1135 }
1136 
1137 void IRTranslator::emitBitTestCase(SwitchCG::BitTestBlock &BB,
1138                                    MachineBasicBlock *NextMBB,
1139                                    BranchProbability BranchProbToNext,
1140                                    Register Reg, SwitchCG::BitTestCase &B,
1141                                    MachineBasicBlock *SwitchBB) {
1142   MachineIRBuilder &MIB = *CurBuilder;
1143   MIB.setMBB(*SwitchBB);
1144 
1145   LLT SwitchTy = getLLTForMVT(BB.RegVT);
1146   Register Cmp;
1147   unsigned PopCount = llvm::popcount(B.Mask);
1148   if (PopCount == 1) {
1149     // Testing for a single bit; just compare the shift count with what it
1150     // would need to be to shift a 1 bit in that position.
1151     auto MaskTrailingZeros =
1152         MIB.buildConstant(SwitchTy, llvm::countr_zero(B.Mask));
1153     Cmp =
1154         MIB.buildICmp(ICmpInst::ICMP_EQ, LLT::scalar(1), Reg, MaskTrailingZeros)
1155             .getReg(0);
1156   } else if (PopCount == BB.Range) {
1157     // There is only one zero bit in the range, test for it directly.
1158     auto MaskTrailingOnes =
1159         MIB.buildConstant(SwitchTy, llvm::countr_one(B.Mask));
1160     Cmp = MIB.buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), Reg, MaskTrailingOnes)
1161               .getReg(0);
1162   } else {
1163     // Make desired shift.
1164     auto CstOne = MIB.buildConstant(SwitchTy, 1);
1165     auto SwitchVal = MIB.buildShl(SwitchTy, CstOne, Reg);
1166 
1167     // Emit bit tests and jumps.
1168     auto CstMask = MIB.buildConstant(SwitchTy, B.Mask);
1169     auto AndOp = MIB.buildAnd(SwitchTy, SwitchVal, CstMask);
1170     auto CstZero = MIB.buildConstant(SwitchTy, 0);
1171     Cmp = MIB.buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), AndOp, CstZero)
1172               .getReg(0);
1173   }
1174 
1175   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
1176   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
1177   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
1178   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
1179   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
1180   // one as they are relative probabilities (and thus work more like weights),
1181   // and hence we need to normalize them to let the sum of them become one.
1182   SwitchBB->normalizeSuccProbs();
1183 
1184   // Record the fact that the IR edge from the header to the bit test target
1185   // will go through our new block. Neeeded for PHIs to have nodes added.
1186   addMachineCFGPred({BB.Parent->getBasicBlock(), B.TargetBB->getBasicBlock()},
1187                     SwitchBB);
1188 
1189   MIB.buildBrCond(Cmp, *B.TargetBB);
1190 
1191   // Avoid emitting unnecessary branches to the next block.
1192   if (NextMBB != SwitchBB->getNextNode())
1193     MIB.buildBr(*NextMBB);
1194 }
1195 
1196 bool IRTranslator::lowerBitTestWorkItem(
1197     SwitchCG::SwitchWorkListItem W, MachineBasicBlock *SwitchMBB,
1198     MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB,
1199     MachineIRBuilder &MIB, MachineFunction::iterator BBI,
1200     BranchProbability DefaultProb, BranchProbability UnhandledProbs,
1201     SwitchCG::CaseClusterIt I, MachineBasicBlock *Fallthrough,
1202     bool FallthroughUnreachable) {
1203   using namespace SwitchCG;
1204   MachineFunction *CurMF = SwitchMBB->getParent();
1205   // FIXME: Optimize away range check based on pivot comparisons.
1206   BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
1207   // The bit test blocks haven't been inserted yet; insert them here.
1208   for (BitTestCase &BTC : BTB->Cases)
1209     CurMF->insert(BBI, BTC.ThisBB);
1210 
1211   // Fill in fields of the BitTestBlock.
1212   BTB->Parent = CurMBB;
1213   BTB->Default = Fallthrough;
1214 
1215   BTB->DefaultProb = UnhandledProbs;
1216   // If the cases in bit test don't form a contiguous range, we evenly
1217   // distribute the probability on the edge to Fallthrough to two
1218   // successors of CurMBB.
1219   if (!BTB->ContiguousRange) {
1220     BTB->Prob += DefaultProb / 2;
1221     BTB->DefaultProb -= DefaultProb / 2;
1222   }
1223 
1224   if (FallthroughUnreachable)
1225     BTB->FallthroughUnreachable = true;
1226 
1227   // If we're in the right place, emit the bit test header right now.
1228   if (CurMBB == SwitchMBB) {
1229     emitBitTestHeader(*BTB, SwitchMBB);
1230     BTB->Emitted = true;
1231   }
1232   return true;
1233 }
1234 
1235 bool IRTranslator::lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W,
1236                                        Value *Cond,
1237                                        MachineBasicBlock *SwitchMBB,
1238                                        MachineBasicBlock *DefaultMBB,
1239                                        MachineIRBuilder &MIB) {
1240   using namespace SwitchCG;
1241   MachineFunction *CurMF = FuncInfo.MF;
1242   MachineBasicBlock *NextMBB = nullptr;
1243   MachineFunction::iterator BBI(W.MBB);
1244   if (++BBI != FuncInfo.MF->end())
1245     NextMBB = &*BBI;
1246 
1247   if (EnableOpts) {
1248     // Here, we order cases by probability so the most likely case will be
1249     // checked first. However, two clusters can have the same probability in
1250     // which case their relative ordering is non-deterministic. So we use Low
1251     // as a tie-breaker as clusters are guaranteed to never overlap.
1252     llvm::sort(W.FirstCluster, W.LastCluster + 1,
1253                [](const CaseCluster &a, const CaseCluster &b) {
1254                  return a.Prob != b.Prob
1255                             ? a.Prob > b.Prob
1256                             : a.Low->getValue().slt(b.Low->getValue());
1257                });
1258 
1259     // Rearrange the case blocks so that the last one falls through if possible
1260     // without changing the order of probabilities.
1261     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster;) {
1262       --I;
1263       if (I->Prob > W.LastCluster->Prob)
1264         break;
1265       if (I->Kind == CC_Range && I->MBB == NextMBB) {
1266         std::swap(*I, *W.LastCluster);
1267         break;
1268       }
1269     }
1270   }
1271 
1272   // Compute total probability.
1273   BranchProbability DefaultProb = W.DefaultProb;
1274   BranchProbability UnhandledProbs = DefaultProb;
1275   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
1276     UnhandledProbs += I->Prob;
1277 
1278   MachineBasicBlock *CurMBB = W.MBB;
1279   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
1280     bool FallthroughUnreachable = false;
1281     MachineBasicBlock *Fallthrough;
1282     if (I == W.LastCluster) {
1283       // For the last cluster, fall through to the default destination.
1284       Fallthrough = DefaultMBB;
1285       FallthroughUnreachable = isa<UnreachableInst>(
1286           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
1287     } else {
1288       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
1289       CurMF->insert(BBI, Fallthrough);
1290     }
1291     UnhandledProbs -= I->Prob;
1292 
1293     switch (I->Kind) {
1294     case CC_BitTests: {
1295       if (!lowerBitTestWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
1296                                 DefaultProb, UnhandledProbs, I, Fallthrough,
1297                                 FallthroughUnreachable)) {
1298         LLVM_DEBUG(dbgs() << "Failed to lower bit test for switch");
1299         return false;
1300       }
1301       break;
1302     }
1303 
1304     case CC_JumpTable: {
1305       if (!lowerJumpTableWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
1306                                   UnhandledProbs, I, Fallthrough,
1307                                   FallthroughUnreachable)) {
1308         LLVM_DEBUG(dbgs() << "Failed to lower jump table");
1309         return false;
1310       }
1311       break;
1312     }
1313     case CC_Range: {
1314       if (!lowerSwitchRangeWorkItem(I, Cond, Fallthrough,
1315                                     FallthroughUnreachable, UnhandledProbs,
1316                                     CurMBB, MIB, SwitchMBB)) {
1317         LLVM_DEBUG(dbgs() << "Failed to lower switch range");
1318         return false;
1319       }
1320       break;
1321     }
1322     }
1323     CurMBB = Fallthrough;
1324   }
1325 
1326   return true;
1327 }
1328 
1329 bool IRTranslator::translateIndirectBr(const User &U,
1330                                        MachineIRBuilder &MIRBuilder) {
1331   const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
1332 
1333   const Register Tgt = getOrCreateVReg(*BrInst.getAddress());
1334   MIRBuilder.buildBrIndirect(Tgt);
1335 
1336   // Link successors.
1337   SmallPtrSet<const BasicBlock *, 32> AddedSuccessors;
1338   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
1339   for (const BasicBlock *Succ : successors(&BrInst)) {
1340     // It's legal for indirectbr instructions to have duplicate blocks in the
1341     // destination list. We don't allow this in MIR. Skip anything that's
1342     // already a successor.
1343     if (!AddedSuccessors.insert(Succ).second)
1344       continue;
1345     CurBB.addSuccessor(&getMBB(*Succ));
1346   }
1347 
1348   return true;
1349 }
1350 
1351 static bool isSwiftError(const Value *V) {
1352   if (auto Arg = dyn_cast<Argument>(V))
1353     return Arg->hasSwiftErrorAttr();
1354   if (auto AI = dyn_cast<AllocaInst>(V))
1355     return AI->isSwiftError();
1356   return false;
1357 }
1358 
1359 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
1360   const LoadInst &LI = cast<LoadInst>(U);
1361   TypeSize StoreSize = DL->getTypeStoreSize(LI.getType());
1362   if (StoreSize.isZero())
1363     return true;
1364 
1365   ArrayRef<Register> Regs = getOrCreateVRegs(LI);
1366   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
1367   Register Base = getOrCreateVReg(*LI.getPointerOperand());
1368   AAMDNodes AAInfo = LI.getAAMetadata();
1369 
1370   const Value *Ptr = LI.getPointerOperand();
1371   Type *OffsetIRTy = DL->getIndexType(Ptr->getType());
1372   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1373 
1374   if (CLI->supportSwiftError() && isSwiftError(Ptr)) {
1375     assert(Regs.size() == 1 && "swifterror should be single pointer");
1376     Register VReg =
1377         SwiftError.getOrCreateVRegUseAt(&LI, &MIRBuilder.getMBB(), Ptr);
1378     MIRBuilder.buildCopy(Regs[0], VReg);
1379     return true;
1380   }
1381 
1382   MachineMemOperand::Flags Flags =
1383       TLI->getLoadMemOperandFlags(LI, *DL, AC, LibInfo);
1384   if (AA && !(Flags & MachineMemOperand::MOInvariant)) {
1385     if (AA->pointsToConstantMemory(
1386             MemoryLocation(Ptr, LocationSize::precise(StoreSize), AAInfo))) {
1387       Flags |= MachineMemOperand::MOInvariant;
1388     }
1389   }
1390 
1391   const MDNode *Ranges =
1392       Regs.size() == 1 ? LI.getMetadata(LLVMContext::MD_range) : nullptr;
1393   for (unsigned i = 0; i < Regs.size(); ++i) {
1394     Register Addr;
1395     MIRBuilder.materializePtrAdd(Addr, Base, OffsetTy, Offsets[i] / 8);
1396 
1397     MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
1398     Align BaseAlign = getMemOpAlign(LI);
1399     auto MMO = MF->getMachineMemOperand(
1400         Ptr, Flags, MRI->getType(Regs[i]),
1401         commonAlignment(BaseAlign, Offsets[i] / 8), AAInfo, Ranges,
1402         LI.getSyncScopeID(), LI.getOrdering());
1403     MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
1404   }
1405 
1406   return true;
1407 }
1408 
1409 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
1410   const StoreInst &SI = cast<StoreInst>(U);
1411   if (DL->getTypeStoreSize(SI.getValueOperand()->getType()).isZero())
1412     return true;
1413 
1414   ArrayRef<Register> Vals = getOrCreateVRegs(*SI.getValueOperand());
1415   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
1416   Register Base = getOrCreateVReg(*SI.getPointerOperand());
1417 
1418   Type *OffsetIRTy = DL->getIndexType(SI.getPointerOperandType());
1419   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1420 
1421   if (CLI->supportSwiftError() && isSwiftError(SI.getPointerOperand())) {
1422     assert(Vals.size() == 1 && "swifterror should be single pointer");
1423 
1424     Register VReg = SwiftError.getOrCreateVRegDefAt(&SI, &MIRBuilder.getMBB(),
1425                                                     SI.getPointerOperand());
1426     MIRBuilder.buildCopy(VReg, Vals[0]);
1427     return true;
1428   }
1429 
1430   MachineMemOperand::Flags Flags = TLI->getStoreMemOperandFlags(SI, *DL);
1431 
1432   for (unsigned i = 0; i < Vals.size(); ++i) {
1433     Register Addr;
1434     MIRBuilder.materializePtrAdd(Addr, Base, OffsetTy, Offsets[i] / 8);
1435 
1436     MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
1437     Align BaseAlign = getMemOpAlign(SI);
1438     auto MMO = MF->getMachineMemOperand(
1439         Ptr, Flags, MRI->getType(Vals[i]),
1440         commonAlignment(BaseAlign, Offsets[i] / 8), SI.getAAMetadata(), nullptr,
1441         SI.getSyncScopeID(), SI.getOrdering());
1442     MIRBuilder.buildStore(Vals[i], Addr, *MMO);
1443   }
1444   return true;
1445 }
1446 
1447 static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
1448   const Value *Src = U.getOperand(0);
1449   Type *Int32Ty = Type::getInt32Ty(U.getContext());
1450 
1451   // getIndexedOffsetInType is designed for GEPs, so the first index is the
1452   // usual array element rather than looking into the actual aggregate.
1453   SmallVector<Value *, 1> Indices;
1454   Indices.push_back(ConstantInt::get(Int32Ty, 0));
1455 
1456   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
1457     for (auto Idx : EVI->indices())
1458       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
1459   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
1460     for (auto Idx : IVI->indices())
1461       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
1462   } else {
1463     for (Value *Op : drop_begin(U.operands()))
1464       Indices.push_back(Op);
1465   }
1466 
1467   return 8 * static_cast<uint64_t>(
1468                  DL.getIndexedOffsetInType(Src->getType(), Indices));
1469 }
1470 
1471 bool IRTranslator::translateExtractValue(const User &U,
1472                                          MachineIRBuilder &MIRBuilder) {
1473   const Value *Src = U.getOperand(0);
1474   uint64_t Offset = getOffsetFromIndices(U, *DL);
1475   ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
1476   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
1477   unsigned Idx = llvm::lower_bound(Offsets, Offset) - Offsets.begin();
1478   auto &DstRegs = allocateVRegs(U);
1479 
1480   for (unsigned i = 0; i < DstRegs.size(); ++i)
1481     DstRegs[i] = SrcRegs[Idx++];
1482 
1483   return true;
1484 }
1485 
1486 bool IRTranslator::translateInsertValue(const User &U,
1487                                         MachineIRBuilder &MIRBuilder) {
1488   const Value *Src = U.getOperand(0);
1489   uint64_t Offset = getOffsetFromIndices(U, *DL);
1490   auto &DstRegs = allocateVRegs(U);
1491   ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
1492   ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
1493   ArrayRef<Register> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
1494   auto *InsertedIt = InsertedRegs.begin();
1495 
1496   for (unsigned i = 0; i < DstRegs.size(); ++i) {
1497     if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
1498       DstRegs[i] = *InsertedIt++;
1499     else
1500       DstRegs[i] = SrcRegs[i];
1501   }
1502 
1503   return true;
1504 }
1505 
1506 bool IRTranslator::translateSelect(const User &U,
1507                                    MachineIRBuilder &MIRBuilder) {
1508   Register Tst = getOrCreateVReg(*U.getOperand(0));
1509   ArrayRef<Register> ResRegs = getOrCreateVRegs(U);
1510   ArrayRef<Register> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
1511   ArrayRef<Register> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
1512 
1513   uint32_t Flags = 0;
1514   if (const SelectInst *SI = dyn_cast<SelectInst>(&U))
1515     Flags = MachineInstr::copyFlagsFromInstruction(*SI);
1516 
1517   for (unsigned i = 0; i < ResRegs.size(); ++i) {
1518     MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i], Flags);
1519   }
1520 
1521   return true;
1522 }
1523 
1524 bool IRTranslator::translateCopy(const User &U, const Value &V,
1525                                  MachineIRBuilder &MIRBuilder) {
1526   Register Src = getOrCreateVReg(V);
1527   auto &Regs = *VMap.getVRegs(U);
1528   if (Regs.empty()) {
1529     Regs.push_back(Src);
1530     VMap.getOffsets(U)->push_back(0);
1531   } else {
1532     // If we already assigned a vreg for this instruction, we can't change that.
1533     // Emit a copy to satisfy the users we already emitted.
1534     MIRBuilder.buildCopy(Regs[0], Src);
1535   }
1536   return true;
1537 }
1538 
1539 bool IRTranslator::translateBitCast(const User &U,
1540                                     MachineIRBuilder &MIRBuilder) {
1541   // If we're bitcasting to the source type, we can reuse the source vreg.
1542   if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
1543       getLLTForType(*U.getType(), *DL)) {
1544     // If the source is a ConstantInt then it was probably created by
1545     // ConstantHoisting and we should leave it alone.
1546     if (isa<ConstantInt>(U.getOperand(0)))
1547       return translateCast(TargetOpcode::G_CONSTANT_FOLD_BARRIER, U,
1548                            MIRBuilder);
1549     return translateCopy(U, *U.getOperand(0), MIRBuilder);
1550   }
1551 
1552   return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
1553 }
1554 
1555 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
1556                                  MachineIRBuilder &MIRBuilder) {
1557   if (U.getType()->getScalarType()->isBFloatTy() ||
1558       U.getOperand(0)->getType()->getScalarType()->isBFloatTy())
1559     return false;
1560 
1561   uint32_t Flags = 0;
1562   if (const Instruction *I = dyn_cast<Instruction>(&U))
1563     Flags = MachineInstr::copyFlagsFromInstruction(*I);
1564 
1565   Register Op = getOrCreateVReg(*U.getOperand(0));
1566   Register Res = getOrCreateVReg(U);
1567   MIRBuilder.buildInstr(Opcode, {Res}, {Op}, Flags);
1568   return true;
1569 }
1570 
1571 bool IRTranslator::translateGetElementPtr(const User &U,
1572                                           MachineIRBuilder &MIRBuilder) {
1573   Value &Op0 = *U.getOperand(0);
1574   Register BaseReg = getOrCreateVReg(Op0);
1575   Type *PtrIRTy = Op0.getType();
1576   LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
1577   Type *OffsetIRTy = DL->getIndexType(PtrIRTy);
1578   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1579 
1580   uint32_t Flags = 0;
1581   if (const Instruction *I = dyn_cast<Instruction>(&U))
1582     Flags = MachineInstr::copyFlagsFromInstruction(*I);
1583 
1584   // Normalize Vector GEP - all scalar operands should be converted to the
1585   // splat vector.
1586   unsigned VectorWidth = 0;
1587 
1588   // True if we should use a splat vector; using VectorWidth alone is not
1589   // sufficient.
1590   bool WantSplatVector = false;
1591   if (auto *VT = dyn_cast<VectorType>(U.getType())) {
1592     VectorWidth = cast<FixedVectorType>(VT)->getNumElements();
1593     // We don't produce 1 x N vectors; those are treated as scalars.
1594     WantSplatVector = VectorWidth > 1;
1595   }
1596 
1597   // We might need to splat the base pointer into a vector if the offsets
1598   // are vectors.
1599   if (WantSplatVector && !PtrTy.isVector()) {
1600     BaseReg = MIRBuilder
1601                   .buildSplatBuildVector(LLT::fixed_vector(VectorWidth, PtrTy),
1602                                          BaseReg)
1603                   .getReg(0);
1604     PtrIRTy = FixedVectorType::get(PtrIRTy, VectorWidth);
1605     PtrTy = getLLTForType(*PtrIRTy, *DL);
1606     OffsetIRTy = DL->getIndexType(PtrIRTy);
1607     OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1608   }
1609 
1610   int64_t Offset = 0;
1611   for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
1612        GTI != E; ++GTI) {
1613     const Value *Idx = GTI.getOperand();
1614     if (StructType *StTy = GTI.getStructTypeOrNull()) {
1615       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
1616       Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
1617       continue;
1618     } else {
1619       uint64_t ElementSize = GTI.getSequentialElementStride(*DL);
1620 
1621       // If this is a scalar constant or a splat vector of constants,
1622       // handle it quickly.
1623       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
1624         if (std::optional<int64_t> Val = CI->getValue().trySExtValue()) {
1625           Offset += ElementSize * *Val;
1626           continue;
1627         }
1628       }
1629 
1630       if (Offset != 0) {
1631         auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset);
1632         BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, OffsetMIB.getReg(0))
1633                       .getReg(0);
1634         Offset = 0;
1635       }
1636 
1637       Register IdxReg = getOrCreateVReg(*Idx);
1638       LLT IdxTy = MRI->getType(IdxReg);
1639       if (IdxTy != OffsetTy) {
1640         if (!IdxTy.isVector() && WantSplatVector) {
1641           IdxReg = MIRBuilder
1642                        .buildSplatBuildVector(OffsetTy.changeElementType(IdxTy),
1643                                               IdxReg)
1644                        .getReg(0);
1645         }
1646 
1647         IdxReg = MIRBuilder.buildSExtOrTrunc(OffsetTy, IdxReg).getReg(0);
1648       }
1649 
1650       // N = N + Idx * ElementSize;
1651       // Avoid doing it for ElementSize of 1.
1652       Register GepOffsetReg;
1653       if (ElementSize != 1) {
1654         auto ElementSizeMIB = MIRBuilder.buildConstant(
1655             getLLTForType(*OffsetIRTy, *DL), ElementSize);
1656         GepOffsetReg =
1657             MIRBuilder.buildMul(OffsetTy, IdxReg, ElementSizeMIB).getReg(0);
1658       } else
1659         GepOffsetReg = IdxReg;
1660 
1661       BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, GepOffsetReg).getReg(0);
1662     }
1663   }
1664 
1665   if (Offset != 0) {
1666     auto OffsetMIB =
1667         MIRBuilder.buildConstant(OffsetTy, Offset);
1668 
1669     if (int64_t(Offset) >= 0 && cast<GEPOperator>(U).isInBounds())
1670       Flags |= MachineInstr::MIFlag::NoUWrap;
1671 
1672     MIRBuilder.buildPtrAdd(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0),
1673                            Flags);
1674     return true;
1675   }
1676 
1677   MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
1678   return true;
1679 }
1680 
1681 bool IRTranslator::translateMemFunc(const CallInst &CI,
1682                                     MachineIRBuilder &MIRBuilder,
1683                                     unsigned Opcode) {
1684   const Value *SrcPtr = CI.getArgOperand(1);
1685   // If the source is undef, then just emit a nop.
1686   if (isa<UndefValue>(SrcPtr))
1687     return true;
1688 
1689   SmallVector<Register, 3> SrcRegs;
1690 
1691   unsigned MinPtrSize = UINT_MAX;
1692   for (auto AI = CI.arg_begin(), AE = CI.arg_end(); std::next(AI) != AE; ++AI) {
1693     Register SrcReg = getOrCreateVReg(**AI);
1694     LLT SrcTy = MRI->getType(SrcReg);
1695     if (SrcTy.isPointer())
1696       MinPtrSize = std::min<unsigned>(SrcTy.getSizeInBits(), MinPtrSize);
1697     SrcRegs.push_back(SrcReg);
1698   }
1699 
1700   LLT SizeTy = LLT::scalar(MinPtrSize);
1701 
1702   // The size operand should be the minimum of the pointer sizes.
1703   Register &SizeOpReg = SrcRegs[SrcRegs.size() - 1];
1704   if (MRI->getType(SizeOpReg) != SizeTy)
1705     SizeOpReg = MIRBuilder.buildZExtOrTrunc(SizeTy, SizeOpReg).getReg(0);
1706 
1707   auto ICall = MIRBuilder.buildInstr(Opcode);
1708   for (Register SrcReg : SrcRegs)
1709     ICall.addUse(SrcReg);
1710 
1711   Align DstAlign;
1712   Align SrcAlign;
1713   unsigned IsVol =
1714       cast<ConstantInt>(CI.getArgOperand(CI.arg_size() - 1))->getZExtValue();
1715 
1716   ConstantInt *CopySize = nullptr;
1717 
1718   if (auto *MCI = dyn_cast<MemCpyInst>(&CI)) {
1719     DstAlign = MCI->getDestAlign().valueOrOne();
1720     SrcAlign = MCI->getSourceAlign().valueOrOne();
1721     CopySize = dyn_cast<ConstantInt>(MCI->getArgOperand(2));
1722   } else if (auto *MCI = dyn_cast<MemCpyInlineInst>(&CI)) {
1723     DstAlign = MCI->getDestAlign().valueOrOne();
1724     SrcAlign = MCI->getSourceAlign().valueOrOne();
1725     CopySize = dyn_cast<ConstantInt>(MCI->getArgOperand(2));
1726   } else if (auto *MMI = dyn_cast<MemMoveInst>(&CI)) {
1727     DstAlign = MMI->getDestAlign().valueOrOne();
1728     SrcAlign = MMI->getSourceAlign().valueOrOne();
1729     CopySize = dyn_cast<ConstantInt>(MMI->getArgOperand(2));
1730   } else {
1731     auto *MSI = cast<MemSetInst>(&CI);
1732     DstAlign = MSI->getDestAlign().valueOrOne();
1733   }
1734 
1735   if (Opcode != TargetOpcode::G_MEMCPY_INLINE) {
1736     // We need to propagate the tail call flag from the IR inst as an argument.
1737     // Otherwise, we have to pessimize and assume later that we cannot tail call
1738     // any memory intrinsics.
1739     ICall.addImm(CI.isTailCall() ? 1 : 0);
1740   }
1741 
1742   // Create mem operands to store the alignment and volatile info.
1743   MachineMemOperand::Flags LoadFlags = MachineMemOperand::MOLoad;
1744   MachineMemOperand::Flags StoreFlags = MachineMemOperand::MOStore;
1745   if (IsVol) {
1746     LoadFlags |= MachineMemOperand::MOVolatile;
1747     StoreFlags |= MachineMemOperand::MOVolatile;
1748   }
1749 
1750   AAMDNodes AAInfo = CI.getAAMetadata();
1751   if (AA && CopySize &&
1752       AA->pointsToConstantMemory(MemoryLocation(
1753           SrcPtr, LocationSize::precise(CopySize->getZExtValue()), AAInfo))) {
1754     LoadFlags |= MachineMemOperand::MOInvariant;
1755 
1756     // FIXME: pointsToConstantMemory probably does not imply dereferenceable,
1757     // but the previous usage implied it did. Probably should check
1758     // isDereferenceableAndAlignedPointer.
1759     LoadFlags |= MachineMemOperand::MODereferenceable;
1760   }
1761 
1762   ICall.addMemOperand(
1763       MF->getMachineMemOperand(MachinePointerInfo(CI.getArgOperand(0)),
1764                                StoreFlags, 1, DstAlign, AAInfo));
1765   if (Opcode != TargetOpcode::G_MEMSET)
1766     ICall.addMemOperand(MF->getMachineMemOperand(
1767         MachinePointerInfo(SrcPtr), LoadFlags, 1, SrcAlign, AAInfo));
1768 
1769   return true;
1770 }
1771 
1772 bool IRTranslator::translateTrap(const CallInst &CI,
1773                                  MachineIRBuilder &MIRBuilder,
1774                                  unsigned Opcode) {
1775   StringRef TrapFuncName =
1776       CI.getAttributes().getFnAttr("trap-func-name").getValueAsString();
1777   if (TrapFuncName.empty()) {
1778     if (Opcode == TargetOpcode::G_UBSANTRAP) {
1779       uint64_t Code = cast<ConstantInt>(CI.getOperand(0))->getZExtValue();
1780       MIRBuilder.buildInstr(Opcode, {}, ArrayRef<llvm::SrcOp>{Code});
1781     } else {
1782       MIRBuilder.buildInstr(Opcode);
1783     }
1784     return true;
1785   }
1786 
1787   CallLowering::CallLoweringInfo Info;
1788   if (Opcode == TargetOpcode::G_UBSANTRAP)
1789     Info.OrigArgs.push_back({getOrCreateVRegs(*CI.getArgOperand(0)),
1790                              CI.getArgOperand(0)->getType(), 0});
1791 
1792   Info.Callee = MachineOperand::CreateES(TrapFuncName.data());
1793   Info.CB = &CI;
1794   Info.OrigRet = {Register(), Type::getVoidTy(CI.getContext()), 0};
1795   return CLI->lowerCall(MIRBuilder, Info);
1796 }
1797 
1798 bool IRTranslator::translateVectorInterleave2Intrinsic(
1799     const CallInst &CI, MachineIRBuilder &MIRBuilder) {
1800   assert(CI.getIntrinsicID() == Intrinsic::vector_interleave2 &&
1801          "This function can only be called on the interleave2 intrinsic!");
1802   // Canonicalize interleave2 to G_SHUFFLE_VECTOR (similar to SelectionDAG).
1803   Register Op0 = getOrCreateVReg(*CI.getOperand(0));
1804   Register Op1 = getOrCreateVReg(*CI.getOperand(1));
1805   Register Res = getOrCreateVReg(CI);
1806 
1807   LLT OpTy = MRI->getType(Op0);
1808   MIRBuilder.buildShuffleVector(Res, Op0, Op1,
1809                                 createInterleaveMask(OpTy.getNumElements(), 2));
1810 
1811   return true;
1812 }
1813 
1814 bool IRTranslator::translateVectorDeinterleave2Intrinsic(
1815     const CallInst &CI, MachineIRBuilder &MIRBuilder) {
1816   assert(CI.getIntrinsicID() == Intrinsic::vector_deinterleave2 &&
1817          "This function can only be called on the deinterleave2 intrinsic!");
1818   // Canonicalize deinterleave2 to shuffles that extract sub-vectors (similar to
1819   // SelectionDAG).
1820   Register Op = getOrCreateVReg(*CI.getOperand(0));
1821   auto Undef = MIRBuilder.buildUndef(MRI->getType(Op));
1822   ArrayRef<Register> Res = getOrCreateVRegs(CI);
1823 
1824   LLT ResTy = MRI->getType(Res[0]);
1825   MIRBuilder.buildShuffleVector(Res[0], Op, Undef,
1826                                 createStrideMask(0, 2, ResTy.getNumElements()));
1827   MIRBuilder.buildShuffleVector(Res[1], Op, Undef,
1828                                 createStrideMask(1, 2, ResTy.getNumElements()));
1829 
1830   return true;
1831 }
1832 
1833 void IRTranslator::getStackGuard(Register DstReg,
1834                                  MachineIRBuilder &MIRBuilder) {
1835   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1836   MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
1837   auto MIB =
1838       MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD, {DstReg}, {});
1839 
1840   Value *Global = TLI->getSDagStackGuard(*MF->getFunction().getParent());
1841   if (!Global)
1842     return;
1843 
1844   unsigned AddrSpace = Global->getType()->getPointerAddressSpace();
1845   LLT PtrTy = LLT::pointer(AddrSpace, DL->getPointerSizeInBits(AddrSpace));
1846 
1847   MachinePointerInfo MPInfo(Global);
1848   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
1849                MachineMemOperand::MODereferenceable;
1850   MachineMemOperand *MemRef = MF->getMachineMemOperand(
1851       MPInfo, Flags, PtrTy, DL->getPointerABIAlignment(AddrSpace));
1852   MIB.setMemRefs({MemRef});
1853 }
1854 
1855 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
1856                                               MachineIRBuilder &MIRBuilder) {
1857   ArrayRef<Register> ResRegs = getOrCreateVRegs(CI);
1858   MIRBuilder.buildInstr(
1859       Op, {ResRegs[0], ResRegs[1]},
1860       {getOrCreateVReg(*CI.getOperand(0)), getOrCreateVReg(*CI.getOperand(1))});
1861 
1862   return true;
1863 }
1864 
1865 bool IRTranslator::translateFixedPointIntrinsic(unsigned Op, const CallInst &CI,
1866                                                 MachineIRBuilder &MIRBuilder) {
1867   Register Dst = getOrCreateVReg(CI);
1868   Register Src0 = getOrCreateVReg(*CI.getOperand(0));
1869   Register Src1 = getOrCreateVReg(*CI.getOperand(1));
1870   uint64_t Scale = cast<ConstantInt>(CI.getOperand(2))->getZExtValue();
1871   MIRBuilder.buildInstr(Op, {Dst}, { Src0, Src1, Scale });
1872   return true;
1873 }
1874 
1875 unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) {
1876   switch (ID) {
1877     default:
1878       break;
1879     case Intrinsic::acos:
1880       return TargetOpcode::G_FACOS;
1881     case Intrinsic::asin:
1882       return TargetOpcode::G_FASIN;
1883     case Intrinsic::atan:
1884       return TargetOpcode::G_FATAN;
1885     case Intrinsic::atan2:
1886       return TargetOpcode::G_FATAN2;
1887     case Intrinsic::bswap:
1888       return TargetOpcode::G_BSWAP;
1889     case Intrinsic::bitreverse:
1890       return TargetOpcode::G_BITREVERSE;
1891     case Intrinsic::fshl:
1892       return TargetOpcode::G_FSHL;
1893     case Intrinsic::fshr:
1894       return TargetOpcode::G_FSHR;
1895     case Intrinsic::ceil:
1896       return TargetOpcode::G_FCEIL;
1897     case Intrinsic::cos:
1898       return TargetOpcode::G_FCOS;
1899     case Intrinsic::cosh:
1900       return TargetOpcode::G_FCOSH;
1901     case Intrinsic::ctpop:
1902       return TargetOpcode::G_CTPOP;
1903     case Intrinsic::exp:
1904       return TargetOpcode::G_FEXP;
1905     case Intrinsic::exp2:
1906       return TargetOpcode::G_FEXP2;
1907     case Intrinsic::exp10:
1908       return TargetOpcode::G_FEXP10;
1909     case Intrinsic::fabs:
1910       return TargetOpcode::G_FABS;
1911     case Intrinsic::copysign:
1912       return TargetOpcode::G_FCOPYSIGN;
1913     case Intrinsic::minnum:
1914       return TargetOpcode::G_FMINNUM;
1915     case Intrinsic::maxnum:
1916       return TargetOpcode::G_FMAXNUM;
1917     case Intrinsic::minimum:
1918       return TargetOpcode::G_FMINIMUM;
1919     case Intrinsic::maximum:
1920       return TargetOpcode::G_FMAXIMUM;
1921     case Intrinsic::canonicalize:
1922       return TargetOpcode::G_FCANONICALIZE;
1923     case Intrinsic::floor:
1924       return TargetOpcode::G_FFLOOR;
1925     case Intrinsic::fma:
1926       return TargetOpcode::G_FMA;
1927     case Intrinsic::log:
1928       return TargetOpcode::G_FLOG;
1929     case Intrinsic::log2:
1930       return TargetOpcode::G_FLOG2;
1931     case Intrinsic::log10:
1932       return TargetOpcode::G_FLOG10;
1933     case Intrinsic::ldexp:
1934       return TargetOpcode::G_FLDEXP;
1935     case Intrinsic::nearbyint:
1936       return TargetOpcode::G_FNEARBYINT;
1937     case Intrinsic::pow:
1938       return TargetOpcode::G_FPOW;
1939     case Intrinsic::powi:
1940       return TargetOpcode::G_FPOWI;
1941     case Intrinsic::rint:
1942       return TargetOpcode::G_FRINT;
1943     case Intrinsic::round:
1944       return TargetOpcode::G_INTRINSIC_ROUND;
1945     case Intrinsic::roundeven:
1946       return TargetOpcode::G_INTRINSIC_ROUNDEVEN;
1947     case Intrinsic::sin:
1948       return TargetOpcode::G_FSIN;
1949     case Intrinsic::sinh:
1950       return TargetOpcode::G_FSINH;
1951     case Intrinsic::sqrt:
1952       return TargetOpcode::G_FSQRT;
1953     case Intrinsic::tan:
1954       return TargetOpcode::G_FTAN;
1955     case Intrinsic::tanh:
1956       return TargetOpcode::G_FTANH;
1957     case Intrinsic::trunc:
1958       return TargetOpcode::G_INTRINSIC_TRUNC;
1959     case Intrinsic::readcyclecounter:
1960       return TargetOpcode::G_READCYCLECOUNTER;
1961     case Intrinsic::readsteadycounter:
1962       return TargetOpcode::G_READSTEADYCOUNTER;
1963     case Intrinsic::ptrmask:
1964       return TargetOpcode::G_PTRMASK;
1965     case Intrinsic::lrint:
1966       return TargetOpcode::G_INTRINSIC_LRINT;
1967     case Intrinsic::llrint:
1968       return TargetOpcode::G_INTRINSIC_LLRINT;
1969     // FADD/FMUL require checking the FMF, so are handled elsewhere.
1970     case Intrinsic::vector_reduce_fmin:
1971       return TargetOpcode::G_VECREDUCE_FMIN;
1972     case Intrinsic::vector_reduce_fmax:
1973       return TargetOpcode::G_VECREDUCE_FMAX;
1974     case Intrinsic::vector_reduce_fminimum:
1975       return TargetOpcode::G_VECREDUCE_FMINIMUM;
1976     case Intrinsic::vector_reduce_fmaximum:
1977       return TargetOpcode::G_VECREDUCE_FMAXIMUM;
1978     case Intrinsic::vector_reduce_add:
1979       return TargetOpcode::G_VECREDUCE_ADD;
1980     case Intrinsic::vector_reduce_mul:
1981       return TargetOpcode::G_VECREDUCE_MUL;
1982     case Intrinsic::vector_reduce_and:
1983       return TargetOpcode::G_VECREDUCE_AND;
1984     case Intrinsic::vector_reduce_or:
1985       return TargetOpcode::G_VECREDUCE_OR;
1986     case Intrinsic::vector_reduce_xor:
1987       return TargetOpcode::G_VECREDUCE_XOR;
1988     case Intrinsic::vector_reduce_smax:
1989       return TargetOpcode::G_VECREDUCE_SMAX;
1990     case Intrinsic::vector_reduce_smin:
1991       return TargetOpcode::G_VECREDUCE_SMIN;
1992     case Intrinsic::vector_reduce_umax:
1993       return TargetOpcode::G_VECREDUCE_UMAX;
1994     case Intrinsic::vector_reduce_umin:
1995       return TargetOpcode::G_VECREDUCE_UMIN;
1996     case Intrinsic::experimental_vector_compress:
1997       return TargetOpcode::G_VECTOR_COMPRESS;
1998     case Intrinsic::lround:
1999       return TargetOpcode::G_LROUND;
2000     case Intrinsic::llround:
2001       return TargetOpcode::G_LLROUND;
2002     case Intrinsic::get_fpenv:
2003       return TargetOpcode::G_GET_FPENV;
2004     case Intrinsic::get_fpmode:
2005       return TargetOpcode::G_GET_FPMODE;
2006   }
2007   return Intrinsic::not_intrinsic;
2008 }
2009 
2010 bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI,
2011                                             Intrinsic::ID ID,
2012                                             MachineIRBuilder &MIRBuilder) {
2013 
2014   unsigned Op = getSimpleIntrinsicOpcode(ID);
2015 
2016   // Is this a simple intrinsic?
2017   if (Op == Intrinsic::not_intrinsic)
2018     return false;
2019 
2020   // Yes. Let's translate it.
2021   SmallVector<llvm::SrcOp, 4> VRegs;
2022   for (const auto &Arg : CI.args())
2023     VRegs.push_back(getOrCreateVReg(*Arg));
2024 
2025   MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
2026                         MachineInstr::copyFlagsFromInstruction(CI));
2027   return true;
2028 }
2029 
2030 // TODO: Include ConstainedOps.def when all strict instructions are defined.
2031 static unsigned getConstrainedOpcode(Intrinsic::ID ID) {
2032   switch (ID) {
2033   case Intrinsic::experimental_constrained_fadd:
2034     return TargetOpcode::G_STRICT_FADD;
2035   case Intrinsic::experimental_constrained_fsub:
2036     return TargetOpcode::G_STRICT_FSUB;
2037   case Intrinsic::experimental_constrained_fmul:
2038     return TargetOpcode::G_STRICT_FMUL;
2039   case Intrinsic::experimental_constrained_fdiv:
2040     return TargetOpcode::G_STRICT_FDIV;
2041   case Intrinsic::experimental_constrained_frem:
2042     return TargetOpcode::G_STRICT_FREM;
2043   case Intrinsic::experimental_constrained_fma:
2044     return TargetOpcode::G_STRICT_FMA;
2045   case Intrinsic::experimental_constrained_sqrt:
2046     return TargetOpcode::G_STRICT_FSQRT;
2047   case Intrinsic::experimental_constrained_ldexp:
2048     return TargetOpcode::G_STRICT_FLDEXP;
2049   default:
2050     return 0;
2051   }
2052 }
2053 
2054 bool IRTranslator::translateConstrainedFPIntrinsic(
2055   const ConstrainedFPIntrinsic &FPI, MachineIRBuilder &MIRBuilder) {
2056   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
2057 
2058   unsigned Opcode = getConstrainedOpcode(FPI.getIntrinsicID());
2059   if (!Opcode)
2060     return false;
2061 
2062   uint32_t Flags = MachineInstr::copyFlagsFromInstruction(FPI);
2063   if (EB == fp::ExceptionBehavior::ebIgnore)
2064     Flags |= MachineInstr::NoFPExcept;
2065 
2066   SmallVector<llvm::SrcOp, 4> VRegs;
2067   for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
2068     VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(I)));
2069 
2070   MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(FPI)}, VRegs, Flags);
2071   return true;
2072 }
2073 
2074 std::optional<MCRegister> IRTranslator::getArgPhysReg(Argument &Arg) {
2075   auto VRegs = getOrCreateVRegs(Arg);
2076   if (VRegs.size() != 1)
2077     return std::nullopt;
2078 
2079   // Arguments are lowered as a copy of a livein physical register.
2080   auto *VRegDef = MF->getRegInfo().getVRegDef(VRegs[0]);
2081   if (!VRegDef || !VRegDef->isCopy())
2082     return std::nullopt;
2083   return VRegDef->getOperand(1).getReg().asMCReg();
2084 }
2085 
2086 bool IRTranslator::translateIfEntryValueArgument(bool isDeclare, Value *Val,
2087                                                  const DILocalVariable *Var,
2088                                                  const DIExpression *Expr,
2089                                                  const DebugLoc &DL,
2090                                                  MachineIRBuilder &MIRBuilder) {
2091   auto *Arg = dyn_cast<Argument>(Val);
2092   if (!Arg)
2093     return false;
2094 
2095   if (!Expr->isEntryValue())
2096     return false;
2097 
2098   std::optional<MCRegister> PhysReg = getArgPhysReg(*Arg);
2099   if (!PhysReg) {
2100     LLVM_DEBUG(dbgs() << "Dropping dbg." << (isDeclare ? "declare" : "value")
2101                       << ": expression is entry_value but "
2102                       << "couldn't find a physical register\n");
2103     LLVM_DEBUG(dbgs() << *Var << "\n");
2104     return true;
2105   }
2106 
2107   if (isDeclare) {
2108     // Append an op deref to account for the fact that this is a dbg_declare.
2109     Expr = DIExpression::append(Expr, dwarf::DW_OP_deref);
2110     MF->setVariableDbgInfo(Var, Expr, *PhysReg, DL);
2111   } else {
2112     MIRBuilder.buildDirectDbgValue(*PhysReg, Var, Expr);
2113   }
2114 
2115   return true;
2116 }
2117 
2118 static unsigned getConvOpcode(Intrinsic::ID ID) {
2119   switch (ID) {
2120   default:
2121     llvm_unreachable("Unexpected intrinsic");
2122   case Intrinsic::experimental_convergence_anchor:
2123     return TargetOpcode::CONVERGENCECTRL_ANCHOR;
2124   case Intrinsic::experimental_convergence_entry:
2125     return TargetOpcode::CONVERGENCECTRL_ENTRY;
2126   case Intrinsic::experimental_convergence_loop:
2127     return TargetOpcode::CONVERGENCECTRL_LOOP;
2128   }
2129 }
2130 
2131 bool IRTranslator::translateConvergenceControlIntrinsic(
2132     const CallInst &CI, Intrinsic::ID ID, MachineIRBuilder &MIRBuilder) {
2133   MachineInstrBuilder MIB = MIRBuilder.buildInstr(getConvOpcode(ID));
2134   Register OutputReg = getOrCreateConvergenceTokenVReg(CI);
2135   MIB.addDef(OutputReg);
2136 
2137   if (ID == Intrinsic::experimental_convergence_loop) {
2138     auto Bundle = CI.getOperandBundle(LLVMContext::OB_convergencectrl);
2139     assert(Bundle && "Expected a convergence control token.");
2140     Register InputReg =
2141         getOrCreateConvergenceTokenVReg(*Bundle->Inputs[0].get());
2142     MIB.addUse(InputReg);
2143   }
2144 
2145   return true;
2146 }
2147 
2148 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
2149                                            MachineIRBuilder &MIRBuilder) {
2150   if (auto *MI = dyn_cast<AnyMemIntrinsic>(&CI)) {
2151     if (ORE->enabled()) {
2152       if (MemoryOpRemark::canHandle(MI, *LibInfo)) {
2153         MemoryOpRemark R(*ORE, "gisel-irtranslator-memsize", *DL, *LibInfo);
2154         R.visit(MI);
2155       }
2156     }
2157   }
2158 
2159   // If this is a simple intrinsic (that is, we just need to add a def of
2160   // a vreg, and uses for each arg operand, then translate it.
2161   if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
2162     return true;
2163 
2164   switch (ID) {
2165   default:
2166     break;
2167   case Intrinsic::lifetime_start:
2168   case Intrinsic::lifetime_end: {
2169     // No stack colouring in O0, discard region information.
2170     if (MF->getTarget().getOptLevel() == CodeGenOptLevel::None)
2171       return true;
2172 
2173     unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START
2174                                                   : TargetOpcode::LIFETIME_END;
2175 
2176     // Get the underlying objects for the location passed on the lifetime
2177     // marker.
2178     SmallVector<const Value *, 4> Allocas;
2179     getUnderlyingObjects(CI.getArgOperand(1), Allocas);
2180 
2181     // Iterate over each underlying object, creating lifetime markers for each
2182     // static alloca. Quit if we find a non-static alloca.
2183     for (const Value *V : Allocas) {
2184       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
2185       if (!AI)
2186         continue;
2187 
2188       if (!AI->isStaticAlloca())
2189         return true;
2190 
2191       MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI));
2192     }
2193     return true;
2194   }
2195   case Intrinsic::fake_use: {
2196     SmallVector<llvm::SrcOp, 4> VRegs;
2197     for (const auto &Arg : CI.args())
2198       for (auto VReg : getOrCreateVRegs(*Arg))
2199         VRegs.push_back(VReg);
2200     MIRBuilder.buildInstr(TargetOpcode::FAKE_USE, {}, VRegs);
2201     MF->setHasFakeUses(true);
2202     return true;
2203   }
2204   case Intrinsic::dbg_declare: {
2205     const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
2206     assert(DI.getVariable() && "Missing variable");
2207     translateDbgDeclareRecord(DI.getAddress(), DI.hasArgList(), DI.getVariable(),
2208                        DI.getExpression(), DI.getDebugLoc(), MIRBuilder);
2209     return true;
2210   }
2211   case Intrinsic::dbg_label: {
2212     const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
2213     assert(DI.getLabel() && "Missing label");
2214 
2215     assert(DI.getLabel()->isValidLocationForIntrinsic(
2216                MIRBuilder.getDebugLoc()) &&
2217            "Expected inlined-at fields to agree");
2218 
2219     MIRBuilder.buildDbgLabel(DI.getLabel());
2220     return true;
2221   }
2222   case Intrinsic::vaend:
2223     // No target I know of cares about va_end. Certainly no in-tree target
2224     // does. Simplest intrinsic ever!
2225     return true;
2226   case Intrinsic::vastart: {
2227     Value *Ptr = CI.getArgOperand(0);
2228     unsigned ListSize = TLI->getVaListSizeInBits(*DL) / 8;
2229     Align Alignment = getKnownAlignment(Ptr, *DL);
2230 
2231     MIRBuilder.buildInstr(TargetOpcode::G_VASTART, {}, {getOrCreateVReg(*Ptr)})
2232         .addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Ptr),
2233                                                 MachineMemOperand::MOStore,
2234                                                 ListSize, Alignment));
2235     return true;
2236   }
2237   case Intrinsic::dbg_assign:
2238     // A dbg.assign is a dbg.value with more information about stack locations,
2239     // typically produced during optimisation of variables with leaked
2240     // addresses. We can treat it like a normal dbg_value intrinsic here; to
2241     // benefit from the full analysis of stack/SSA locations, GlobalISel would
2242     // need to register for and use the AssignmentTrackingAnalysis pass.
2243     [[fallthrough]];
2244   case Intrinsic::dbg_value: {
2245     // This form of DBG_VALUE is target-independent.
2246     const DbgValueInst &DI = cast<DbgValueInst>(CI);
2247     translateDbgValueRecord(DI.getValue(), DI.hasArgList(), DI.getVariable(),
2248                        DI.getExpression(), DI.getDebugLoc(), MIRBuilder);
2249     return true;
2250   }
2251   case Intrinsic::uadd_with_overflow:
2252     return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
2253   case Intrinsic::sadd_with_overflow:
2254     return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
2255   case Intrinsic::usub_with_overflow:
2256     return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
2257   case Intrinsic::ssub_with_overflow:
2258     return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
2259   case Intrinsic::umul_with_overflow:
2260     return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
2261   case Intrinsic::smul_with_overflow:
2262     return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
2263   case Intrinsic::uadd_sat:
2264     return translateBinaryOp(TargetOpcode::G_UADDSAT, CI, MIRBuilder);
2265   case Intrinsic::sadd_sat:
2266     return translateBinaryOp(TargetOpcode::G_SADDSAT, CI, MIRBuilder);
2267   case Intrinsic::usub_sat:
2268     return translateBinaryOp(TargetOpcode::G_USUBSAT, CI, MIRBuilder);
2269   case Intrinsic::ssub_sat:
2270     return translateBinaryOp(TargetOpcode::G_SSUBSAT, CI, MIRBuilder);
2271   case Intrinsic::ushl_sat:
2272     return translateBinaryOp(TargetOpcode::G_USHLSAT, CI, MIRBuilder);
2273   case Intrinsic::sshl_sat:
2274     return translateBinaryOp(TargetOpcode::G_SSHLSAT, CI, MIRBuilder);
2275   case Intrinsic::umin:
2276     return translateBinaryOp(TargetOpcode::G_UMIN, CI, MIRBuilder);
2277   case Intrinsic::umax:
2278     return translateBinaryOp(TargetOpcode::G_UMAX, CI, MIRBuilder);
2279   case Intrinsic::smin:
2280     return translateBinaryOp(TargetOpcode::G_SMIN, CI, MIRBuilder);
2281   case Intrinsic::smax:
2282     return translateBinaryOp(TargetOpcode::G_SMAX, CI, MIRBuilder);
2283   case Intrinsic::abs:
2284     // TODO: Preserve "int min is poison" arg in GMIR?
2285     return translateUnaryOp(TargetOpcode::G_ABS, CI, MIRBuilder);
2286   case Intrinsic::smul_fix:
2287     return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIX, CI, MIRBuilder);
2288   case Intrinsic::umul_fix:
2289     return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIX, CI, MIRBuilder);
2290   case Intrinsic::smul_fix_sat:
2291     return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIXSAT, CI, MIRBuilder);
2292   case Intrinsic::umul_fix_sat:
2293     return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIXSAT, CI, MIRBuilder);
2294   case Intrinsic::sdiv_fix:
2295     return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIX, CI, MIRBuilder);
2296   case Intrinsic::udiv_fix:
2297     return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIX, CI, MIRBuilder);
2298   case Intrinsic::sdiv_fix_sat:
2299     return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIXSAT, CI, MIRBuilder);
2300   case Intrinsic::udiv_fix_sat:
2301     return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIXSAT, CI, MIRBuilder);
2302   case Intrinsic::fmuladd: {
2303     const TargetMachine &TM = MF->getTarget();
2304     Register Dst = getOrCreateVReg(CI);
2305     Register Op0 = getOrCreateVReg(*CI.getArgOperand(0));
2306     Register Op1 = getOrCreateVReg(*CI.getArgOperand(1));
2307     Register Op2 = getOrCreateVReg(*CI.getArgOperand(2));
2308     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
2309         TLI->isFMAFasterThanFMulAndFAdd(*MF,
2310                                         TLI->getValueType(*DL, CI.getType()))) {
2311       // TODO: Revisit this to see if we should move this part of the
2312       // lowering to the combiner.
2313       MIRBuilder.buildFMA(Dst, Op0, Op1, Op2,
2314                           MachineInstr::copyFlagsFromInstruction(CI));
2315     } else {
2316       LLT Ty = getLLTForType(*CI.getType(), *DL);
2317       auto FMul = MIRBuilder.buildFMul(
2318           Ty, Op0, Op1, MachineInstr::copyFlagsFromInstruction(CI));
2319       MIRBuilder.buildFAdd(Dst, FMul, Op2,
2320                            MachineInstr::copyFlagsFromInstruction(CI));
2321     }
2322     return true;
2323   }
2324   case Intrinsic::convert_from_fp16:
2325     // FIXME: This intrinsic should probably be removed from the IR.
2326     MIRBuilder.buildFPExt(getOrCreateVReg(CI),
2327                           getOrCreateVReg(*CI.getArgOperand(0)),
2328                           MachineInstr::copyFlagsFromInstruction(CI));
2329     return true;
2330   case Intrinsic::convert_to_fp16:
2331     // FIXME: This intrinsic should probably be removed from the IR.
2332     MIRBuilder.buildFPTrunc(getOrCreateVReg(CI),
2333                             getOrCreateVReg(*CI.getArgOperand(0)),
2334                             MachineInstr::copyFlagsFromInstruction(CI));
2335     return true;
2336   case Intrinsic::frexp: {
2337     ArrayRef<Register> VRegs = getOrCreateVRegs(CI);
2338     MIRBuilder.buildFFrexp(VRegs[0], VRegs[1],
2339                            getOrCreateVReg(*CI.getArgOperand(0)),
2340                            MachineInstr::copyFlagsFromInstruction(CI));
2341     return true;
2342   }
2343   case Intrinsic::sincos: {
2344     ArrayRef<Register> VRegs = getOrCreateVRegs(CI);
2345     MIRBuilder.buildFSincos(VRegs[0], VRegs[1],
2346                             getOrCreateVReg(*CI.getArgOperand(0)),
2347                             MachineInstr::copyFlagsFromInstruction(CI));
2348     return true;
2349   }
2350   case Intrinsic::fptosi_sat:
2351     MIRBuilder.buildFPTOSI_SAT(getOrCreateVReg(CI),
2352                                getOrCreateVReg(*CI.getArgOperand(0)));
2353     return true;
2354   case Intrinsic::fptoui_sat:
2355     MIRBuilder.buildFPTOUI_SAT(getOrCreateVReg(CI),
2356                                getOrCreateVReg(*CI.getArgOperand(0)));
2357     return true;
2358   case Intrinsic::memcpy_inline:
2359     return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMCPY_INLINE);
2360   case Intrinsic::memcpy:
2361     return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMCPY);
2362   case Intrinsic::memmove:
2363     return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMMOVE);
2364   case Intrinsic::memset:
2365     return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMSET);
2366   case Intrinsic::eh_typeid_for: {
2367     GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
2368     Register Reg = getOrCreateVReg(CI);
2369     unsigned TypeID = MF->getTypeIDFor(GV);
2370     MIRBuilder.buildConstant(Reg, TypeID);
2371     return true;
2372   }
2373   case Intrinsic::objectsize:
2374     llvm_unreachable("llvm.objectsize.* should have been lowered already");
2375 
2376   case Intrinsic::is_constant:
2377     llvm_unreachable("llvm.is.constant.* should have been lowered already");
2378 
2379   case Intrinsic::stackguard:
2380     getStackGuard(getOrCreateVReg(CI), MIRBuilder);
2381     return true;
2382   case Intrinsic::stackprotector: {
2383     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
2384     Register GuardVal;
2385     if (TLI->useLoadStackGuardNode(*CI.getModule())) {
2386       GuardVal = MRI->createGenericVirtualRegister(PtrTy);
2387       getStackGuard(GuardVal, MIRBuilder);
2388     } else
2389       GuardVal = getOrCreateVReg(*CI.getArgOperand(0)); // The guard's value.
2390 
2391     AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
2392     int FI = getOrCreateFrameIndex(*Slot);
2393     MF->getFrameInfo().setStackProtectorIndex(FI);
2394 
2395     MIRBuilder.buildStore(
2396         GuardVal, getOrCreateVReg(*Slot),
2397         *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
2398                                   MachineMemOperand::MOStore |
2399                                       MachineMemOperand::MOVolatile,
2400                                   PtrTy, Align(8)));
2401     return true;
2402   }
2403   case Intrinsic::stacksave: {
2404     MIRBuilder.buildInstr(TargetOpcode::G_STACKSAVE, {getOrCreateVReg(CI)}, {});
2405     return true;
2406   }
2407   case Intrinsic::stackrestore: {
2408     MIRBuilder.buildInstr(TargetOpcode::G_STACKRESTORE, {},
2409                           {getOrCreateVReg(*CI.getArgOperand(0))});
2410     return true;
2411   }
2412   case Intrinsic::cttz:
2413   case Intrinsic::ctlz: {
2414     ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
2415     bool isTrailing = ID == Intrinsic::cttz;
2416     unsigned Opcode = isTrailing
2417                           ? Cst->isZero() ? TargetOpcode::G_CTTZ
2418                                           : TargetOpcode::G_CTTZ_ZERO_UNDEF
2419                           : Cst->isZero() ? TargetOpcode::G_CTLZ
2420                                           : TargetOpcode::G_CTLZ_ZERO_UNDEF;
2421     MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(CI)},
2422                           {getOrCreateVReg(*CI.getArgOperand(0))});
2423     return true;
2424   }
2425   case Intrinsic::invariant_start: {
2426     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
2427     Register Undef = MRI->createGenericVirtualRegister(PtrTy);
2428     MIRBuilder.buildUndef(Undef);
2429     return true;
2430   }
2431   case Intrinsic::invariant_end:
2432     return true;
2433   case Intrinsic::expect:
2434   case Intrinsic::annotation:
2435   case Intrinsic::ptr_annotation:
2436   case Intrinsic::launder_invariant_group:
2437   case Intrinsic::strip_invariant_group: {
2438     // Drop the intrinsic, but forward the value.
2439     MIRBuilder.buildCopy(getOrCreateVReg(CI),
2440                          getOrCreateVReg(*CI.getArgOperand(0)));
2441     return true;
2442   }
2443   case Intrinsic::assume:
2444   case Intrinsic::experimental_noalias_scope_decl:
2445   case Intrinsic::var_annotation:
2446   case Intrinsic::sideeffect:
2447     // Discard annotate attributes, assumptions, and artificial side-effects.
2448     return true;
2449   case Intrinsic::read_volatile_register:
2450   case Intrinsic::read_register: {
2451     Value *Arg = CI.getArgOperand(0);
2452     MIRBuilder
2453         .buildInstr(TargetOpcode::G_READ_REGISTER, {getOrCreateVReg(CI)}, {})
2454         .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()));
2455     return true;
2456   }
2457   case Intrinsic::write_register: {
2458     Value *Arg = CI.getArgOperand(0);
2459     MIRBuilder.buildInstr(TargetOpcode::G_WRITE_REGISTER)
2460       .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()))
2461       .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
2462     return true;
2463   }
2464   case Intrinsic::localescape: {
2465     MachineBasicBlock &EntryMBB = MF->front();
2466     StringRef EscapedName = GlobalValue::dropLLVMManglingEscape(MF->getName());
2467 
2468     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
2469     // is the same on all targets.
2470     for (unsigned Idx = 0, E = CI.arg_size(); Idx < E; ++Idx) {
2471       Value *Arg = CI.getArgOperand(Idx)->stripPointerCasts();
2472       if (isa<ConstantPointerNull>(Arg))
2473         continue; // Skip null pointers. They represent a hole in index space.
2474 
2475       int FI = getOrCreateFrameIndex(*cast<AllocaInst>(Arg));
2476       MCSymbol *FrameAllocSym =
2477           MF->getContext().getOrCreateFrameAllocSymbol(EscapedName, Idx);
2478 
2479       // This should be inserted at the start of the entry block.
2480       auto LocalEscape =
2481           MIRBuilder.buildInstrNoInsert(TargetOpcode::LOCAL_ESCAPE)
2482               .addSym(FrameAllocSym)
2483               .addFrameIndex(FI);
2484 
2485       EntryMBB.insert(EntryMBB.begin(), LocalEscape);
2486     }
2487 
2488     return true;
2489   }
2490   case Intrinsic::vector_reduce_fadd:
2491   case Intrinsic::vector_reduce_fmul: {
2492     // Need to check for the reassoc flag to decide whether we want a
2493     // sequential reduction opcode or not.
2494     Register Dst = getOrCreateVReg(CI);
2495     Register ScalarSrc = getOrCreateVReg(*CI.getArgOperand(0));
2496     Register VecSrc = getOrCreateVReg(*CI.getArgOperand(1));
2497     unsigned Opc = 0;
2498     if (!CI.hasAllowReassoc()) {
2499       // The sequential ordering case.
2500       Opc = ID == Intrinsic::vector_reduce_fadd
2501                 ? TargetOpcode::G_VECREDUCE_SEQ_FADD
2502                 : TargetOpcode::G_VECREDUCE_SEQ_FMUL;
2503       MIRBuilder.buildInstr(Opc, {Dst}, {ScalarSrc, VecSrc},
2504                             MachineInstr::copyFlagsFromInstruction(CI));
2505       return true;
2506     }
2507     // We split the operation into a separate G_FADD/G_FMUL + the reduce,
2508     // since the associativity doesn't matter.
2509     unsigned ScalarOpc;
2510     if (ID == Intrinsic::vector_reduce_fadd) {
2511       Opc = TargetOpcode::G_VECREDUCE_FADD;
2512       ScalarOpc = TargetOpcode::G_FADD;
2513     } else {
2514       Opc = TargetOpcode::G_VECREDUCE_FMUL;
2515       ScalarOpc = TargetOpcode::G_FMUL;
2516     }
2517     LLT DstTy = MRI->getType(Dst);
2518     auto Rdx = MIRBuilder.buildInstr(
2519         Opc, {DstTy}, {VecSrc}, MachineInstr::copyFlagsFromInstruction(CI));
2520     MIRBuilder.buildInstr(ScalarOpc, {Dst}, {ScalarSrc, Rdx},
2521                           MachineInstr::copyFlagsFromInstruction(CI));
2522 
2523     return true;
2524   }
2525   case Intrinsic::trap:
2526     return translateTrap(CI, MIRBuilder, TargetOpcode::G_TRAP);
2527   case Intrinsic::debugtrap:
2528     return translateTrap(CI, MIRBuilder, TargetOpcode::G_DEBUGTRAP);
2529   case Intrinsic::ubsantrap:
2530     return translateTrap(CI, MIRBuilder, TargetOpcode::G_UBSANTRAP);
2531   case Intrinsic::allow_runtime_check:
2532   case Intrinsic::allow_ubsan_check:
2533     MIRBuilder.buildCopy(getOrCreateVReg(CI),
2534                          getOrCreateVReg(*ConstantInt::getTrue(CI.getType())));
2535     return true;
2536   case Intrinsic::amdgcn_cs_chain:
2537     return translateCallBase(CI, MIRBuilder);
2538   case Intrinsic::fptrunc_round: {
2539     uint32_t Flags = MachineInstr::copyFlagsFromInstruction(CI);
2540 
2541     // Convert the metadata argument to a constant integer
2542     Metadata *MD = cast<MetadataAsValue>(CI.getArgOperand(1))->getMetadata();
2543     std::optional<RoundingMode> RoundMode =
2544         convertStrToRoundingMode(cast<MDString>(MD)->getString());
2545 
2546     // Add the Rounding mode as an integer
2547     MIRBuilder
2548         .buildInstr(TargetOpcode::G_INTRINSIC_FPTRUNC_ROUND,
2549                     {getOrCreateVReg(CI)},
2550                     {getOrCreateVReg(*CI.getArgOperand(0))}, Flags)
2551         .addImm((int)*RoundMode);
2552 
2553     return true;
2554   }
2555   case Intrinsic::is_fpclass: {
2556     Value *FpValue = CI.getOperand(0);
2557     ConstantInt *TestMaskValue = cast<ConstantInt>(CI.getOperand(1));
2558 
2559     MIRBuilder
2560         .buildInstr(TargetOpcode::G_IS_FPCLASS, {getOrCreateVReg(CI)},
2561                     {getOrCreateVReg(*FpValue)})
2562         .addImm(TestMaskValue->getZExtValue());
2563 
2564     return true;
2565   }
2566   case Intrinsic::set_fpenv: {
2567     Value *FPEnv = CI.getOperand(0);
2568     MIRBuilder.buildSetFPEnv(getOrCreateVReg(*FPEnv));
2569     return true;
2570   }
2571   case Intrinsic::reset_fpenv:
2572     MIRBuilder.buildResetFPEnv();
2573     return true;
2574   case Intrinsic::set_fpmode: {
2575     Value *FPState = CI.getOperand(0);
2576     MIRBuilder.buildSetFPMode(getOrCreateVReg(*FPState));
2577     return true;
2578   }
2579   case Intrinsic::reset_fpmode:
2580     MIRBuilder.buildResetFPMode();
2581     return true;
2582   case Intrinsic::vscale: {
2583     MIRBuilder.buildVScale(getOrCreateVReg(CI), 1);
2584     return true;
2585   }
2586   case Intrinsic::scmp:
2587     MIRBuilder.buildSCmp(getOrCreateVReg(CI),
2588                          getOrCreateVReg(*CI.getOperand(0)),
2589                          getOrCreateVReg(*CI.getOperand(1)));
2590     return true;
2591   case Intrinsic::ucmp:
2592     MIRBuilder.buildUCmp(getOrCreateVReg(CI),
2593                          getOrCreateVReg(*CI.getOperand(0)),
2594                          getOrCreateVReg(*CI.getOperand(1)));
2595     return true;
2596   case Intrinsic::vector_extract:
2597     return translateExtractVector(CI, MIRBuilder);
2598   case Intrinsic::vector_insert:
2599     return translateInsertVector(CI, MIRBuilder);
2600   case Intrinsic::prefetch: {
2601     Value *Addr = CI.getOperand(0);
2602     unsigned RW = cast<ConstantInt>(CI.getOperand(1))->getZExtValue();
2603     unsigned Locality = cast<ConstantInt>(CI.getOperand(2))->getZExtValue();
2604     unsigned CacheType = cast<ConstantInt>(CI.getOperand(3))->getZExtValue();
2605 
2606     auto Flags = RW ? MachineMemOperand::MOStore : MachineMemOperand::MOLoad;
2607     auto &MMO = *MF->getMachineMemOperand(MachinePointerInfo(Addr), Flags,
2608                                           LLT(), Align());
2609 
2610     MIRBuilder.buildPrefetch(getOrCreateVReg(*Addr), RW, Locality, CacheType,
2611                              MMO);
2612 
2613     return true;
2614   }
2615 
2616   case Intrinsic::vector_interleave2:
2617   case Intrinsic::vector_deinterleave2: {
2618     // Both intrinsics have at least one operand.
2619     Value *Op0 = CI.getOperand(0);
2620     LLT ResTy = getLLTForType(*Op0->getType(), MIRBuilder.getDataLayout());
2621     if (!ResTy.isFixedVector())
2622       return false;
2623 
2624     if (CI.getIntrinsicID() == Intrinsic::vector_interleave2)
2625       return translateVectorInterleave2Intrinsic(CI, MIRBuilder);
2626 
2627     return translateVectorDeinterleave2Intrinsic(CI, MIRBuilder);
2628   }
2629 
2630 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)  \
2631   case Intrinsic::INTRINSIC:
2632 #include "llvm/IR/ConstrainedOps.def"
2633     return translateConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(CI),
2634                                            MIRBuilder);
2635   case Intrinsic::experimental_convergence_anchor:
2636   case Intrinsic::experimental_convergence_entry:
2637   case Intrinsic::experimental_convergence_loop:
2638     return translateConvergenceControlIntrinsic(CI, ID, MIRBuilder);
2639   }
2640   return false;
2641 }
2642 
2643 bool IRTranslator::translateInlineAsm(const CallBase &CB,
2644                                       MachineIRBuilder &MIRBuilder) {
2645 
2646   const InlineAsmLowering *ALI = MF->getSubtarget().getInlineAsmLowering();
2647 
2648   if (!ALI) {
2649     LLVM_DEBUG(
2650         dbgs() << "Inline asm lowering is not supported for this target yet\n");
2651     return false;
2652   }
2653 
2654   return ALI->lowerInlineAsm(
2655       MIRBuilder, CB, [&](const Value &Val) { return getOrCreateVRegs(Val); });
2656 }
2657 
2658 bool IRTranslator::translateCallBase(const CallBase &CB,
2659                                      MachineIRBuilder &MIRBuilder) {
2660   ArrayRef<Register> Res = getOrCreateVRegs(CB);
2661 
2662   SmallVector<ArrayRef<Register>, 8> Args;
2663   Register SwiftInVReg = 0;
2664   Register SwiftErrorVReg = 0;
2665   for (const auto &Arg : CB.args()) {
2666     if (CLI->supportSwiftError() && isSwiftError(Arg)) {
2667       assert(SwiftInVReg == 0 && "Expected only one swift error argument");
2668       LLT Ty = getLLTForType(*Arg->getType(), *DL);
2669       SwiftInVReg = MRI->createGenericVirtualRegister(Ty);
2670       MIRBuilder.buildCopy(SwiftInVReg, SwiftError.getOrCreateVRegUseAt(
2671                                             &CB, &MIRBuilder.getMBB(), Arg));
2672       Args.emplace_back(ArrayRef(SwiftInVReg));
2673       SwiftErrorVReg =
2674           SwiftError.getOrCreateVRegDefAt(&CB, &MIRBuilder.getMBB(), Arg);
2675       continue;
2676     }
2677     Args.push_back(getOrCreateVRegs(*Arg));
2678   }
2679 
2680   if (auto *CI = dyn_cast<CallInst>(&CB)) {
2681     if (ORE->enabled()) {
2682       if (MemoryOpRemark::canHandle(CI, *LibInfo)) {
2683         MemoryOpRemark R(*ORE, "gisel-irtranslator-memsize", *DL, *LibInfo);
2684         R.visit(CI);
2685       }
2686     }
2687   }
2688 
2689   std::optional<CallLowering::PtrAuthInfo> PAI;
2690   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_ptrauth)) {
2691     // Functions should never be ptrauth-called directly.
2692     assert(!CB.getCalledFunction() && "invalid direct ptrauth call");
2693 
2694     const Value *Key = Bundle->Inputs[0];
2695     const Value *Discriminator = Bundle->Inputs[1];
2696 
2697     // Look through ptrauth constants to try to eliminate the matching bundle
2698     // and turn this into a direct call with no ptrauth.
2699     // CallLowering will use the raw pointer if it doesn't find the PAI.
2700     const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CB.getCalledOperand());
2701     if (!CalleeCPA || !isa<Function>(CalleeCPA->getPointer()) ||
2702         !CalleeCPA->isKnownCompatibleWith(Key, Discriminator, *DL)) {
2703       // If we can't make it direct, package the bundle into PAI.
2704       Register DiscReg = getOrCreateVReg(*Discriminator);
2705       PAI = CallLowering::PtrAuthInfo{cast<ConstantInt>(Key)->getZExtValue(),
2706                                       DiscReg};
2707     }
2708   }
2709 
2710   Register ConvergenceCtrlToken = 0;
2711   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
2712     const auto &Token = *Bundle->Inputs[0].get();
2713     ConvergenceCtrlToken = getOrCreateConvergenceTokenVReg(Token);
2714   }
2715 
2716   // We don't set HasCalls on MFI here yet because call lowering may decide to
2717   // optimize into tail calls. Instead, we defer that to selection where a final
2718   // scan is done to check if any instructions are calls.
2719   bool Success = CLI->lowerCall(
2720       MIRBuilder, CB, Res, Args, SwiftErrorVReg, PAI, ConvergenceCtrlToken,
2721       [&]() { return getOrCreateVReg(*CB.getCalledOperand()); });
2722 
2723   // Check if we just inserted a tail call.
2724   if (Success) {
2725     assert(!HasTailCall && "Can't tail call return twice from block?");
2726     const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
2727     HasTailCall = TII->isTailCall(*std::prev(MIRBuilder.getInsertPt()));
2728   }
2729 
2730   return Success;
2731 }
2732 
2733 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
2734   const CallInst &CI = cast<CallInst>(U);
2735   auto TII = MF->getTarget().getIntrinsicInfo();
2736   const Function *F = CI.getCalledFunction();
2737 
2738   // FIXME: support Windows dllimport function calls and calls through
2739   // weak symbols.
2740   if (F && (F->hasDLLImportStorageClass() ||
2741             (MF->getTarget().getTargetTriple().isOSWindows() &&
2742              F->hasExternalWeakLinkage())))
2743     return false;
2744 
2745   // FIXME: support control flow guard targets.
2746   if (CI.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget))
2747     return false;
2748 
2749   // FIXME: support statepoints and related.
2750   if (isa<GCStatepointInst, GCRelocateInst, GCResultInst>(U))
2751     return false;
2752 
2753   if (CI.isInlineAsm())
2754     return translateInlineAsm(CI, MIRBuilder);
2755 
2756   diagnoseDontCall(CI);
2757 
2758   Intrinsic::ID ID = Intrinsic::not_intrinsic;
2759   if (F && F->isIntrinsic()) {
2760     ID = F->getIntrinsicID();
2761     if (TII && ID == Intrinsic::not_intrinsic)
2762       ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
2763   }
2764 
2765   if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic)
2766     return translateCallBase(CI, MIRBuilder);
2767 
2768   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
2769 
2770   if (translateKnownIntrinsic(CI, ID, MIRBuilder))
2771     return true;
2772 
2773   ArrayRef<Register> ResultRegs;
2774   if (!CI.getType()->isVoidTy())
2775     ResultRegs = getOrCreateVRegs(CI);
2776 
2777   // Ignore the callsite attributes. Backend code is most likely not expecting
2778   // an intrinsic to sometimes have side effects and sometimes not.
2779   MachineInstrBuilder MIB = MIRBuilder.buildIntrinsic(ID, ResultRegs);
2780   if (isa<FPMathOperator>(CI))
2781     MIB->copyIRFlags(CI);
2782 
2783   for (const auto &Arg : enumerate(CI.args())) {
2784     // If this is required to be an immediate, don't materialize it in a
2785     // register.
2786     if (CI.paramHasAttr(Arg.index(), Attribute::ImmArg)) {
2787       if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg.value())) {
2788         // imm arguments are more convenient than cimm (and realistically
2789         // probably sufficient), so use them.
2790         assert(CI->getBitWidth() <= 64 &&
2791                "large intrinsic immediates not handled");
2792         MIB.addImm(CI->getSExtValue());
2793       } else {
2794         MIB.addFPImm(cast<ConstantFP>(Arg.value()));
2795       }
2796     } else if (auto *MDVal = dyn_cast<MetadataAsValue>(Arg.value())) {
2797       auto *MD = MDVal->getMetadata();
2798       auto *MDN = dyn_cast<MDNode>(MD);
2799       if (!MDN) {
2800         if (auto *ConstMD = dyn_cast<ConstantAsMetadata>(MD))
2801           MDN = MDNode::get(MF->getFunction().getContext(), ConstMD);
2802         else // This was probably an MDString.
2803           return false;
2804       }
2805       MIB.addMetadata(MDN);
2806     } else {
2807       ArrayRef<Register> VRegs = getOrCreateVRegs(*Arg.value());
2808       if (VRegs.size() > 1)
2809         return false;
2810       MIB.addUse(VRegs[0]);
2811     }
2812   }
2813 
2814   // Add a MachineMemOperand if it is a target mem intrinsic.
2815   TargetLowering::IntrinsicInfo Info;
2816   // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
2817   if (TLI->getTgtMemIntrinsic(Info, CI, *MF, ID)) {
2818     Align Alignment = Info.align.value_or(
2819         DL->getABITypeAlign(Info.memVT.getTypeForEVT(F->getContext())));
2820     LLT MemTy = Info.memVT.isSimple()
2821                     ? getLLTForMVT(Info.memVT.getSimpleVT())
2822                     : LLT::scalar(Info.memVT.getStoreSizeInBits());
2823 
2824     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
2825     //       didn't yield anything useful.
2826     MachinePointerInfo MPI;
2827     if (Info.ptrVal)
2828       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
2829     else if (Info.fallbackAddressSpace)
2830       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
2831     MIB.addMemOperand(
2832         MF->getMachineMemOperand(MPI, Info.flags, MemTy, Alignment, CI.getAAMetadata()));
2833   }
2834 
2835   if (CI.isConvergent()) {
2836     if (auto Bundle = CI.getOperandBundle(LLVMContext::OB_convergencectrl)) {
2837       auto *Token = Bundle->Inputs[0].get();
2838       Register TokenReg = getOrCreateVReg(*Token);
2839       MIB.addUse(TokenReg, RegState::Implicit);
2840     }
2841   }
2842 
2843   return true;
2844 }
2845 
2846 bool IRTranslator::findUnwindDestinations(
2847     const BasicBlock *EHPadBB,
2848     BranchProbability Prob,
2849     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2850         &UnwindDests) {
2851   EHPersonality Personality = classifyEHPersonality(
2852       EHPadBB->getParent()->getFunction().getPersonalityFn());
2853   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2854   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2855   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2856   bool IsSEH = isAsynchronousEHPersonality(Personality);
2857 
2858   if (IsWasmCXX) {
2859     // Ignore this for now.
2860     return false;
2861   }
2862 
2863   while (EHPadBB) {
2864     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2865     BasicBlock *NewEHPadBB = nullptr;
2866     if (isa<LandingPadInst>(Pad)) {
2867       // Stop on landingpads. They are not funclets.
2868       UnwindDests.emplace_back(&getMBB(*EHPadBB), Prob);
2869       break;
2870     }
2871     if (isa<CleanupPadInst>(Pad)) {
2872       // Stop on cleanup pads. Cleanups are always funclet entries for all known
2873       // personalities.
2874       UnwindDests.emplace_back(&getMBB(*EHPadBB), Prob);
2875       UnwindDests.back().first->setIsEHScopeEntry();
2876       UnwindDests.back().first->setIsEHFuncletEntry();
2877       break;
2878     }
2879     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2880       // Add the catchpad handlers to the possible destinations.
2881       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2882         UnwindDests.emplace_back(&getMBB(*CatchPadBB), Prob);
2883         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2884         if (IsMSVCCXX || IsCoreCLR)
2885           UnwindDests.back().first->setIsEHFuncletEntry();
2886         if (!IsSEH)
2887           UnwindDests.back().first->setIsEHScopeEntry();
2888       }
2889       NewEHPadBB = CatchSwitch->getUnwindDest();
2890     } else {
2891       continue;
2892     }
2893 
2894     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2895     if (BPI && NewEHPadBB)
2896       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2897     EHPadBB = NewEHPadBB;
2898   }
2899   return true;
2900 }
2901 
2902 bool IRTranslator::translateInvoke(const User &U,
2903                                    MachineIRBuilder &MIRBuilder) {
2904   const InvokeInst &I = cast<InvokeInst>(U);
2905   MCContext &Context = MF->getContext();
2906 
2907   const BasicBlock *ReturnBB = I.getSuccessor(0);
2908   const BasicBlock *EHPadBB = I.getSuccessor(1);
2909 
2910   const Function *Fn = I.getCalledFunction();
2911 
2912   // FIXME: support invoking patchpoint and statepoint intrinsics.
2913   if (Fn && Fn->isIntrinsic())
2914     return false;
2915 
2916   // FIXME: support whatever these are.
2917   if (I.hasDeoptState())
2918     return false;
2919 
2920   // FIXME: support control flow guard targets.
2921   if (I.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget))
2922     return false;
2923 
2924   // FIXME: support Windows exception handling.
2925   if (!isa<LandingPadInst>(EHPadBB->getFirstNonPHI()))
2926     return false;
2927 
2928   // FIXME: support Windows dllimport function calls and calls through
2929   // weak symbols.
2930   if (Fn && (Fn->hasDLLImportStorageClass() ||
2931             (MF->getTarget().getTargetTriple().isOSWindows() &&
2932              Fn->hasExternalWeakLinkage())))
2933     return false;
2934 
2935   bool LowerInlineAsm = I.isInlineAsm();
2936   bool NeedEHLabel = true;
2937 
2938   // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
2939   // the region covered by the try.
2940   MCSymbol *BeginSymbol = nullptr;
2941   if (NeedEHLabel) {
2942     MIRBuilder.buildInstr(TargetOpcode::G_INVOKE_REGION_START);
2943     BeginSymbol = Context.createTempSymbol();
2944     MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
2945   }
2946 
2947   if (LowerInlineAsm) {
2948     if (!translateInlineAsm(I, MIRBuilder))
2949       return false;
2950   } else if (!translateCallBase(I, MIRBuilder))
2951     return false;
2952 
2953   MCSymbol *EndSymbol = nullptr;
2954   if (NeedEHLabel) {
2955     EndSymbol = Context.createTempSymbol();
2956     MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
2957   }
2958 
2959   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2960   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2961   MachineBasicBlock *InvokeMBB = &MIRBuilder.getMBB();
2962   BranchProbability EHPadBBProb =
2963       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2964           : BranchProbability::getZero();
2965 
2966   if (!findUnwindDestinations(EHPadBB, EHPadBBProb, UnwindDests))
2967     return false;
2968 
2969   MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
2970                     &ReturnMBB = getMBB(*ReturnBB);
2971   // Update successor info.
2972   addSuccessorWithProb(InvokeMBB, &ReturnMBB);
2973   for (auto &UnwindDest : UnwindDests) {
2974     UnwindDest.first->setIsEHPad();
2975     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2976   }
2977   InvokeMBB->normalizeSuccProbs();
2978 
2979   if (NeedEHLabel) {
2980     assert(BeginSymbol && "Expected a begin symbol!");
2981     assert(EndSymbol && "Expected an end symbol!");
2982     MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
2983   }
2984 
2985   MIRBuilder.buildBr(ReturnMBB);
2986   return true;
2987 }
2988 
2989 bool IRTranslator::translateCallBr(const User &U,
2990                                    MachineIRBuilder &MIRBuilder) {
2991   // FIXME: Implement this.
2992   return false;
2993 }
2994 
2995 bool IRTranslator::translateLandingPad(const User &U,
2996                                        MachineIRBuilder &MIRBuilder) {
2997   const LandingPadInst &LP = cast<LandingPadInst>(U);
2998 
2999   MachineBasicBlock &MBB = MIRBuilder.getMBB();
3000 
3001   MBB.setIsEHPad();
3002 
3003   // If there aren't registers to copy the values into (e.g., during SjLj
3004   // exceptions), then don't bother.
3005   const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
3006   if (TLI->getExceptionPointerRegister(PersonalityFn) == 0 &&
3007       TLI->getExceptionSelectorRegister(PersonalityFn) == 0)
3008     return true;
3009 
3010   // If landingpad's return type is token type, we don't create DAG nodes
3011   // for its exception pointer and selector value. The extraction of exception
3012   // pointer or selector value from token type landingpads is not currently
3013   // supported.
3014   if (LP.getType()->isTokenTy())
3015     return true;
3016 
3017   // Add a label to mark the beginning of the landing pad.  Deletion of the
3018   // landing pad can thus be detected via the MachineModuleInfo.
3019   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
3020     .addSym(MF->addLandingPad(&MBB));
3021 
3022   // If the unwinder does not preserve all registers, ensure that the
3023   // function marks the clobbered registers as used.
3024   const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
3025   if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
3026     MF->getRegInfo().addPhysRegsUsedFromRegMask(RegMask);
3027 
3028   LLT Ty = getLLTForType(*LP.getType(), *DL);
3029   Register Undef = MRI->createGenericVirtualRegister(Ty);
3030   MIRBuilder.buildUndef(Undef);
3031 
3032   SmallVector<LLT, 2> Tys;
3033   for (Type *Ty : cast<StructType>(LP.getType())->elements())
3034     Tys.push_back(getLLTForType(*Ty, *DL));
3035   assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
3036 
3037   // Mark exception register as live in.
3038   Register ExceptionReg = TLI->getExceptionPointerRegister(PersonalityFn);
3039   if (!ExceptionReg)
3040     return false;
3041 
3042   MBB.addLiveIn(ExceptionReg);
3043   ArrayRef<Register> ResRegs = getOrCreateVRegs(LP);
3044   MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
3045 
3046   Register SelectorReg = TLI->getExceptionSelectorRegister(PersonalityFn);
3047   if (!SelectorReg)
3048     return false;
3049 
3050   MBB.addLiveIn(SelectorReg);
3051   Register PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
3052   MIRBuilder.buildCopy(PtrVReg, SelectorReg);
3053   MIRBuilder.buildCast(ResRegs[1], PtrVReg);
3054 
3055   return true;
3056 }
3057 
3058 bool IRTranslator::translateAlloca(const User &U,
3059                                    MachineIRBuilder &MIRBuilder) {
3060   auto &AI = cast<AllocaInst>(U);
3061 
3062   if (AI.isSwiftError())
3063     return true;
3064 
3065   if (AI.isStaticAlloca()) {
3066     Register Res = getOrCreateVReg(AI);
3067     int FI = getOrCreateFrameIndex(AI);
3068     MIRBuilder.buildFrameIndex(Res, FI);
3069     return true;
3070   }
3071 
3072   // FIXME: support stack probing for Windows.
3073   if (MF->getTarget().getTargetTriple().isOSWindows())
3074     return false;
3075 
3076   // Now we're in the harder dynamic case.
3077   Register NumElts = getOrCreateVReg(*AI.getArraySize());
3078   Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
3079   LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
3080   if (MRI->getType(NumElts) != IntPtrTy) {
3081     Register ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
3082     MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
3083     NumElts = ExtElts;
3084   }
3085 
3086   Type *Ty = AI.getAllocatedType();
3087 
3088   Register AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
3089   Register TySize =
3090       getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, DL->getTypeAllocSize(Ty)));
3091   MIRBuilder.buildMul(AllocSize, NumElts, TySize);
3092 
3093   // Round the size of the allocation up to the stack alignment size
3094   // by add SA-1 to the size. This doesn't overflow because we're computing
3095   // an address inside an alloca.
3096   Align StackAlign = MF->getSubtarget().getFrameLowering()->getStackAlign();
3097   auto SAMinusOne = MIRBuilder.buildConstant(IntPtrTy, StackAlign.value() - 1);
3098   auto AllocAdd = MIRBuilder.buildAdd(IntPtrTy, AllocSize, SAMinusOne,
3099                                       MachineInstr::NoUWrap);
3100   auto AlignCst =
3101       MIRBuilder.buildConstant(IntPtrTy, ~(uint64_t)(StackAlign.value() - 1));
3102   auto AlignedAlloc = MIRBuilder.buildAnd(IntPtrTy, AllocAdd, AlignCst);
3103 
3104   Align Alignment = std::max(AI.getAlign(), DL->getPrefTypeAlign(Ty));
3105   if (Alignment <= StackAlign)
3106     Alignment = Align(1);
3107   MIRBuilder.buildDynStackAlloc(getOrCreateVReg(AI), AlignedAlloc, Alignment);
3108 
3109   MF->getFrameInfo().CreateVariableSizedObject(Alignment, &AI);
3110   assert(MF->getFrameInfo().hasVarSizedObjects());
3111   return true;
3112 }
3113 
3114 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
3115   // FIXME: We may need more info about the type. Because of how LLT works,
3116   // we're completely discarding the i64/double distinction here (amongst
3117   // others). Fortunately the ABIs I know of where that matters don't use va_arg
3118   // anyway but that's not guaranteed.
3119   MIRBuilder.buildInstr(TargetOpcode::G_VAARG, {getOrCreateVReg(U)},
3120                         {getOrCreateVReg(*U.getOperand(0)),
3121                          DL->getABITypeAlign(U.getType()).value()});
3122   return true;
3123 }
3124 
3125 bool IRTranslator::translateUnreachable(const User &U, MachineIRBuilder &MIRBuilder) {
3126   if (!MF->getTarget().Options.TrapUnreachable)
3127     return true;
3128 
3129   auto &UI = cast<UnreachableInst>(U);
3130 
3131   // We may be able to ignore unreachable behind a noreturn call.
3132   if (const CallInst *Call = dyn_cast_or_null<CallInst>(UI.getPrevNode());
3133       Call && Call->doesNotReturn()) {
3134     if (MF->getTarget().Options.NoTrapAfterNoreturn)
3135       return true;
3136     // Do not emit an additional trap instruction.
3137     if (Call->isNonContinuableTrap())
3138       return true;
3139   }
3140 
3141   MIRBuilder.buildTrap();
3142   return true;
3143 }
3144 
3145 bool IRTranslator::translateInsertElement(const User &U,
3146                                           MachineIRBuilder &MIRBuilder) {
3147   // If it is a <1 x Ty> vector, use the scalar as it is
3148   // not a legal vector type in LLT.
3149   if (auto *FVT = dyn_cast<FixedVectorType>(U.getType());
3150       FVT && FVT->getNumElements() == 1)
3151     return translateCopy(U, *U.getOperand(1), MIRBuilder);
3152 
3153   Register Res = getOrCreateVReg(U);
3154   Register Val = getOrCreateVReg(*U.getOperand(0));
3155   Register Elt = getOrCreateVReg(*U.getOperand(1));
3156   unsigned PreferredVecIdxWidth = TLI->getVectorIdxTy(*DL).getSizeInBits();
3157   Register Idx;
3158   if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(2))) {
3159     if (CI->getBitWidth() != PreferredVecIdxWidth) {
3160       APInt NewIdx = CI->getValue().zextOrTrunc(PreferredVecIdxWidth);
3161       auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
3162       Idx = getOrCreateVReg(*NewIdxCI);
3163     }
3164   }
3165   if (!Idx)
3166     Idx = getOrCreateVReg(*U.getOperand(2));
3167   if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
3168     const LLT VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
3169     Idx = MIRBuilder.buildZExtOrTrunc(VecIdxTy, Idx).getReg(0);
3170   }
3171   MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
3172   return true;
3173 }
3174 
3175 bool IRTranslator::translateInsertVector(const User &U,
3176                                          MachineIRBuilder &MIRBuilder) {
3177   Register Dst = getOrCreateVReg(U);
3178   Register Vec = getOrCreateVReg(*U.getOperand(0));
3179   Register Elt = getOrCreateVReg(*U.getOperand(1));
3180 
3181   ConstantInt *CI = cast<ConstantInt>(U.getOperand(2));
3182   unsigned PreferredVecIdxWidth = TLI->getVectorIdxTy(*DL).getSizeInBits();
3183 
3184   // Resize Index to preferred index width.
3185   if (CI->getBitWidth() != PreferredVecIdxWidth) {
3186     APInt NewIdx = CI->getValue().zextOrTrunc(PreferredVecIdxWidth);
3187     CI = ConstantInt::get(CI->getContext(), NewIdx);
3188   }
3189 
3190   // If it is a <1 x Ty> vector, we have to use other means.
3191   if (auto *ResultType = dyn_cast<FixedVectorType>(U.getOperand(1)->getType());
3192       ResultType && ResultType->getNumElements() == 1) {
3193     if (auto *InputType = dyn_cast<FixedVectorType>(U.getOperand(0)->getType());
3194         InputType && InputType->getNumElements() == 1) {
3195       // We are inserting an illegal fixed vector into an illegal
3196       // fixed vector, use the scalar as it is not a legal vector type
3197       // in LLT.
3198       return translateCopy(U, *U.getOperand(0), MIRBuilder);
3199     }
3200     if (isa<FixedVectorType>(U.getOperand(0)->getType())) {
3201       // We are inserting an illegal fixed vector into a legal fixed
3202       // vector, use the scalar as it is not a legal vector type in
3203       // LLT.
3204       Register Idx = getOrCreateVReg(*CI);
3205       MIRBuilder.buildInsertVectorElement(Dst, Vec, Elt, Idx);
3206       return true;
3207     }
3208     if (isa<ScalableVectorType>(U.getOperand(0)->getType())) {
3209       // We are inserting an illegal fixed vector into a scalable
3210       // vector, use a scalar element insert.
3211       LLT VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
3212       Register Idx = getOrCreateVReg(*CI);
3213       auto ScaledIndex = MIRBuilder.buildMul(
3214           VecIdxTy, MIRBuilder.buildVScale(VecIdxTy, 1), Idx);
3215       MIRBuilder.buildInsertVectorElement(Dst, Vec, Elt, ScaledIndex);
3216       return true;
3217     }
3218   }
3219 
3220   MIRBuilder.buildInsertSubvector(
3221       getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
3222       getOrCreateVReg(*U.getOperand(1)), CI->getZExtValue());
3223   return true;
3224 }
3225 
3226 bool IRTranslator::translateExtractElement(const User &U,
3227                                            MachineIRBuilder &MIRBuilder) {
3228   // If it is a <1 x Ty> vector, use the scalar as it is
3229   // not a legal vector type in LLT.
3230   if (cast<FixedVectorType>(U.getOperand(0)->getType())->getNumElements() == 1)
3231     return translateCopy(U, *U.getOperand(0), MIRBuilder);
3232 
3233   Register Res = getOrCreateVReg(U);
3234   Register Val = getOrCreateVReg(*U.getOperand(0));
3235   unsigned PreferredVecIdxWidth = TLI->getVectorIdxTy(*DL).getSizeInBits();
3236   Register Idx;
3237   if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) {
3238     if (CI->getBitWidth() != PreferredVecIdxWidth) {
3239       APInt NewIdx = CI->getValue().zextOrTrunc(PreferredVecIdxWidth);
3240       auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
3241       Idx = getOrCreateVReg(*NewIdxCI);
3242     }
3243   }
3244   if (!Idx)
3245     Idx = getOrCreateVReg(*U.getOperand(1));
3246   if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
3247     const LLT VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
3248     Idx = MIRBuilder.buildZExtOrTrunc(VecIdxTy, Idx).getReg(0);
3249   }
3250   MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
3251   return true;
3252 }
3253 
3254 bool IRTranslator::translateExtractVector(const User &U,
3255                                           MachineIRBuilder &MIRBuilder) {
3256   Register Res = getOrCreateVReg(U);
3257   Register Vec = getOrCreateVReg(*U.getOperand(0));
3258   ConstantInt *CI = cast<ConstantInt>(U.getOperand(1));
3259   unsigned PreferredVecIdxWidth = TLI->getVectorIdxTy(*DL).getSizeInBits();
3260 
3261   // Resize Index to preferred index width.
3262   if (CI->getBitWidth() != PreferredVecIdxWidth) {
3263     APInt NewIdx = CI->getValue().zextOrTrunc(PreferredVecIdxWidth);
3264     CI = ConstantInt::get(CI->getContext(), NewIdx);
3265   }
3266 
3267   // If it is a <1 x Ty> vector, we have to use other means.
3268   if (auto *ResultType = dyn_cast<FixedVectorType>(U.getType());
3269       ResultType && ResultType->getNumElements() == 1) {
3270     if (auto *InputType = dyn_cast<FixedVectorType>(U.getOperand(0)->getType());
3271         InputType && InputType->getNumElements() == 1) {
3272       // We are extracting an illegal fixed vector from an illegal fixed vector,
3273       // use the scalar as it is not a legal vector type in LLT.
3274       return translateCopy(U, *U.getOperand(0), MIRBuilder);
3275     }
3276     if (isa<FixedVectorType>(U.getOperand(0)->getType())) {
3277       // We are extracting an illegal fixed vector from a legal fixed
3278       // vector, use the scalar as it is not a legal vector type in
3279       // LLT.
3280       Register Idx = getOrCreateVReg(*CI);
3281       MIRBuilder.buildExtractVectorElement(Res, Vec, Idx);
3282       return true;
3283     }
3284     if (isa<ScalableVectorType>(U.getOperand(0)->getType())) {
3285       // We are extracting an illegal fixed vector from a scalable
3286       // vector, use a scalar element extract.
3287       LLT VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
3288       Register Idx = getOrCreateVReg(*CI);
3289       auto ScaledIndex = MIRBuilder.buildMul(
3290           VecIdxTy, MIRBuilder.buildVScale(VecIdxTy, 1), Idx);
3291       MIRBuilder.buildExtractVectorElement(Res, Vec, ScaledIndex);
3292       return true;
3293     }
3294   }
3295 
3296   MIRBuilder.buildExtractSubvector(getOrCreateVReg(U),
3297                                    getOrCreateVReg(*U.getOperand(0)),
3298                                    CI->getZExtValue());
3299   return true;
3300 }
3301 
3302 bool IRTranslator::translateShuffleVector(const User &U,
3303                                           MachineIRBuilder &MIRBuilder) {
3304   // A ShuffleVector that operates on scalable vectors is a splat vector where
3305   // the value of the splat vector is the 0th element of the first operand,
3306   // since the index mask operand is the zeroinitializer (undef and
3307   // poison are treated as zeroinitializer here).
3308   if (U.getOperand(0)->getType()->isScalableTy()) {
3309     Register Val = getOrCreateVReg(*U.getOperand(0));
3310     auto SplatVal = MIRBuilder.buildExtractVectorElementConstant(
3311         MRI->getType(Val).getElementType(), Val, 0);
3312     MIRBuilder.buildSplatVector(getOrCreateVReg(U), SplatVal);
3313     return true;
3314   }
3315 
3316   ArrayRef<int> Mask;
3317   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&U))
3318     Mask = SVI->getShuffleMask();
3319   else
3320     Mask = cast<ConstantExpr>(U).getShuffleMask();
3321   ArrayRef<int> MaskAlloc = MF->allocateShuffleMask(Mask);
3322   MIRBuilder
3323       .buildInstr(TargetOpcode::G_SHUFFLE_VECTOR, {getOrCreateVReg(U)},
3324                   {getOrCreateVReg(*U.getOperand(0)),
3325                    getOrCreateVReg(*U.getOperand(1))})
3326       .addShuffleMask(MaskAlloc);
3327   return true;
3328 }
3329 
3330 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
3331   const PHINode &PI = cast<PHINode>(U);
3332 
3333   SmallVector<MachineInstr *, 4> Insts;
3334   for (auto Reg : getOrCreateVRegs(PI)) {
3335     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {});
3336     Insts.push_back(MIB.getInstr());
3337   }
3338 
3339   PendingPHIs.emplace_back(&PI, std::move(Insts));
3340   return true;
3341 }
3342 
3343 bool IRTranslator::translateAtomicCmpXchg(const User &U,
3344                                           MachineIRBuilder &MIRBuilder) {
3345   const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
3346 
3347   auto Flags = TLI->getAtomicMemOperandFlags(I, *DL);
3348 
3349   auto Res = getOrCreateVRegs(I);
3350   Register OldValRes = Res[0];
3351   Register SuccessRes = Res[1];
3352   Register Addr = getOrCreateVReg(*I.getPointerOperand());
3353   Register Cmp = getOrCreateVReg(*I.getCompareOperand());
3354   Register NewVal = getOrCreateVReg(*I.getNewValOperand());
3355 
3356   MIRBuilder.buildAtomicCmpXchgWithSuccess(
3357       OldValRes, SuccessRes, Addr, Cmp, NewVal,
3358       *MF->getMachineMemOperand(
3359           MachinePointerInfo(I.getPointerOperand()), Flags, MRI->getType(Cmp),
3360           getMemOpAlign(I), I.getAAMetadata(), nullptr, I.getSyncScopeID(),
3361           I.getSuccessOrdering(), I.getFailureOrdering()));
3362   return true;
3363 }
3364 
3365 bool IRTranslator::translateAtomicRMW(const User &U,
3366                                       MachineIRBuilder &MIRBuilder) {
3367   const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
3368   auto Flags = TLI->getAtomicMemOperandFlags(I, *DL);
3369 
3370   Register Res = getOrCreateVReg(I);
3371   Register Addr = getOrCreateVReg(*I.getPointerOperand());
3372   Register Val = getOrCreateVReg(*I.getValOperand());
3373 
3374   unsigned Opcode = 0;
3375   switch (I.getOperation()) {
3376   default:
3377     return false;
3378   case AtomicRMWInst::Xchg:
3379     Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
3380     break;
3381   case AtomicRMWInst::Add:
3382     Opcode = TargetOpcode::G_ATOMICRMW_ADD;
3383     break;
3384   case AtomicRMWInst::Sub:
3385     Opcode = TargetOpcode::G_ATOMICRMW_SUB;
3386     break;
3387   case AtomicRMWInst::And:
3388     Opcode = TargetOpcode::G_ATOMICRMW_AND;
3389     break;
3390   case AtomicRMWInst::Nand:
3391     Opcode = TargetOpcode::G_ATOMICRMW_NAND;
3392     break;
3393   case AtomicRMWInst::Or:
3394     Opcode = TargetOpcode::G_ATOMICRMW_OR;
3395     break;
3396   case AtomicRMWInst::Xor:
3397     Opcode = TargetOpcode::G_ATOMICRMW_XOR;
3398     break;
3399   case AtomicRMWInst::Max:
3400     Opcode = TargetOpcode::G_ATOMICRMW_MAX;
3401     break;
3402   case AtomicRMWInst::Min:
3403     Opcode = TargetOpcode::G_ATOMICRMW_MIN;
3404     break;
3405   case AtomicRMWInst::UMax:
3406     Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
3407     break;
3408   case AtomicRMWInst::UMin:
3409     Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
3410     break;
3411   case AtomicRMWInst::FAdd:
3412     Opcode = TargetOpcode::G_ATOMICRMW_FADD;
3413     break;
3414   case AtomicRMWInst::FSub:
3415     Opcode = TargetOpcode::G_ATOMICRMW_FSUB;
3416     break;
3417   case AtomicRMWInst::FMax:
3418     Opcode = TargetOpcode::G_ATOMICRMW_FMAX;
3419     break;
3420   case AtomicRMWInst::FMin:
3421     Opcode = TargetOpcode::G_ATOMICRMW_FMIN;
3422     break;
3423   case AtomicRMWInst::UIncWrap:
3424     Opcode = TargetOpcode::G_ATOMICRMW_UINC_WRAP;
3425     break;
3426   case AtomicRMWInst::UDecWrap:
3427     Opcode = TargetOpcode::G_ATOMICRMW_UDEC_WRAP;
3428     break;
3429   case AtomicRMWInst::USubCond:
3430     Opcode = TargetOpcode::G_ATOMICRMW_USUB_COND;
3431     break;
3432   case AtomicRMWInst::USubSat:
3433     Opcode = TargetOpcode::G_ATOMICRMW_USUB_SAT;
3434     break;
3435   }
3436 
3437   MIRBuilder.buildAtomicRMW(
3438       Opcode, Res, Addr, Val,
3439       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
3440                                 Flags, MRI->getType(Val), getMemOpAlign(I),
3441                                 I.getAAMetadata(), nullptr, I.getSyncScopeID(),
3442                                 I.getOrdering()));
3443   return true;
3444 }
3445 
3446 bool IRTranslator::translateFence(const User &U,
3447                                   MachineIRBuilder &MIRBuilder) {
3448   const FenceInst &Fence = cast<FenceInst>(U);
3449   MIRBuilder.buildFence(static_cast<unsigned>(Fence.getOrdering()),
3450                         Fence.getSyncScopeID());
3451   return true;
3452 }
3453 
3454 bool IRTranslator::translateFreeze(const User &U,
3455                                    MachineIRBuilder &MIRBuilder) {
3456   const ArrayRef<Register> DstRegs = getOrCreateVRegs(U);
3457   const ArrayRef<Register> SrcRegs = getOrCreateVRegs(*U.getOperand(0));
3458 
3459   assert(DstRegs.size() == SrcRegs.size() &&
3460          "Freeze with different source and destination type?");
3461 
3462   for (unsigned I = 0; I < DstRegs.size(); ++I) {
3463     MIRBuilder.buildFreeze(DstRegs[I], SrcRegs[I]);
3464   }
3465 
3466   return true;
3467 }
3468 
3469 void IRTranslator::finishPendingPhis() {
3470 #ifndef NDEBUG
3471   DILocationVerifier Verifier;
3472   GISelObserverWrapper WrapperObserver(&Verifier);
3473   RAIIMFObsDelInstaller ObsInstall(*MF, WrapperObserver);
3474 #endif // ifndef NDEBUG
3475   for (auto &Phi : PendingPHIs) {
3476     const PHINode *PI = Phi.first;
3477     if (PI->getType()->isEmptyTy())
3478       continue;
3479     ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
3480     MachineBasicBlock *PhiMBB = ComponentPHIs[0]->getParent();
3481     EntryBuilder->setDebugLoc(PI->getDebugLoc());
3482 #ifndef NDEBUG
3483     Verifier.setCurrentInst(PI);
3484 #endif // ifndef NDEBUG
3485 
3486     SmallSet<const MachineBasicBlock *, 16> SeenPreds;
3487     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
3488       auto IRPred = PI->getIncomingBlock(i);
3489       ArrayRef<Register> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
3490       for (auto *Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
3491         if (SeenPreds.count(Pred) || !PhiMBB->isPredecessor(Pred))
3492           continue;
3493         SeenPreds.insert(Pred);
3494         for (unsigned j = 0; j < ValRegs.size(); ++j) {
3495           MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
3496           MIB.addUse(ValRegs[j]);
3497           MIB.addMBB(Pred);
3498         }
3499       }
3500     }
3501   }
3502 }
3503 
3504 void IRTranslator::translateDbgValueRecord(Value *V, bool HasArgList,
3505                                      const DILocalVariable *Variable,
3506                                      const DIExpression *Expression,
3507                                      const DebugLoc &DL,
3508                                      MachineIRBuilder &MIRBuilder) {
3509   assert(Variable->isValidLocationForIntrinsic(DL) &&
3510          "Expected inlined-at fields to agree");
3511   // Act as if we're handling a debug intrinsic.
3512   MIRBuilder.setDebugLoc(DL);
3513 
3514   if (!V || HasArgList) {
3515     // DI cannot produce a valid DBG_VALUE, so produce an undef DBG_VALUE to
3516     // terminate any prior location.
3517     MIRBuilder.buildIndirectDbgValue(0, Variable, Expression);
3518     return;
3519   }
3520 
3521   if (const auto *CI = dyn_cast<Constant>(V)) {
3522     MIRBuilder.buildConstDbgValue(*CI, Variable, Expression);
3523     return;
3524   }
3525 
3526   if (auto *AI = dyn_cast<AllocaInst>(V);
3527       AI && AI->isStaticAlloca() && Expression->startsWithDeref()) {
3528     // If the value is an alloca and the expression starts with a
3529     // dereference, track a stack slot instead of a register, as registers
3530     // may be clobbered.
3531     auto ExprOperands = Expression->getElements();
3532     auto *ExprDerefRemoved =
3533         DIExpression::get(AI->getContext(), ExprOperands.drop_front());
3534     MIRBuilder.buildFIDbgValue(getOrCreateFrameIndex(*AI), Variable,
3535                                ExprDerefRemoved);
3536     return;
3537   }
3538   if (translateIfEntryValueArgument(false, V, Variable, Expression, DL,
3539                                     MIRBuilder))
3540     return;
3541   for (Register Reg : getOrCreateVRegs(*V)) {
3542     // FIXME: This does not handle register-indirect values at offset 0. The
3543     // direct/indirect thing shouldn't really be handled by something as
3544     // implicit as reg+noreg vs reg+imm in the first place, but it seems
3545     // pretty baked in right now.
3546     MIRBuilder.buildDirectDbgValue(Reg, Variable, Expression);
3547   }
3548   return;
3549 }
3550 
3551 void IRTranslator::translateDbgDeclareRecord(Value *Address, bool HasArgList,
3552                                      const DILocalVariable *Variable,
3553                                      const DIExpression *Expression,
3554                                      const DebugLoc &DL,
3555                                      MachineIRBuilder &MIRBuilder) {
3556   if (!Address || isa<UndefValue>(Address)) {
3557     LLVM_DEBUG(dbgs() << "Dropping debug info for " << *Variable << "\n");
3558     return;
3559   }
3560 
3561   assert(Variable->isValidLocationForIntrinsic(DL) &&
3562          "Expected inlined-at fields to agree");
3563   auto AI = dyn_cast<AllocaInst>(Address);
3564   if (AI && AI->isStaticAlloca()) {
3565     // Static allocas are tracked at the MF level, no need for DBG_VALUE
3566     // instructions (in fact, they get ignored if they *do* exist).
3567     MF->setVariableDbgInfo(Variable, Expression,
3568                            getOrCreateFrameIndex(*AI), DL);
3569     return;
3570   }
3571 
3572   if (translateIfEntryValueArgument(true, Address, Variable,
3573                                     Expression, DL,
3574                                     MIRBuilder))
3575     return;
3576 
3577   // A dbg.declare describes the address of a source variable, so lower it
3578   // into an indirect DBG_VALUE.
3579   MIRBuilder.setDebugLoc(DL);
3580   MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address),
3581                                    Variable, Expression);
3582   return;
3583 }
3584 
3585 void IRTranslator::translateDbgInfo(const Instruction &Inst,
3586                                       MachineIRBuilder &MIRBuilder) {
3587   for (DbgRecord &DR : Inst.getDbgRecordRange()) {
3588     if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
3589       MIRBuilder.setDebugLoc(DLR->getDebugLoc());
3590       assert(DLR->getLabel() && "Missing label");
3591       assert(DLR->getLabel()->isValidLocationForIntrinsic(
3592                  MIRBuilder.getDebugLoc()) &&
3593              "Expected inlined-at fields to agree");
3594       MIRBuilder.buildDbgLabel(DLR->getLabel());
3595       continue;
3596     }
3597     DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
3598     const DILocalVariable *Variable = DVR.getVariable();
3599     const DIExpression *Expression = DVR.getExpression();
3600     Value *V = DVR.getVariableLocationOp(0);
3601     if (DVR.isDbgDeclare())
3602       translateDbgDeclareRecord(V, DVR.hasArgList(), Variable, Expression,
3603                                 DVR.getDebugLoc(), MIRBuilder);
3604     else
3605       translateDbgValueRecord(V, DVR.hasArgList(), Variable, Expression,
3606                               DVR.getDebugLoc(), MIRBuilder);
3607   }
3608 }
3609 
3610 bool IRTranslator::translate(const Instruction &Inst) {
3611   CurBuilder->setDebugLoc(Inst.getDebugLoc());
3612   CurBuilder->setPCSections(Inst.getMetadata(LLVMContext::MD_pcsections));
3613   CurBuilder->setMMRAMetadata(Inst.getMetadata(LLVMContext::MD_mmra));
3614 
3615   if (TLI->fallBackToDAGISel(Inst))
3616     return false;
3617 
3618   switch (Inst.getOpcode()) {
3619 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
3620   case Instruction::OPCODE:                                                    \
3621     return translate##OPCODE(Inst, *CurBuilder.get());
3622 #include "llvm/IR/Instruction.def"
3623   default:
3624     return false;
3625   }
3626 }
3627 
3628 bool IRTranslator::translate(const Constant &C, Register Reg) {
3629   // We only emit constants into the entry block from here. To prevent jumpy
3630   // debug behaviour remove debug line.
3631   if (auto CurrInstDL = CurBuilder->getDL())
3632     EntryBuilder->setDebugLoc(DebugLoc());
3633 
3634   if (auto CI = dyn_cast<ConstantInt>(&C))
3635     EntryBuilder->buildConstant(Reg, *CI);
3636   else if (auto CF = dyn_cast<ConstantFP>(&C))
3637     EntryBuilder->buildFConstant(Reg, *CF);
3638   else if (isa<UndefValue>(C))
3639     EntryBuilder->buildUndef(Reg);
3640   else if (isa<ConstantPointerNull>(C))
3641     EntryBuilder->buildConstant(Reg, 0);
3642   else if (auto GV = dyn_cast<GlobalValue>(&C))
3643     EntryBuilder->buildGlobalValue(Reg, GV);
3644   else if (auto CPA = dyn_cast<ConstantPtrAuth>(&C)) {
3645     Register Addr = getOrCreateVReg(*CPA->getPointer());
3646     Register AddrDisc = getOrCreateVReg(*CPA->getAddrDiscriminator());
3647     EntryBuilder->buildConstantPtrAuth(Reg, CPA, Addr, AddrDisc);
3648   } else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
3649     Constant &Elt = *CAZ->getElementValue(0u);
3650     if (isa<ScalableVectorType>(CAZ->getType())) {
3651       EntryBuilder->buildSplatVector(Reg, getOrCreateVReg(Elt));
3652       return true;
3653     }
3654     // Return the scalar if it is a <1 x Ty> vector.
3655     unsigned NumElts = CAZ->getElementCount().getFixedValue();
3656     if (NumElts == 1)
3657       return translateCopy(C, Elt, *EntryBuilder);
3658     // All elements are zero so we can just use the first one.
3659     EntryBuilder->buildSplatBuildVector(Reg, getOrCreateVReg(Elt));
3660   } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
3661     // Return the scalar if it is a <1 x Ty> vector.
3662     if (CV->getNumElements() == 1)
3663       return translateCopy(C, *CV->getElementAsConstant(0), *EntryBuilder);
3664     SmallVector<Register, 4> Ops;
3665     for (unsigned i = 0; i < CV->getNumElements(); ++i) {
3666       Constant &Elt = *CV->getElementAsConstant(i);
3667       Ops.push_back(getOrCreateVReg(Elt));
3668     }
3669     EntryBuilder->buildBuildVector(Reg, Ops);
3670   } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
3671     switch(CE->getOpcode()) {
3672 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
3673   case Instruction::OPCODE:                                                    \
3674     return translate##OPCODE(*CE, *EntryBuilder.get());
3675 #include "llvm/IR/Instruction.def"
3676     default:
3677       return false;
3678     }
3679   } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
3680     if (CV->getNumOperands() == 1)
3681       return translateCopy(C, *CV->getOperand(0), *EntryBuilder);
3682     SmallVector<Register, 4> Ops;
3683     for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
3684       Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
3685     }
3686     EntryBuilder->buildBuildVector(Reg, Ops);
3687   } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
3688     EntryBuilder->buildBlockAddress(Reg, BA);
3689   } else
3690     return false;
3691 
3692   return true;
3693 }
3694 
3695 bool IRTranslator::finalizeBasicBlock(const BasicBlock &BB,
3696                                       MachineBasicBlock &MBB) {
3697   for (auto &BTB : SL->BitTestCases) {
3698     // Emit header first, if it wasn't already emitted.
3699     if (!BTB.Emitted)
3700       emitBitTestHeader(BTB, BTB.Parent);
3701 
3702     BranchProbability UnhandledProb = BTB.Prob;
3703     for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
3704       UnhandledProb -= BTB.Cases[j].ExtraProb;
3705       // Set the current basic block to the mbb we wish to insert the code into
3706       MachineBasicBlock *MBB = BTB.Cases[j].ThisBB;
3707       // If all cases cover a contiguous range, it is not necessary to jump to
3708       // the default block after the last bit test fails. This is because the
3709       // range check during bit test header creation has guaranteed that every
3710       // case here doesn't go outside the range. In this case, there is no need
3711       // to perform the last bit test, as it will always be true. Instead, make
3712       // the second-to-last bit-test fall through to the target of the last bit
3713       // test, and delete the last bit test.
3714 
3715       MachineBasicBlock *NextMBB;
3716       if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
3717         // Second-to-last bit-test with contiguous range: fall through to the
3718         // target of the final bit test.
3719         NextMBB = BTB.Cases[j + 1].TargetBB;
3720       } else if (j + 1 == ej) {
3721         // For the last bit test, fall through to Default.
3722         NextMBB = BTB.Default;
3723       } else {
3724         // Otherwise, fall through to the next bit test.
3725         NextMBB = BTB.Cases[j + 1].ThisBB;
3726       }
3727 
3728       emitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j], MBB);
3729 
3730       if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
3731         // We need to record the replacement phi edge here that normally
3732         // happens in emitBitTestCase before we delete the case, otherwise the
3733         // phi edge will be lost.
3734         addMachineCFGPred({BTB.Parent->getBasicBlock(),
3735                            BTB.Cases[ej - 1].TargetBB->getBasicBlock()},
3736                           MBB);
3737         // Since we're not going to use the final bit test, remove it.
3738         BTB.Cases.pop_back();
3739         break;
3740       }
3741     }
3742     // This is "default" BB. We have two jumps to it. From "header" BB and from
3743     // last "case" BB, unless the latter was skipped.
3744     CFGEdge HeaderToDefaultEdge = {BTB.Parent->getBasicBlock(),
3745                                    BTB.Default->getBasicBlock()};
3746     addMachineCFGPred(HeaderToDefaultEdge, BTB.Parent);
3747     if (!BTB.ContiguousRange) {
3748       addMachineCFGPred(HeaderToDefaultEdge, BTB.Cases.back().ThisBB);
3749     }
3750   }
3751   SL->BitTestCases.clear();
3752 
3753   for (auto &JTCase : SL->JTCases) {
3754     // Emit header first, if it wasn't already emitted.
3755     if (!JTCase.first.Emitted)
3756       emitJumpTableHeader(JTCase.second, JTCase.first, JTCase.first.HeaderBB);
3757 
3758     emitJumpTable(JTCase.second, JTCase.second.MBB);
3759   }
3760   SL->JTCases.clear();
3761 
3762   for (auto &SwCase : SL->SwitchCases)
3763     emitSwitchCase(SwCase, &CurBuilder->getMBB(), *CurBuilder);
3764   SL->SwitchCases.clear();
3765 
3766   // Check if we need to generate stack-protector guard checks.
3767   StackProtector &SP = getAnalysis<StackProtector>();
3768   if (SP.shouldEmitSDCheck(BB)) {
3769     bool FunctionBasedInstrumentation =
3770         TLI->getSSPStackGuardCheck(*MF->getFunction().getParent());
3771     SPDescriptor.initialize(&BB, &MBB, FunctionBasedInstrumentation);
3772   }
3773   // Handle stack protector.
3774   if (SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
3775     LLVM_DEBUG(dbgs() << "Unimplemented stack protector case\n");
3776     return false;
3777   } else if (SPDescriptor.shouldEmitStackProtector()) {
3778     MachineBasicBlock *ParentMBB = SPDescriptor.getParentMBB();
3779     MachineBasicBlock *SuccessMBB = SPDescriptor.getSuccessMBB();
3780 
3781     // Find the split point to split the parent mbb. At the same time copy all
3782     // physical registers used in the tail of parent mbb into virtual registers
3783     // before the split point and back into physical registers after the split
3784     // point. This prevents us needing to deal with Live-ins and many other
3785     // register allocation issues caused by us splitting the parent mbb. The
3786     // register allocator will clean up said virtual copies later on.
3787     MachineBasicBlock::iterator SplitPoint = findSplitPointForStackProtector(
3788         ParentMBB, *MF->getSubtarget().getInstrInfo());
3789 
3790     // Splice the terminator of ParentMBB into SuccessMBB.
3791     SuccessMBB->splice(SuccessMBB->end(), ParentMBB, SplitPoint,
3792                        ParentMBB->end());
3793 
3794     // Add compare/jump on neq/jump to the parent BB.
3795     if (!emitSPDescriptorParent(SPDescriptor, ParentMBB))
3796       return false;
3797 
3798     // CodeGen Failure MBB if we have not codegened it yet.
3799     MachineBasicBlock *FailureMBB = SPDescriptor.getFailureMBB();
3800     if (FailureMBB->empty()) {
3801       if (!emitSPDescriptorFailure(SPDescriptor, FailureMBB))
3802         return false;
3803     }
3804 
3805     // Clear the Per-BB State.
3806     SPDescriptor.resetPerBBState();
3807   }
3808   return true;
3809 }
3810 
3811 bool IRTranslator::emitSPDescriptorParent(StackProtectorDescriptor &SPD,
3812                                           MachineBasicBlock *ParentBB) {
3813   CurBuilder->setInsertPt(*ParentBB, ParentBB->end());
3814   // First create the loads to the guard/stack slot for the comparison.
3815   Type *PtrIRTy = PointerType::getUnqual(MF->getFunction().getContext());
3816   const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
3817   LLT PtrMemTy = getLLTForMVT(TLI->getPointerMemTy(*DL));
3818 
3819   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3820   int FI = MFI.getStackProtectorIndex();
3821 
3822   Register Guard;
3823   Register StackSlotPtr = CurBuilder->buildFrameIndex(PtrTy, FI).getReg(0);
3824   const Module &M = *ParentBB->getParent()->getFunction().getParent();
3825   Align Align = DL->getPrefTypeAlign(PointerType::getUnqual(M.getContext()));
3826 
3827   // Generate code to load the content of the guard slot.
3828   Register GuardVal =
3829       CurBuilder
3830           ->buildLoad(PtrMemTy, StackSlotPtr,
3831                       MachinePointerInfo::getFixedStack(*MF, FI), Align,
3832                       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile)
3833           .getReg(0);
3834 
3835   if (TLI->useStackGuardXorFP()) {
3836     LLVM_DEBUG(dbgs() << "Stack protector xor'ing with FP not yet implemented");
3837     return false;
3838   }
3839 
3840   // Retrieve guard check function, nullptr if instrumentation is inlined.
3841   if (const Function *GuardCheckFn = TLI->getSSPStackGuardCheck(M)) {
3842     // This path is currently untestable on GlobalISel, since the only platform
3843     // that needs this seems to be Windows, and we fall back on that currently.
3844     // The code still lives here in case that changes.
3845     // Silence warning about unused variable until the code below that uses
3846     // 'GuardCheckFn' is enabled.
3847     (void)GuardCheckFn;
3848     return false;
3849 #if 0
3850     // The target provides a guard check function to validate the guard value.
3851     // Generate a call to that function with the content of the guard slot as
3852     // argument.
3853     FunctionType *FnTy = GuardCheckFn->getFunctionType();
3854     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3855     ISD::ArgFlagsTy Flags;
3856     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
3857       Flags.setInReg();
3858     CallLowering::ArgInfo GuardArgInfo(
3859         {GuardVal, FnTy->getParamType(0), {Flags}});
3860 
3861     CallLowering::CallLoweringInfo Info;
3862     Info.OrigArgs.push_back(GuardArgInfo);
3863     Info.CallConv = GuardCheckFn->getCallingConv();
3864     Info.Callee = MachineOperand::CreateGA(GuardCheckFn, 0);
3865     Info.OrigRet = {Register(), FnTy->getReturnType()};
3866     if (!CLI->lowerCall(MIRBuilder, Info)) {
3867       LLVM_DEBUG(dbgs() << "Failed to lower call to stack protector check\n");
3868       return false;
3869     }
3870     return true;
3871 #endif
3872   }
3873 
3874   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3875   // Otherwise, emit a volatile load to retrieve the stack guard value.
3876   if (TLI->useLoadStackGuardNode(*ParentBB->getBasicBlock()->getModule())) {
3877     Guard =
3878         MRI->createGenericVirtualRegister(LLT::scalar(PtrTy.getSizeInBits()));
3879     getStackGuard(Guard, *CurBuilder);
3880   } else {
3881     // TODO: test using android subtarget when we support @llvm.thread.pointer.
3882     const Value *IRGuard = TLI->getSDagStackGuard(M);
3883     Register GuardPtr = getOrCreateVReg(*IRGuard);
3884 
3885     Guard = CurBuilder
3886                 ->buildLoad(PtrMemTy, GuardPtr,
3887                             MachinePointerInfo::getFixedStack(*MF, FI), Align,
3888                             MachineMemOperand::MOLoad |
3889                                 MachineMemOperand::MOVolatile)
3890                 .getReg(0);
3891   }
3892 
3893   // Perform the comparison.
3894   auto Cmp =
3895       CurBuilder->buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), Guard, GuardVal);
3896   // If the guard/stackslot do not equal, branch to failure MBB.
3897   CurBuilder->buildBrCond(Cmp, *SPD.getFailureMBB());
3898   // Otherwise branch to success MBB.
3899   CurBuilder->buildBr(*SPD.getSuccessMBB());
3900   return true;
3901 }
3902 
3903 bool IRTranslator::emitSPDescriptorFailure(StackProtectorDescriptor &SPD,
3904                                            MachineBasicBlock *FailureBB) {
3905   CurBuilder->setInsertPt(*FailureBB, FailureBB->end());
3906 
3907   const RTLIB::Libcall Libcall = RTLIB::STACKPROTECTOR_CHECK_FAIL;
3908   const char *Name = TLI->getLibcallName(Libcall);
3909 
3910   CallLowering::CallLoweringInfo Info;
3911   Info.CallConv = TLI->getLibcallCallingConv(Libcall);
3912   Info.Callee = MachineOperand::CreateES(Name);
3913   Info.OrigRet = {Register(), Type::getVoidTy(MF->getFunction().getContext()),
3914                   0};
3915   if (!CLI->lowerCall(*CurBuilder, Info)) {
3916     LLVM_DEBUG(dbgs() << "Failed to lower call to stack protector fail\n");
3917     return false;
3918   }
3919 
3920   // Emit a trap instruction if we are required to do so.
3921   const TargetOptions &TargetOpts = TLI->getTargetMachine().Options;
3922   if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
3923     CurBuilder->buildInstr(TargetOpcode::G_TRAP);
3924 
3925   return true;
3926 }
3927 
3928 void IRTranslator::finalizeFunction() {
3929   // Release the memory used by the different maps we
3930   // needed during the translation.
3931   PendingPHIs.clear();
3932   VMap.reset();
3933   FrameIndices.clear();
3934   MachinePreds.clear();
3935   // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
3936   // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
3937   // destroying it twice (in ~IRTranslator() and ~LLVMContext())
3938   EntryBuilder.reset();
3939   CurBuilder.reset();
3940   FuncInfo.clear();
3941   SPDescriptor.resetPerFunctionState();
3942 }
3943 
3944 /// Returns true if a BasicBlock \p BB within a variadic function contains a
3945 /// variadic musttail call.
3946 static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB) {
3947   if (!IsVarArg)
3948     return false;
3949 
3950   // Walk the block backwards, because tail calls usually only appear at the end
3951   // of a block.
3952   return llvm::any_of(llvm::reverse(BB), [](const Instruction &I) {
3953     const auto *CI = dyn_cast<CallInst>(&I);
3954     return CI && CI->isMustTailCall();
3955   });
3956 }
3957 
3958 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
3959   MF = &CurMF;
3960   const Function &F = MF->getFunction();
3961   GISelCSEAnalysisWrapper &Wrapper =
3962       getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
3963   // Set the CSEConfig and run the analysis.
3964   GISelCSEInfo *CSEInfo = nullptr;
3965   TPC = &getAnalysis<TargetPassConfig>();
3966   bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences()
3967                        ? EnableCSEInIRTranslator
3968                        : TPC->isGISelCSEEnabled();
3969   TLI = MF->getSubtarget().getTargetLowering();
3970 
3971   if (EnableCSE) {
3972     EntryBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
3973     CSEInfo = &Wrapper.get(TPC->getCSEConfig());
3974     EntryBuilder->setCSEInfo(CSEInfo);
3975     CurBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
3976     CurBuilder->setCSEInfo(CSEInfo);
3977   } else {
3978     EntryBuilder = std::make_unique<MachineIRBuilder>();
3979     CurBuilder = std::make_unique<MachineIRBuilder>();
3980   }
3981   CLI = MF->getSubtarget().getCallLowering();
3982   CurBuilder->setMF(*MF);
3983   EntryBuilder->setMF(*MF);
3984   MRI = &MF->getRegInfo();
3985   DL = &F.getDataLayout();
3986   ORE = std::make_unique<OptimizationRemarkEmitter>(&F);
3987   const TargetMachine &TM = MF->getTarget();
3988   TM.resetTargetOptions(F);
3989   EnableOpts = OptLevel != CodeGenOptLevel::None && !skipFunction(F);
3990   FuncInfo.MF = MF;
3991   if (EnableOpts) {
3992     AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3993     FuncInfo.BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
3994   } else {
3995     AA = nullptr;
3996     FuncInfo.BPI = nullptr;
3997   }
3998 
3999   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
4000       MF->getFunction());
4001   LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
4002   FuncInfo.CanLowerReturn = CLI->checkReturnTypeForCallConv(*MF);
4003 
4004   SL = std::make_unique<GISelSwitchLowering>(this, FuncInfo);
4005   SL->init(*TLI, TM, *DL);
4006 
4007   assert(PendingPHIs.empty() && "stale PHIs");
4008 
4009   // Targets which want to use big endian can enable it using
4010   // enableBigEndian()
4011   if (!DL->isLittleEndian() && !CLI->enableBigEndian()) {
4012     // Currently we don't properly handle big endian code.
4013     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
4014                                F.getSubprogram(), &F.getEntryBlock());
4015     R << "unable to translate in big endian mode";
4016     reportTranslationError(*MF, *TPC, *ORE, R);
4017     return false;
4018   }
4019 
4020   // Release the per-function state when we return, whether we succeeded or not.
4021   auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
4022 
4023   // Setup a separate basic-block for the arguments and constants
4024   MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
4025   MF->push_back(EntryBB);
4026   EntryBuilder->setMBB(*EntryBB);
4027 
4028   DebugLoc DbgLoc = F.getEntryBlock().getFirstNonPHI()->getDebugLoc();
4029   SwiftError.setFunction(CurMF);
4030   SwiftError.createEntriesInEntryBlock(DbgLoc);
4031 
4032   bool IsVarArg = F.isVarArg();
4033   bool HasMustTailInVarArgFn = false;
4034 
4035   // Create all blocks, in IR order, to preserve the layout.
4036   FuncInfo.MBBMap.resize(F.getMaxBlockNumber());
4037   for (const BasicBlock &BB: F) {
4038     auto *&MBB = FuncInfo.MBBMap[BB.getNumber()];
4039 
4040     MBB = MF->CreateMachineBasicBlock(&BB);
4041     MF->push_back(MBB);
4042 
4043     if (BB.hasAddressTaken())
4044       MBB->setAddressTakenIRBlock(const_cast<BasicBlock *>(&BB));
4045 
4046     if (!HasMustTailInVarArgFn)
4047       HasMustTailInVarArgFn = checkForMustTailInVarArgFn(IsVarArg, BB);
4048   }
4049 
4050   MF->getFrameInfo().setHasMustTailInVarArgFunc(HasMustTailInVarArgFn);
4051 
4052   // Make our arguments/constants entry block fallthrough to the IR entry block.
4053   EntryBB->addSuccessor(&getMBB(F.front()));
4054 
4055   if (CLI->fallBackToDAGISel(*MF)) {
4056     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
4057                                F.getSubprogram(), &F.getEntryBlock());
4058     R << "unable to lower function: "
4059       << ore::NV("Prototype", F.getFunctionType());
4060     reportTranslationError(*MF, *TPC, *ORE, R);
4061     return false;
4062   }
4063 
4064   // Lower the actual args into this basic block.
4065   SmallVector<ArrayRef<Register>, 8> VRegArgs;
4066   for (const Argument &Arg: F.args()) {
4067     if (DL->getTypeStoreSize(Arg.getType()).isZero())
4068       continue; // Don't handle zero sized types.
4069     ArrayRef<Register> VRegs = getOrCreateVRegs(Arg);
4070     VRegArgs.push_back(VRegs);
4071 
4072     if (Arg.hasSwiftErrorAttr()) {
4073       assert(VRegs.size() == 1 && "Too many vregs for Swift error");
4074       SwiftError.setCurrentVReg(EntryBB, SwiftError.getFunctionArg(), VRegs[0]);
4075     }
4076   }
4077 
4078   if (!CLI->lowerFormalArguments(*EntryBuilder, F, VRegArgs, FuncInfo)) {
4079     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
4080                                F.getSubprogram(), &F.getEntryBlock());
4081     R << "unable to lower arguments: "
4082       << ore::NV("Prototype", F.getFunctionType());
4083     reportTranslationError(*MF, *TPC, *ORE, R);
4084     return false;
4085   }
4086 
4087   // Need to visit defs before uses when translating instructions.
4088   GISelObserverWrapper WrapperObserver;
4089   if (EnableCSE && CSEInfo)
4090     WrapperObserver.addObserver(CSEInfo);
4091   {
4092     ReversePostOrderTraversal<const Function *> RPOT(&F);
4093 #ifndef NDEBUG
4094     DILocationVerifier Verifier;
4095     WrapperObserver.addObserver(&Verifier);
4096 #endif // ifndef NDEBUG
4097     RAIIMFObsDelInstaller ObsInstall(*MF, WrapperObserver);
4098     for (const BasicBlock *BB : RPOT) {
4099       MachineBasicBlock &MBB = getMBB(*BB);
4100       // Set the insertion point of all the following translations to
4101       // the end of this basic block.
4102       CurBuilder->setMBB(MBB);
4103       HasTailCall = false;
4104       for (const Instruction &Inst : *BB) {
4105         // If we translated a tail call in the last step, then we know
4106         // everything after the call is either a return, or something that is
4107         // handled by the call itself. (E.g. a lifetime marker or assume
4108         // intrinsic.) In this case, we should stop translating the block and
4109         // move on.
4110         if (HasTailCall)
4111           break;
4112 #ifndef NDEBUG
4113         Verifier.setCurrentInst(&Inst);
4114 #endif // ifndef NDEBUG
4115 
4116         // Translate any debug-info attached to the instruction.
4117         translateDbgInfo(Inst, *CurBuilder);
4118 
4119         if (translate(Inst))
4120           continue;
4121 
4122         OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
4123                                    Inst.getDebugLoc(), BB);
4124         R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
4125 
4126         if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
4127           std::string InstStrStorage;
4128           raw_string_ostream InstStr(InstStrStorage);
4129           InstStr << Inst;
4130 
4131           R << ": '" << InstStrStorage << "'";
4132         }
4133 
4134         reportTranslationError(*MF, *TPC, *ORE, R);
4135         return false;
4136       }
4137 
4138       if (!finalizeBasicBlock(*BB, MBB)) {
4139         OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
4140                                    BB->getTerminator()->getDebugLoc(), BB);
4141         R << "unable to translate basic block";
4142         reportTranslationError(*MF, *TPC, *ORE, R);
4143         return false;
4144       }
4145     }
4146 #ifndef NDEBUG
4147     WrapperObserver.removeObserver(&Verifier);
4148 #endif
4149   }
4150 
4151   finishPendingPhis();
4152 
4153   SwiftError.propagateVRegs();
4154 
4155   // Merge the argument lowering and constants block with its single
4156   // successor, the LLVM-IR entry block.  We want the basic block to
4157   // be maximal.
4158   assert(EntryBB->succ_size() == 1 &&
4159          "Custom BB used for lowering should have only one successor");
4160   // Get the successor of the current entry block.
4161   MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
4162   assert(NewEntryBB.pred_size() == 1 &&
4163          "LLVM-IR entry block has a predecessor!?");
4164   // Move all the instruction from the current entry block to the
4165   // new entry block.
4166   NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
4167                     EntryBB->end());
4168 
4169   // Update the live-in information for the new entry block.
4170   for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
4171     NewEntryBB.addLiveIn(LiveIn);
4172   NewEntryBB.sortUniqueLiveIns();
4173 
4174   // Get rid of the now empty basic block.
4175   EntryBB->removeSuccessor(&NewEntryBB);
4176   MF->remove(EntryBB);
4177   MF->deleteMachineBasicBlock(EntryBB);
4178 
4179   assert(&MF->front() == &NewEntryBB &&
4180          "New entry wasn't next in the list of basic block!");
4181 
4182   // Initialize stack protector information.
4183   StackProtector &SP = getAnalysis<StackProtector>();
4184   SP.copyToMachineFrameInfo(MF->getFrameInfo());
4185 
4186   return false;
4187 }
4188