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