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