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