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/OptimizationRemarkEmitter.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/CodeGen/Analysis.h"
21 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
22 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
23 #include "llvm/CodeGen/LowLevelType.h"
24 #include "llvm/CodeGen/MachineBasicBlock.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/CodeGen/MachineOperand.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/StackProtector.h"
32 #include "llvm/CodeGen/TargetFrameLowering.h"
33 #include "llvm/CodeGen/TargetLowering.h"
34 #include "llvm/CodeGen/TargetPassConfig.h"
35 #include "llvm/CodeGen/TargetRegisterInfo.h"
36 #include "llvm/CodeGen/TargetSubtargetInfo.h"
37 #include "llvm/IR/BasicBlock.h"
38 #include "llvm/IR/CFG.h"
39 #include "llvm/IR/Constant.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/DebugInfo.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GetElementPtrTypeIterator.h"
46 #include "llvm/IR/InlineAsm.h"
47 #include "llvm/IR/InstrTypes.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/IntrinsicInst.h"
50 #include "llvm/IR/Intrinsics.h"
51 #include "llvm/IR/LLVMContext.h"
52 #include "llvm/IR/Metadata.h"
53 #include "llvm/IR/Type.h"
54 #include "llvm/IR/User.h"
55 #include "llvm/IR/Value.h"
56 #include "llvm/MC/MCContext.h"
57 #include "llvm/Pass.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CodeGen.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/LowLevelTypeImpl.h"
63 #include "llvm/Support/MathExtras.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include "llvm/Target/TargetIntrinsicInfo.h"
66 #include "llvm/Target/TargetMachine.h"
67 #include <algorithm>
68 #include <cassert>
69 #include <cstdint>
70 #include <iterator>
71 #include <string>
72 #include <utility>
73 #include <vector>
74 
75 #define DEBUG_TYPE "irtranslator"
76 
77 using namespace llvm;
78 
79 static cl::opt<bool>
80     EnableCSEInIRTranslator("enable-cse-in-irtranslator",
81                             cl::desc("Should enable CSE in irtranslator"),
82                             cl::Optional, cl::init(false));
83 char IRTranslator::ID = 0;
84 
85 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
86                 false, false)
87 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
88 INITIALIZE_PASS_DEPENDENCY(GISelCSEAnalysisWrapperPass)
89 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
90                 false, false)
91 
92 static void reportTranslationError(MachineFunction &MF,
93                                    const TargetPassConfig &TPC,
94                                    OptimizationRemarkEmitter &ORE,
95                                    OptimizationRemarkMissed &R) {
96   MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
97 
98   // Print the function name explicitly if we don't have a debug location (which
99   // makes the diagnostic less useful) or if we're going to emit a raw error.
100   if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
101     R << (" (in function: " + MF.getName() + ")").str();
102 
103   if (TPC.isGlobalISelAbortEnabled())
104     report_fatal_error(R.getMsg());
105   else
106     ORE.emit(R);
107 }
108 
109 IRTranslator::IRTranslator() : MachineFunctionPass(ID) {
110   initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
111 }
112 
113 #ifndef NDEBUG
114 namespace {
115 /// Verify that every instruction created has the same DILocation as the
116 /// instruction being translated.
117 class DILocationVerifier : public GISelChangeObserver {
118   const Instruction *CurrInst = nullptr;
119 
120 public:
121   DILocationVerifier() = default;
122   ~DILocationVerifier() = default;
123 
124   const Instruction *getCurrentInst() const { return CurrInst; }
125   void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; }
126 
127   void erasingInstr(MachineInstr &MI) override {}
128   void changingInstr(MachineInstr &MI) override {}
129   void changedInstr(MachineInstr &MI) override {}
130 
131   void createdInstr(MachineInstr &MI) override {
132     assert(getCurrentInst() && "Inserted instruction without a current MI");
133 
134     // Only print the check message if we're actually checking it.
135 #ifndef NDEBUG
136     LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst
137                       << " was copied to " << MI);
138 #endif
139     assert(CurrInst->getDebugLoc() == MI.getDebugLoc() &&
140            "Line info was not transferred to all instructions");
141   }
142 };
143 } // namespace
144 #endif // ifndef NDEBUG
145 
146 
147 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
148   AU.addRequired<StackProtector>();
149   AU.addRequired<TargetPassConfig>();
150   AU.addRequired<GISelCSEAnalysisWrapperPass>();
151   getSelectionDAGFallbackAnalysisUsage(AU);
152   MachineFunctionPass::getAnalysisUsage(AU);
153 }
154 
155 IRTranslator::ValueToVRegInfo::VRegListT &
156 IRTranslator::allocateVRegs(const Value &Val) {
157   assert(!VMap.contains(Val) && "Value already allocated in VMap");
158   auto *Regs = VMap.getVRegs(Val);
159   auto *Offsets = VMap.getOffsets(Val);
160   SmallVector<LLT, 4> SplitTys;
161   computeValueLLTs(*DL, *Val.getType(), SplitTys,
162                    Offsets->empty() ? Offsets : nullptr);
163   for (unsigned i = 0; i < SplitTys.size(); ++i)
164     Regs->push_back(0);
165   return *Regs;
166 }
167 
168 ArrayRef<unsigned> IRTranslator::getOrCreateVRegs(const Value &Val) {
169   auto VRegsIt = VMap.findVRegs(Val);
170   if (VRegsIt != VMap.vregs_end())
171     return *VRegsIt->second;
172 
173   if (Val.getType()->isVoidTy())
174     return *VMap.getVRegs(Val);
175 
176   // Create entry for this type.
177   auto *VRegs = VMap.getVRegs(Val);
178   auto *Offsets = VMap.getOffsets(Val);
179 
180   assert(Val.getType()->isSized() &&
181          "Don't know how to create an empty vreg");
182 
183   SmallVector<LLT, 4> SplitTys;
184   computeValueLLTs(*DL, *Val.getType(), SplitTys,
185                    Offsets->empty() ? Offsets : nullptr);
186 
187   if (!isa<Constant>(Val)) {
188     for (auto Ty : SplitTys)
189       VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
190     return *VRegs;
191   }
192 
193   if (Val.getType()->isAggregateType()) {
194     // UndefValue, ConstantAggregateZero
195     auto &C = cast<Constant>(Val);
196     unsigned Idx = 0;
197     while (auto Elt = C.getAggregateElement(Idx++)) {
198       auto EltRegs = getOrCreateVRegs(*Elt);
199       llvm::copy(EltRegs, std::back_inserter(*VRegs));
200     }
201   } else {
202     assert(SplitTys.size() == 1 && "unexpectedly split LLT");
203     VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
204     bool Success = translate(cast<Constant>(Val), VRegs->front());
205     if (!Success) {
206       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
207                                  MF->getFunction().getSubprogram(),
208                                  &MF->getFunction().getEntryBlock());
209       R << "unable to translate constant: " << ore::NV("Type", Val.getType());
210       reportTranslationError(*MF, *TPC, *ORE, R);
211       return *VRegs;
212     }
213   }
214 
215   return *VRegs;
216 }
217 
218 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
219   if (FrameIndices.find(&AI) != FrameIndices.end())
220     return FrameIndices[&AI];
221 
222   unsigned ElementSize = DL->getTypeAllocSize(AI.getAllocatedType());
223   unsigned Size =
224       ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
225 
226   // Always allocate at least one byte.
227   Size = std::max(Size, 1u);
228 
229   unsigned Alignment = AI.getAlignment();
230   if (!Alignment)
231     Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
232 
233   int &FI = FrameIndices[&AI];
234   FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
235   return FI;
236 }
237 
238 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
239   unsigned Alignment = 0;
240   Type *ValTy = nullptr;
241   if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
242     Alignment = SI->getAlignment();
243     ValTy = SI->getValueOperand()->getType();
244   } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
245     Alignment = LI->getAlignment();
246     ValTy = LI->getType();
247   } else if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
248     // TODO(PR27168): This instruction has no alignment attribute, but unlike
249     // the default alignment for load/store, the default here is to assume
250     // it has NATURAL alignment, not DataLayout-specified alignment.
251     const DataLayout &DL = AI->getModule()->getDataLayout();
252     Alignment = DL.getTypeStoreSize(AI->getCompareOperand()->getType());
253     ValTy = AI->getCompareOperand()->getType();
254   } else if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
255     // TODO(PR27168): This instruction has no alignment attribute, but unlike
256     // the default alignment for load/store, the default here is to assume
257     // it has NATURAL alignment, not DataLayout-specified alignment.
258     const DataLayout &DL = AI->getModule()->getDataLayout();
259     Alignment = DL.getTypeStoreSize(AI->getValOperand()->getType());
260     ValTy = AI->getType();
261   } else {
262     OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
263     R << "unable to translate memop: " << ore::NV("Opcode", &I);
264     reportTranslationError(*MF, *TPC, *ORE, R);
265     return 1;
266   }
267 
268   return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
269 }
270 
271 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
272   MachineBasicBlock *&MBB = BBToMBB[&BB];
273   assert(MBB && "BasicBlock was not encountered before");
274   return *MBB;
275 }
276 
277 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
278   assert(NewPred && "new predecessor must be a real MachineBasicBlock");
279   MachinePreds[Edge].push_back(NewPred);
280 }
281 
282 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
283                                      MachineIRBuilder &MIRBuilder) {
284   // FIXME: handle signed/unsigned wrapping flags.
285 
286   // Get or create a virtual register for each value.
287   // Unless the value is a Constant => loadimm cst?
288   // or inline constant each time?
289   // Creation of a virtual register needs to have a size.
290   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
291   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
292   unsigned Res = getOrCreateVReg(U);
293   uint16_t Flags = 0;
294   if (isa<Instruction>(U)) {
295     const Instruction &I = cast<Instruction>(U);
296     Flags = MachineInstr::copyFlagsFromInstruction(I);
297   }
298 
299   MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags);
300   return true;
301 }
302 
303 bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
304   // -0.0 - X --> G_FNEG
305   if (isa<Constant>(U.getOperand(0)) &&
306       U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
307     MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
308         .addDef(getOrCreateVReg(U))
309         .addUse(getOrCreateVReg(*U.getOperand(1)));
310     return true;
311   }
312   return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
313 }
314 
315 bool IRTranslator::translateFNeg(const User &U, MachineIRBuilder &MIRBuilder) {
316   MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
317       .addDef(getOrCreateVReg(U))
318       .addUse(getOrCreateVReg(*U.getOperand(0)));
319   return true;
320 }
321 
322 bool IRTranslator::translateCompare(const User &U,
323                                     MachineIRBuilder &MIRBuilder) {
324   const CmpInst *CI = dyn_cast<CmpInst>(&U);
325   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
326   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
327   unsigned Res = getOrCreateVReg(U);
328   CmpInst::Predicate Pred =
329       CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
330                                     cast<ConstantExpr>(U).getPredicate());
331   if (CmpInst::isIntPredicate(Pred))
332     MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
333   else if (Pred == CmpInst::FCMP_FALSE)
334     MIRBuilder.buildCopy(
335         Res, getOrCreateVReg(*Constant::getNullValue(CI->getType())));
336   else if (Pred == CmpInst::FCMP_TRUE)
337     MIRBuilder.buildCopy(
338         Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType())));
339   else {
340     MIRBuilder.buildInstr(TargetOpcode::G_FCMP, {Res}, {Pred, Op0, Op1},
341                           MachineInstr::copyFlagsFromInstruction(*CI));
342   }
343 
344   return true;
345 }
346 
347 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
348   const ReturnInst &RI = cast<ReturnInst>(U);
349   const Value *Ret = RI.getReturnValue();
350   if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
351     Ret = nullptr;
352 
353   ArrayRef<unsigned> VRegs;
354   if (Ret)
355     VRegs = getOrCreateVRegs(*Ret);
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 
361   return CLI->lowerReturn(MIRBuilder, Ret, VRegs);
362 }
363 
364 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
365   const BranchInst &BrInst = cast<BranchInst>(U);
366   unsigned Succ = 0;
367   if (!BrInst.isUnconditional()) {
368     // We want a G_BRCOND to the true BB followed by an unconditional branch.
369     unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
370     const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
371     MachineBasicBlock &TrueBB = getMBB(TrueTgt);
372     MIRBuilder.buildBrCond(Tst, TrueBB);
373   }
374 
375   const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
376   MachineBasicBlock &TgtBB = getMBB(BrTgt);
377   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
378 
379   // If the unconditional target is the layout successor, fallthrough.
380   if (!CurBB.isLayoutSuccessor(&TgtBB))
381     MIRBuilder.buildBr(TgtBB);
382 
383   // Link successors.
384   for (const BasicBlock *Succ : successors(&BrInst))
385     CurBB.addSuccessor(&getMBB(*Succ));
386   return true;
387 }
388 
389 bool IRTranslator::translateSwitch(const User &U,
390                                    MachineIRBuilder &MIRBuilder) {
391   // For now, just translate as a chain of conditional branches.
392   // FIXME: could we share most of the logic/code in
393   // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
394   // At first sight, it seems most of the logic in there is independent of
395   // SelectionDAG-specifics and a lot of work went in to optimize switch
396   // lowering in there.
397 
398   const SwitchInst &SwInst = cast<SwitchInst>(U);
399   const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
400   const BasicBlock *OrigBB = SwInst.getParent();
401 
402   LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
403   for (auto &CaseIt : SwInst.cases()) {
404     const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
405     const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
406     MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
407     MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
408     const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
409     MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
410 
411     MIRBuilder.buildBrCond(Tst, TrueMBB);
412     CurMBB.addSuccessor(&TrueMBB);
413     addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
414 
415     MachineBasicBlock *FalseMBB =
416         MF->CreateMachineBasicBlock(SwInst.getParent());
417     // Insert the comparison blocks one after the other.
418     MF->insert(std::next(CurMBB.getIterator()), FalseMBB);
419     MIRBuilder.buildBr(*FalseMBB);
420     CurMBB.addSuccessor(FalseMBB);
421 
422     MIRBuilder.setMBB(*FalseMBB);
423   }
424   // handle default case
425   const BasicBlock *DefaultBB = SwInst.getDefaultDest();
426   MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
427   MIRBuilder.buildBr(DefaultMBB);
428   MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
429   CurMBB.addSuccessor(&DefaultMBB);
430   addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
431 
432   return true;
433 }
434 
435 bool IRTranslator::translateIndirectBr(const User &U,
436                                        MachineIRBuilder &MIRBuilder) {
437   const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
438 
439   const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
440   MIRBuilder.buildBrIndirect(Tgt);
441 
442   // Link successors.
443   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
444   for (const BasicBlock *Succ : successors(&BrInst))
445     CurBB.addSuccessor(&getMBB(*Succ));
446 
447   return true;
448 }
449 
450 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
451   const LoadInst &LI = cast<LoadInst>(U);
452 
453   auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
454                                : MachineMemOperand::MONone;
455   Flags |= MachineMemOperand::MOLoad;
456 
457   if (DL->getTypeStoreSize(LI.getType()) == 0)
458     return true;
459 
460   ArrayRef<unsigned> Regs = getOrCreateVRegs(LI);
461   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
462   unsigned Base = getOrCreateVReg(*LI.getPointerOperand());
463 
464   for (unsigned i = 0; i < Regs.size(); ++i) {
465     unsigned Addr = 0;
466     MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
467 
468     MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
469     unsigned BaseAlign = getMemOpAlignment(LI);
470     auto MMO = MF->getMachineMemOperand(
471         Ptr, Flags, (MRI->getType(Regs[i]).getSizeInBits() + 7) / 8,
472         MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
473         LI.getSyncScopeID(), LI.getOrdering());
474     MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
475   }
476 
477   return true;
478 }
479 
480 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
481   const StoreInst &SI = cast<StoreInst>(U);
482   auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
483                                : MachineMemOperand::MONone;
484   Flags |= MachineMemOperand::MOStore;
485 
486   if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
487     return true;
488 
489   ArrayRef<unsigned> Vals = getOrCreateVRegs(*SI.getValueOperand());
490   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
491   unsigned Base = getOrCreateVReg(*SI.getPointerOperand());
492 
493   for (unsigned i = 0; i < Vals.size(); ++i) {
494     unsigned Addr = 0;
495     MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
496 
497     MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
498     unsigned BaseAlign = getMemOpAlignment(SI);
499     auto MMO = MF->getMachineMemOperand(
500         Ptr, Flags, (MRI->getType(Vals[i]).getSizeInBits() + 7) / 8,
501         MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
502         SI.getSyncScopeID(), SI.getOrdering());
503     MIRBuilder.buildStore(Vals[i], Addr, *MMO);
504   }
505   return true;
506 }
507 
508 static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
509   const Value *Src = U.getOperand(0);
510   Type *Int32Ty = Type::getInt32Ty(U.getContext());
511 
512   // getIndexedOffsetInType is designed for GEPs, so the first index is the
513   // usual array element rather than looking into the actual aggregate.
514   SmallVector<Value *, 1> Indices;
515   Indices.push_back(ConstantInt::get(Int32Ty, 0));
516 
517   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
518     for (auto Idx : EVI->indices())
519       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
520   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
521     for (auto Idx : IVI->indices())
522       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
523   } else {
524     for (unsigned i = 1; i < U.getNumOperands(); ++i)
525       Indices.push_back(U.getOperand(i));
526   }
527 
528   return 8 * static_cast<uint64_t>(
529                  DL.getIndexedOffsetInType(Src->getType(), Indices));
530 }
531 
532 bool IRTranslator::translateExtractValue(const User &U,
533                                          MachineIRBuilder &MIRBuilder) {
534   const Value *Src = U.getOperand(0);
535   uint64_t Offset = getOffsetFromIndices(U, *DL);
536   ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
537   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
538   unsigned Idx = llvm::lower_bound(Offsets, Offset) - Offsets.begin();
539   auto &DstRegs = allocateVRegs(U);
540 
541   for (unsigned i = 0; i < DstRegs.size(); ++i)
542     DstRegs[i] = SrcRegs[Idx++];
543 
544   return true;
545 }
546 
547 bool IRTranslator::translateInsertValue(const User &U,
548                                         MachineIRBuilder &MIRBuilder) {
549   const Value *Src = U.getOperand(0);
550   uint64_t Offset = getOffsetFromIndices(U, *DL);
551   auto &DstRegs = allocateVRegs(U);
552   ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
553   ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
554   ArrayRef<unsigned> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
555   auto InsertedIt = InsertedRegs.begin();
556 
557   for (unsigned i = 0; i < DstRegs.size(); ++i) {
558     if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
559       DstRegs[i] = *InsertedIt++;
560     else
561       DstRegs[i] = SrcRegs[i];
562   }
563 
564   return true;
565 }
566 
567 bool IRTranslator::translateSelect(const User &U,
568                                    MachineIRBuilder &MIRBuilder) {
569   unsigned Tst = getOrCreateVReg(*U.getOperand(0));
570   ArrayRef<unsigned> ResRegs = getOrCreateVRegs(U);
571   ArrayRef<unsigned> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
572   ArrayRef<unsigned> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
573 
574   const SelectInst &SI = cast<SelectInst>(U);
575   uint16_t Flags = 0;
576   if (const CmpInst *Cmp = dyn_cast<CmpInst>(SI.getCondition()))
577     Flags = MachineInstr::copyFlagsFromInstruction(*Cmp);
578 
579   for (unsigned i = 0; i < ResRegs.size(); ++i) {
580     MIRBuilder.buildInstr(TargetOpcode::G_SELECT, {ResRegs[i]},
581                           {Tst, Op0Regs[i], Op1Regs[i]}, Flags);
582   }
583 
584   return true;
585 }
586 
587 bool IRTranslator::translateBitCast(const User &U,
588                                     MachineIRBuilder &MIRBuilder) {
589   // If we're bitcasting to the source type, we can reuse the source vreg.
590   if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
591       getLLTForType(*U.getType(), *DL)) {
592     unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
593     auto &Regs = *VMap.getVRegs(U);
594     // If we already assigned a vreg for this bitcast, we can't change that.
595     // Emit a copy to satisfy the users we already emitted.
596     if (!Regs.empty())
597       MIRBuilder.buildCopy(Regs[0], SrcReg);
598     else {
599       Regs.push_back(SrcReg);
600       VMap.getOffsets(U)->push_back(0);
601     }
602     return true;
603   }
604   return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
605 }
606 
607 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
608                                  MachineIRBuilder &MIRBuilder) {
609   unsigned Op = getOrCreateVReg(*U.getOperand(0));
610   unsigned Res = getOrCreateVReg(U);
611   MIRBuilder.buildInstr(Opcode, {Res}, {Op});
612   return true;
613 }
614 
615 bool IRTranslator::translateGetElementPtr(const User &U,
616                                           MachineIRBuilder &MIRBuilder) {
617   // FIXME: support vector GEPs.
618   if (U.getType()->isVectorTy())
619     return false;
620 
621   Value &Op0 = *U.getOperand(0);
622   unsigned BaseReg = getOrCreateVReg(Op0);
623   Type *PtrIRTy = Op0.getType();
624   LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
625   Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
626   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
627 
628   int64_t Offset = 0;
629   for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
630        GTI != E; ++GTI) {
631     const Value *Idx = GTI.getOperand();
632     if (StructType *StTy = GTI.getStructTypeOrNull()) {
633       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
634       Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
635       continue;
636     } else {
637       uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
638 
639       // If this is a scalar constant or a splat vector of constants,
640       // handle it quickly.
641       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
642         Offset += ElementSize * CI->getSExtValue();
643         continue;
644       }
645 
646       if (Offset != 0) {
647         unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
648         LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
649         auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset);
650         MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetMIB.getReg(0));
651 
652         BaseReg = NewBaseReg;
653         Offset = 0;
654       }
655 
656       unsigned IdxReg = getOrCreateVReg(*Idx);
657       if (MRI->getType(IdxReg) != OffsetTy) {
658         unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
659         MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
660         IdxReg = NewIdxReg;
661       }
662 
663       // N = N + Idx * ElementSize;
664       // Avoid doing it for ElementSize of 1.
665       unsigned GepOffsetReg;
666       if (ElementSize != 1) {
667         GepOffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
668         auto ElementSizeMIB = MIRBuilder.buildConstant(
669             getLLTForType(*OffsetIRTy, *DL), ElementSize);
670         MIRBuilder.buildMul(GepOffsetReg, ElementSizeMIB.getReg(0), IdxReg);
671       } else
672         GepOffsetReg = IdxReg;
673 
674       unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
675       MIRBuilder.buildGEP(NewBaseReg, BaseReg, GepOffsetReg);
676       BaseReg = NewBaseReg;
677     }
678   }
679 
680   if (Offset != 0) {
681     auto OffsetMIB =
682         MIRBuilder.buildConstant(getLLTForType(*OffsetIRTy, *DL), Offset);
683     MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0));
684     return true;
685   }
686 
687   MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
688   return true;
689 }
690 
691 bool IRTranslator::translateMemfunc(const CallInst &CI,
692                                     MachineIRBuilder &MIRBuilder,
693                                     unsigned ID) {
694   LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
695   Type *DstTy = CI.getArgOperand(0)->getType();
696   if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
697       SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
698     return false;
699 
700   SmallVector<CallLowering::ArgInfo, 8> Args;
701   for (int i = 0; i < 3; ++i) {
702     const auto &Arg = CI.getArgOperand(i);
703     Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
704   }
705 
706   const char *Callee;
707   switch (ID) {
708   case Intrinsic::memmove:
709   case Intrinsic::memcpy: {
710     Type *SrcTy = CI.getArgOperand(1)->getType();
711     if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
712       return false;
713     Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
714     break;
715   }
716   case Intrinsic::memset:
717     Callee = "memset";
718     break;
719   default:
720     return false;
721   }
722 
723   return CLI->lowerCall(MIRBuilder, CI.getCallingConv(),
724                         MachineOperand::CreateES(Callee),
725                         CallLowering::ArgInfo(0, CI.getType()), Args);
726 }
727 
728 void IRTranslator::getStackGuard(unsigned DstReg,
729                                  MachineIRBuilder &MIRBuilder) {
730   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
731   MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
732   auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
733   MIB.addDef(DstReg);
734 
735   auto &TLI = *MF->getSubtarget().getTargetLowering();
736   Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
737   if (!Global)
738     return;
739 
740   MachinePointerInfo MPInfo(Global);
741   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
742                MachineMemOperand::MODereferenceable;
743   MachineMemOperand *MemRef =
744       MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
745                                DL->getPointerABIAlignment(0));
746   MIB.setMemRefs({MemRef});
747 }
748 
749 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
750                                               MachineIRBuilder &MIRBuilder) {
751   ArrayRef<unsigned> ResRegs = getOrCreateVRegs(CI);
752   MIRBuilder.buildInstr(Op)
753       .addDef(ResRegs[0])
754       .addDef(ResRegs[1])
755       .addUse(getOrCreateVReg(*CI.getOperand(0)))
756       .addUse(getOrCreateVReg(*CI.getOperand(1)));
757 
758   return true;
759 }
760 
761 unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) {
762   switch (ID) {
763     default:
764       break;
765     case Intrinsic::bswap:
766       return TargetOpcode::G_BSWAP;
767     case Intrinsic::ceil:
768       return TargetOpcode::G_FCEIL;
769     case Intrinsic::cos:
770       return TargetOpcode::G_FCOS;
771     case Intrinsic::ctpop:
772       return TargetOpcode::G_CTPOP;
773     case Intrinsic::exp:
774       return TargetOpcode::G_FEXP;
775     case Intrinsic::exp2:
776       return TargetOpcode::G_FEXP2;
777     case Intrinsic::fabs:
778       return TargetOpcode::G_FABS;
779     case Intrinsic::canonicalize:
780       return TargetOpcode::G_FCANONICALIZE;
781     case Intrinsic::floor:
782       return TargetOpcode::G_FFLOOR;
783     case Intrinsic::fma:
784       return TargetOpcode::G_FMA;
785     case Intrinsic::log:
786       return TargetOpcode::G_FLOG;
787     case Intrinsic::log2:
788       return TargetOpcode::G_FLOG2;
789     case Intrinsic::log10:
790       return TargetOpcode::G_FLOG10;
791     case Intrinsic::nearbyint:
792       return TargetOpcode::G_FNEARBYINT;
793     case Intrinsic::pow:
794       return TargetOpcode::G_FPOW;
795     case Intrinsic::rint:
796       return TargetOpcode::G_FRINT;
797     case Intrinsic::round:
798       return TargetOpcode::G_INTRINSIC_ROUND;
799     case Intrinsic::sin:
800       return TargetOpcode::G_FSIN;
801     case Intrinsic::sqrt:
802       return TargetOpcode::G_FSQRT;
803     case Intrinsic::trunc:
804       return TargetOpcode::G_INTRINSIC_TRUNC;
805   }
806   return Intrinsic::not_intrinsic;
807 }
808 
809 bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI,
810                                             Intrinsic::ID ID,
811                                             MachineIRBuilder &MIRBuilder) {
812 
813   unsigned Op = getSimpleIntrinsicOpcode(ID);
814 
815   // Is this a simple intrinsic?
816   if (Op == Intrinsic::not_intrinsic)
817     return false;
818 
819   // Yes. Let's translate it.
820   SmallVector<llvm::SrcOp, 4> VRegs;
821   for (auto &Arg : CI.arg_operands())
822     VRegs.push_back(getOrCreateVReg(*Arg));
823 
824   MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
825                         MachineInstr::copyFlagsFromInstruction(CI));
826   return true;
827 }
828 
829 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
830                                            MachineIRBuilder &MIRBuilder) {
831 
832   // If this is a simple intrinsic (that is, we just need to add a def of
833   // a vreg, and uses for each arg operand, then translate it.
834   if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
835     return true;
836 
837   switch (ID) {
838   default:
839     break;
840   case Intrinsic::lifetime_start:
841   case Intrinsic::lifetime_end: {
842     // No stack colouring in O0, discard region information.
843     if (MF->getTarget().getOptLevel() == CodeGenOpt::None)
844       return true;
845 
846     unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START
847                                                   : TargetOpcode::LIFETIME_END;
848 
849     // Get the underlying objects for the location passed on the lifetime
850     // marker.
851     SmallVector<const Value *, 4> Allocas;
852     GetUnderlyingObjects(CI.getArgOperand(1), Allocas, *DL);
853 
854     // Iterate over each underlying object, creating lifetime markers for each
855     // static alloca. Quit if we find a non-static alloca.
856     for (const Value *V : Allocas) {
857       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
858       if (!AI)
859         continue;
860 
861       if (!AI->isStaticAlloca())
862         return true;
863 
864       MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI));
865     }
866     return true;
867   }
868   case Intrinsic::dbg_declare: {
869     const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
870     assert(DI.getVariable() && "Missing variable");
871 
872     const Value *Address = DI.getAddress();
873     if (!Address || isa<UndefValue>(Address)) {
874       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
875       return true;
876     }
877 
878     assert(DI.getVariable()->isValidLocationForIntrinsic(
879                MIRBuilder.getDebugLoc()) &&
880            "Expected inlined-at fields to agree");
881     auto AI = dyn_cast<AllocaInst>(Address);
882     if (AI && AI->isStaticAlloca()) {
883       // Static allocas are tracked at the MF level, no need for DBG_VALUE
884       // instructions (in fact, they get ignored if they *do* exist).
885       MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
886                              getOrCreateFrameIndex(*AI), DI.getDebugLoc());
887     } else {
888       // A dbg.declare describes the address of a source variable, so lower it
889       // into an indirect DBG_VALUE.
890       MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address),
891                                        DI.getVariable(), DI.getExpression());
892     }
893     return true;
894   }
895   case Intrinsic::dbg_label: {
896     const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
897     assert(DI.getLabel() && "Missing label");
898 
899     assert(DI.getLabel()->isValidLocationForIntrinsic(
900                MIRBuilder.getDebugLoc()) &&
901            "Expected inlined-at fields to agree");
902 
903     MIRBuilder.buildDbgLabel(DI.getLabel());
904     return true;
905   }
906   case Intrinsic::vaend:
907     // No target I know of cares about va_end. Certainly no in-tree target
908     // does. Simplest intrinsic ever!
909     return true;
910   case Intrinsic::vastart: {
911     auto &TLI = *MF->getSubtarget().getTargetLowering();
912     Value *Ptr = CI.getArgOperand(0);
913     unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
914 
915     // FIXME: Get alignment
916     MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
917         .addUse(getOrCreateVReg(*Ptr))
918         .addMemOperand(MF->getMachineMemOperand(
919             MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 1));
920     return true;
921   }
922   case Intrinsic::dbg_value: {
923     // This form of DBG_VALUE is target-independent.
924     const DbgValueInst &DI = cast<DbgValueInst>(CI);
925     const Value *V = DI.getValue();
926     assert(DI.getVariable()->isValidLocationForIntrinsic(
927                MIRBuilder.getDebugLoc()) &&
928            "Expected inlined-at fields to agree");
929     if (!V) {
930       // Currently the optimizer can produce this; insert an undef to
931       // help debugging.  Probably the optimizer should not do this.
932       MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
933     } else if (const auto *CI = dyn_cast<Constant>(V)) {
934       MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
935     } else {
936       unsigned Reg = getOrCreateVReg(*V);
937       // FIXME: This does not handle register-indirect values at offset 0. The
938       // direct/indirect thing shouldn't really be handled by something as
939       // implicit as reg+noreg vs reg+imm in the first palce, but it seems
940       // pretty baked in right now.
941       MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
942     }
943     return true;
944   }
945   case Intrinsic::uadd_with_overflow:
946     return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
947   case Intrinsic::sadd_with_overflow:
948     return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
949   case Intrinsic::usub_with_overflow:
950     return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
951   case Intrinsic::ssub_with_overflow:
952     return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
953   case Intrinsic::umul_with_overflow:
954     return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
955   case Intrinsic::smul_with_overflow:
956     return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
957   case Intrinsic::fmuladd: {
958     const TargetMachine &TM = MF->getTarget();
959     const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
960     unsigned Dst = getOrCreateVReg(CI);
961     unsigned Op0 = getOrCreateVReg(*CI.getArgOperand(0));
962     unsigned Op1 = getOrCreateVReg(*CI.getArgOperand(1));
963     unsigned Op2 = getOrCreateVReg(*CI.getArgOperand(2));
964     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
965         TLI.isFMAFasterThanFMulAndFAdd(TLI.getValueType(*DL, CI.getType()))) {
966       // TODO: Revisit this to see if we should move this part of the
967       // lowering to the combiner.
968       MIRBuilder.buildInstr(TargetOpcode::G_FMA, {Dst}, {Op0, Op1, Op2},
969                             MachineInstr::copyFlagsFromInstruction(CI));
970     } else {
971       LLT Ty = getLLTForType(*CI.getType(), *DL);
972       auto FMul = MIRBuilder.buildInstr(TargetOpcode::G_FMUL, {Ty}, {Op0, Op1},
973                                         MachineInstr::copyFlagsFromInstruction(CI));
974       MIRBuilder.buildInstr(TargetOpcode::G_FADD, {Dst}, {FMul, Op2},
975                             MachineInstr::copyFlagsFromInstruction(CI));
976     }
977     return true;
978   }
979   case Intrinsic::memcpy:
980   case Intrinsic::memmove:
981   case Intrinsic::memset:
982     return translateMemfunc(CI, MIRBuilder, ID);
983   case Intrinsic::eh_typeid_for: {
984     GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
985     unsigned Reg = getOrCreateVReg(CI);
986     unsigned TypeID = MF->getTypeIDFor(GV);
987     MIRBuilder.buildConstant(Reg, TypeID);
988     return true;
989   }
990   case Intrinsic::objectsize: {
991     // If we don't know by now, we're never going to know.
992     const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
993 
994     MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
995     return true;
996   }
997   case Intrinsic::is_constant:
998     // If this wasn't constant-folded away by now, then it's not a
999     // constant.
1000     MIRBuilder.buildConstant(getOrCreateVReg(CI), 0);
1001     return true;
1002   case Intrinsic::stackguard:
1003     getStackGuard(getOrCreateVReg(CI), MIRBuilder);
1004     return true;
1005   case Intrinsic::stackprotector: {
1006     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1007     unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
1008     getStackGuard(GuardVal, MIRBuilder);
1009 
1010     AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
1011     int FI = getOrCreateFrameIndex(*Slot);
1012     MF->getFrameInfo().setStackProtectorIndex(FI);
1013 
1014     MIRBuilder.buildStore(
1015         GuardVal, getOrCreateVReg(*Slot),
1016         *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
1017                                   MachineMemOperand::MOStore |
1018                                       MachineMemOperand::MOVolatile,
1019                                   PtrTy.getSizeInBits() / 8, 8));
1020     return true;
1021   }
1022   case Intrinsic::stacksave: {
1023     // Save the stack pointer to the location provided by the intrinsic.
1024     unsigned Reg = getOrCreateVReg(CI);
1025     unsigned StackPtr = MF->getSubtarget()
1026                             .getTargetLowering()
1027                             ->getStackPointerRegisterToSaveRestore();
1028 
1029     // If the target doesn't specify a stack pointer, then fall back.
1030     if (!StackPtr)
1031       return false;
1032 
1033     MIRBuilder.buildCopy(Reg, StackPtr);
1034     return true;
1035   }
1036   case Intrinsic::stackrestore: {
1037     // Restore the stack pointer from the location provided by the intrinsic.
1038     unsigned Reg = getOrCreateVReg(*CI.getArgOperand(0));
1039     unsigned StackPtr = MF->getSubtarget()
1040                             .getTargetLowering()
1041                             ->getStackPointerRegisterToSaveRestore();
1042 
1043     // If the target doesn't specify a stack pointer, then fall back.
1044     if (!StackPtr)
1045       return false;
1046 
1047     MIRBuilder.buildCopy(StackPtr, Reg);
1048     return true;
1049   }
1050   case Intrinsic::cttz:
1051   case Intrinsic::ctlz: {
1052     ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
1053     bool isTrailing = ID == Intrinsic::cttz;
1054     unsigned Opcode = isTrailing
1055                           ? Cst->isZero() ? TargetOpcode::G_CTTZ
1056                                           : TargetOpcode::G_CTTZ_ZERO_UNDEF
1057                           : Cst->isZero() ? TargetOpcode::G_CTLZ
1058                                           : TargetOpcode::G_CTLZ_ZERO_UNDEF;
1059     MIRBuilder.buildInstr(Opcode)
1060         .addDef(getOrCreateVReg(CI))
1061         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
1062     return true;
1063   }
1064   case Intrinsic::invariant_start: {
1065     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1066     unsigned Undef = MRI->createGenericVirtualRegister(PtrTy);
1067     MIRBuilder.buildUndef(Undef);
1068     return true;
1069   }
1070   case Intrinsic::invariant_end:
1071     return true;
1072   }
1073   return false;
1074 }
1075 
1076 bool IRTranslator::translateInlineAsm(const CallInst &CI,
1077                                       MachineIRBuilder &MIRBuilder) {
1078   const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
1079   if (!IA.getConstraintString().empty())
1080     return false;
1081 
1082   unsigned ExtraInfo = 0;
1083   if (IA.hasSideEffects())
1084     ExtraInfo |= InlineAsm::Extra_HasSideEffects;
1085   if (IA.getDialect() == InlineAsm::AD_Intel)
1086     ExtraInfo |= InlineAsm::Extra_AsmDialect;
1087 
1088   MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
1089     .addExternalSymbol(IA.getAsmString().c_str())
1090     .addImm(ExtraInfo);
1091 
1092   return true;
1093 }
1094 
1095 unsigned IRTranslator::packRegs(const Value &V,
1096                                   MachineIRBuilder &MIRBuilder) {
1097   ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
1098   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
1099   LLT BigTy = getLLTForType(*V.getType(), *DL);
1100 
1101   if (Regs.size() == 1)
1102     return Regs[0];
1103 
1104   unsigned Dst = MRI->createGenericVirtualRegister(BigTy);
1105   MIRBuilder.buildUndef(Dst);
1106   for (unsigned i = 0; i < Regs.size(); ++i) {
1107     unsigned NewDst = MRI->createGenericVirtualRegister(BigTy);
1108     MIRBuilder.buildInsert(NewDst, Dst, Regs[i], Offsets[i]);
1109     Dst = NewDst;
1110   }
1111   return Dst;
1112 }
1113 
1114 void IRTranslator::unpackRegs(const Value &V, unsigned Src,
1115                                 MachineIRBuilder &MIRBuilder) {
1116   ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
1117   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
1118 
1119   for (unsigned i = 0; i < Regs.size(); ++i)
1120     MIRBuilder.buildExtract(Regs[i], Src, Offsets[i]);
1121 }
1122 
1123 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
1124   const CallInst &CI = cast<CallInst>(U);
1125   auto TII = MF->getTarget().getIntrinsicInfo();
1126   const Function *F = CI.getCalledFunction();
1127 
1128   // FIXME: support Windows dllimport function calls.
1129   if (F && F->hasDLLImportStorageClass())
1130     return false;
1131 
1132   if (CI.isInlineAsm())
1133     return translateInlineAsm(CI, MIRBuilder);
1134 
1135   Intrinsic::ID ID = Intrinsic::not_intrinsic;
1136   if (F && F->isIntrinsic()) {
1137     ID = F->getIntrinsicID();
1138     if (TII && ID == Intrinsic::not_intrinsic)
1139       ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
1140   }
1141 
1142   if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) {
1143     bool IsSplitType = valueIsSplit(CI);
1144     unsigned Res = IsSplitType ? MRI->createGenericVirtualRegister(
1145                                      getLLTForType(*CI.getType(), *DL))
1146                                : getOrCreateVReg(CI);
1147 
1148     SmallVector<unsigned, 8> Args;
1149     for (auto &Arg: CI.arg_operands())
1150       Args.push_back(packRegs(*Arg, MIRBuilder));
1151 
1152     MF->getFrameInfo().setHasCalls(true);
1153     bool Success = CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
1154       return getOrCreateVReg(*CI.getCalledValue());
1155     });
1156 
1157     if (IsSplitType)
1158       unpackRegs(CI, Res, MIRBuilder);
1159     return Success;
1160   }
1161 
1162   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
1163 
1164   if (translateKnownIntrinsic(CI, ID, MIRBuilder))
1165     return true;
1166 
1167   ArrayRef<unsigned> ResultRegs;
1168   if (!CI.getType()->isVoidTy())
1169     ResultRegs = getOrCreateVRegs(CI);
1170 
1171   MachineInstrBuilder MIB =
1172       MIRBuilder.buildIntrinsic(ID, ResultRegs, !CI.doesNotAccessMemory());
1173   if (isa<FPMathOperator>(CI))
1174     MIB->copyIRFlags(CI);
1175 
1176   for (auto &Arg : CI.arg_operands()) {
1177     // Some intrinsics take metadata parameters. Reject them.
1178     if (isa<MetadataAsValue>(Arg))
1179       return false;
1180     MIB.addUse(packRegs(*Arg, MIRBuilder));
1181   }
1182 
1183   // Add a MachineMemOperand if it is a target mem intrinsic.
1184   const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1185   TargetLowering::IntrinsicInfo Info;
1186   // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
1187   if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
1188     unsigned Align = Info.align;
1189     if (Align == 0)
1190       Align = DL->getABITypeAlignment(Info.memVT.getTypeForEVT(F->getContext()));
1191 
1192     uint64_t Size = Info.memVT.getStoreSize();
1193     MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
1194                                                Info.flags, Size, Align));
1195   }
1196 
1197   return true;
1198 }
1199 
1200 bool IRTranslator::translateInvoke(const User &U,
1201                                    MachineIRBuilder &MIRBuilder) {
1202   const InvokeInst &I = cast<InvokeInst>(U);
1203   MCContext &Context = MF->getContext();
1204 
1205   const BasicBlock *ReturnBB = I.getSuccessor(0);
1206   const BasicBlock *EHPadBB = I.getSuccessor(1);
1207 
1208   const Value *Callee = I.getCalledValue();
1209   const Function *Fn = dyn_cast<Function>(Callee);
1210   if (isa<InlineAsm>(Callee))
1211     return false;
1212 
1213   // FIXME: support invoking patchpoint and statepoint intrinsics.
1214   if (Fn && Fn->isIntrinsic())
1215     return false;
1216 
1217   // FIXME: support whatever these are.
1218   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
1219     return false;
1220 
1221   // FIXME: support Windows exception handling.
1222   if (!isa<LandingPadInst>(EHPadBB->front()))
1223     return false;
1224 
1225   // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
1226   // the region covered by the try.
1227   MCSymbol *BeginSymbol = Context.createTempSymbol();
1228   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
1229 
1230   unsigned Res = 0;
1231   if (!I.getType()->isVoidTy())
1232     Res = MRI->createGenericVirtualRegister(getLLTForType(*I.getType(), *DL));
1233   SmallVector<unsigned, 8> Args;
1234   for (auto &Arg: I.arg_operands())
1235     Args.push_back(packRegs(*Arg, MIRBuilder));
1236 
1237   if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
1238                       [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
1239     return false;
1240 
1241   unpackRegs(I, Res, MIRBuilder);
1242 
1243   MCSymbol *EndSymbol = Context.createTempSymbol();
1244   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
1245 
1246   // FIXME: track probabilities.
1247   MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
1248                     &ReturnMBB = getMBB(*ReturnBB);
1249   MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
1250   MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
1251   MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
1252   MIRBuilder.buildBr(ReturnMBB);
1253 
1254   return true;
1255 }
1256 
1257 bool IRTranslator::translateCallBr(const User &U,
1258                                    MachineIRBuilder &MIRBuilder) {
1259   // FIXME: Implement this.
1260   return false;
1261 }
1262 
1263 bool IRTranslator::translateLandingPad(const User &U,
1264                                        MachineIRBuilder &MIRBuilder) {
1265   const LandingPadInst &LP = cast<LandingPadInst>(U);
1266 
1267   MachineBasicBlock &MBB = MIRBuilder.getMBB();
1268 
1269   MBB.setIsEHPad();
1270 
1271   // If there aren't registers to copy the values into (e.g., during SjLj
1272   // exceptions), then don't bother.
1273   auto &TLI = *MF->getSubtarget().getTargetLowering();
1274   const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
1275   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
1276       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
1277     return true;
1278 
1279   // If landingpad's return type is token type, we don't create DAG nodes
1280   // for its exception pointer and selector value. The extraction of exception
1281   // pointer or selector value from token type landingpads is not currently
1282   // supported.
1283   if (LP.getType()->isTokenTy())
1284     return true;
1285 
1286   // Add a label to mark the beginning of the landing pad.  Deletion of the
1287   // landing pad can thus be detected via the MachineModuleInfo.
1288   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
1289     .addSym(MF->addLandingPad(&MBB));
1290 
1291   LLT Ty = getLLTForType(*LP.getType(), *DL);
1292   unsigned Undef = MRI->createGenericVirtualRegister(Ty);
1293   MIRBuilder.buildUndef(Undef);
1294 
1295   SmallVector<LLT, 2> Tys;
1296   for (Type *Ty : cast<StructType>(LP.getType())->elements())
1297     Tys.push_back(getLLTForType(*Ty, *DL));
1298   assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
1299 
1300   // Mark exception register as live in.
1301   unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
1302   if (!ExceptionReg)
1303     return false;
1304 
1305   MBB.addLiveIn(ExceptionReg);
1306   ArrayRef<unsigned> ResRegs = getOrCreateVRegs(LP);
1307   MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
1308 
1309   unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
1310   if (!SelectorReg)
1311     return false;
1312 
1313   MBB.addLiveIn(SelectorReg);
1314   unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
1315   MIRBuilder.buildCopy(PtrVReg, SelectorReg);
1316   MIRBuilder.buildCast(ResRegs[1], PtrVReg);
1317 
1318   return true;
1319 }
1320 
1321 bool IRTranslator::translateAlloca(const User &U,
1322                                    MachineIRBuilder &MIRBuilder) {
1323   auto &AI = cast<AllocaInst>(U);
1324 
1325   if (AI.isSwiftError())
1326     return false;
1327 
1328   if (AI.isStaticAlloca()) {
1329     unsigned Res = getOrCreateVReg(AI);
1330     int FI = getOrCreateFrameIndex(AI);
1331     MIRBuilder.buildFrameIndex(Res, FI);
1332     return true;
1333   }
1334 
1335   // FIXME: support stack probing for Windows.
1336   if (MF->getTarget().getTargetTriple().isOSWindows())
1337     return false;
1338 
1339   // Now we're in the harder dynamic case.
1340   Type *Ty = AI.getAllocatedType();
1341   unsigned Align =
1342       std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
1343 
1344   unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
1345 
1346   Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
1347   LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
1348   if (MRI->getType(NumElts) != IntPtrTy) {
1349     unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
1350     MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
1351     NumElts = ExtElts;
1352   }
1353 
1354   unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
1355   unsigned TySize =
1356       getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
1357   MIRBuilder.buildMul(AllocSize, NumElts, TySize);
1358 
1359   LLT PtrTy = getLLTForType(*AI.getType(), *DL);
1360   auto &TLI = *MF->getSubtarget().getTargetLowering();
1361   unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1362 
1363   unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
1364   MIRBuilder.buildCopy(SPTmp, SPReg);
1365 
1366   unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
1367   MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
1368 
1369   // Handle alignment. We have to realign if the allocation granule was smaller
1370   // than stack alignment, or the specific alloca requires more than stack
1371   // alignment.
1372   unsigned StackAlign =
1373       MF->getSubtarget().getFrameLowering()->getStackAlignment();
1374   Align = std::max(Align, StackAlign);
1375   if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
1376     // Round the size of the allocation up to the stack alignment size
1377     // by add SA-1 to the size. This doesn't overflow because we're computing
1378     // an address inside an alloca.
1379     unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
1380     MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
1381     AllocTmp = AlignedAlloc;
1382   }
1383 
1384   MIRBuilder.buildCopy(SPReg, AllocTmp);
1385   MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
1386 
1387   MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
1388   assert(MF->getFrameInfo().hasVarSizedObjects());
1389   return true;
1390 }
1391 
1392 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
1393   // FIXME: We may need more info about the type. Because of how LLT works,
1394   // we're completely discarding the i64/double distinction here (amongst
1395   // others). Fortunately the ABIs I know of where that matters don't use va_arg
1396   // anyway but that's not guaranteed.
1397   MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
1398     .addDef(getOrCreateVReg(U))
1399     .addUse(getOrCreateVReg(*U.getOperand(0)))
1400     .addImm(DL->getABITypeAlignment(U.getType()));
1401   return true;
1402 }
1403 
1404 bool IRTranslator::translateInsertElement(const User &U,
1405                                           MachineIRBuilder &MIRBuilder) {
1406   // If it is a <1 x Ty> vector, use the scalar as it is
1407   // not a legal vector type in LLT.
1408   if (U.getType()->getVectorNumElements() == 1) {
1409     unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1410     auto &Regs = *VMap.getVRegs(U);
1411     if (Regs.empty()) {
1412       Regs.push_back(Elt);
1413       VMap.getOffsets(U)->push_back(0);
1414     } else {
1415       MIRBuilder.buildCopy(Regs[0], Elt);
1416     }
1417     return true;
1418   }
1419 
1420   unsigned Res = getOrCreateVReg(U);
1421   unsigned Val = getOrCreateVReg(*U.getOperand(0));
1422   unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1423   unsigned Idx = getOrCreateVReg(*U.getOperand(2));
1424   MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
1425   return true;
1426 }
1427 
1428 bool IRTranslator::translateExtractElement(const User &U,
1429                                            MachineIRBuilder &MIRBuilder) {
1430   // If it is a <1 x Ty> vector, use the scalar as it is
1431   // not a legal vector type in LLT.
1432   if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
1433     unsigned Elt = getOrCreateVReg(*U.getOperand(0));
1434     auto &Regs = *VMap.getVRegs(U);
1435     if (Regs.empty()) {
1436       Regs.push_back(Elt);
1437       VMap.getOffsets(U)->push_back(0);
1438     } else {
1439       MIRBuilder.buildCopy(Regs[0], Elt);
1440     }
1441     return true;
1442   }
1443   unsigned Res = getOrCreateVReg(U);
1444   unsigned Val = getOrCreateVReg(*U.getOperand(0));
1445   const auto &TLI = *MF->getSubtarget().getTargetLowering();
1446   unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits();
1447   unsigned Idx = 0;
1448   if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) {
1449     if (CI->getBitWidth() != PreferredVecIdxWidth) {
1450       APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth);
1451       auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
1452       Idx = getOrCreateVReg(*NewIdxCI);
1453     }
1454   }
1455   if (!Idx)
1456     Idx = getOrCreateVReg(*U.getOperand(1));
1457   if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
1458     const LLT &VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
1459     Idx = MIRBuilder.buildSExtOrTrunc(VecIdxTy, Idx)->getOperand(0).getReg();
1460   }
1461   MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
1462   return true;
1463 }
1464 
1465 bool IRTranslator::translateShuffleVector(const User &U,
1466                                           MachineIRBuilder &MIRBuilder) {
1467   MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
1468       .addDef(getOrCreateVReg(U))
1469       .addUse(getOrCreateVReg(*U.getOperand(0)))
1470       .addUse(getOrCreateVReg(*U.getOperand(1)))
1471       .addUse(getOrCreateVReg(*U.getOperand(2)));
1472   return true;
1473 }
1474 
1475 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
1476   const PHINode &PI = cast<PHINode>(U);
1477 
1478   SmallVector<MachineInstr *, 4> Insts;
1479   for (auto Reg : getOrCreateVRegs(PI)) {
1480     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {});
1481     Insts.push_back(MIB.getInstr());
1482   }
1483 
1484   PendingPHIs.emplace_back(&PI, std::move(Insts));
1485   return true;
1486 }
1487 
1488 bool IRTranslator::translateAtomicCmpXchg(const User &U,
1489                                           MachineIRBuilder &MIRBuilder) {
1490   const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
1491 
1492   if (I.isWeak())
1493     return false;
1494 
1495   auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1496                               : MachineMemOperand::MONone;
1497   Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1498 
1499   Type *ResType = I.getType();
1500   Type *ValType = ResType->Type::getStructElementType(0);
1501 
1502   auto Res = getOrCreateVRegs(I);
1503   unsigned OldValRes = Res[0];
1504   unsigned SuccessRes = Res[1];
1505   unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1506   unsigned Cmp = getOrCreateVReg(*I.getCompareOperand());
1507   unsigned NewVal = getOrCreateVReg(*I.getNewValOperand());
1508 
1509   MIRBuilder.buildAtomicCmpXchgWithSuccess(
1510       OldValRes, SuccessRes, Addr, Cmp, NewVal,
1511       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1512                                 Flags, DL->getTypeStoreSize(ValType),
1513                                 getMemOpAlignment(I), AAMDNodes(), nullptr,
1514                                 I.getSyncScopeID(), I.getSuccessOrdering(),
1515                                 I.getFailureOrdering()));
1516   return true;
1517 }
1518 
1519 bool IRTranslator::translateAtomicRMW(const User &U,
1520                                       MachineIRBuilder &MIRBuilder) {
1521   const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
1522 
1523   auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1524                               : MachineMemOperand::MONone;
1525   Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1526 
1527   Type *ResType = I.getType();
1528 
1529   unsigned Res = getOrCreateVReg(I);
1530   unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1531   unsigned Val = getOrCreateVReg(*I.getValOperand());
1532 
1533   unsigned Opcode = 0;
1534   switch (I.getOperation()) {
1535   default:
1536     llvm_unreachable("Unknown atomicrmw op");
1537     return false;
1538   case AtomicRMWInst::Xchg:
1539     Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
1540     break;
1541   case AtomicRMWInst::Add:
1542     Opcode = TargetOpcode::G_ATOMICRMW_ADD;
1543     break;
1544   case AtomicRMWInst::Sub:
1545     Opcode = TargetOpcode::G_ATOMICRMW_SUB;
1546     break;
1547   case AtomicRMWInst::And:
1548     Opcode = TargetOpcode::G_ATOMICRMW_AND;
1549     break;
1550   case AtomicRMWInst::Nand:
1551     Opcode = TargetOpcode::G_ATOMICRMW_NAND;
1552     break;
1553   case AtomicRMWInst::Or:
1554     Opcode = TargetOpcode::G_ATOMICRMW_OR;
1555     break;
1556   case AtomicRMWInst::Xor:
1557     Opcode = TargetOpcode::G_ATOMICRMW_XOR;
1558     break;
1559   case AtomicRMWInst::Max:
1560     Opcode = TargetOpcode::G_ATOMICRMW_MAX;
1561     break;
1562   case AtomicRMWInst::Min:
1563     Opcode = TargetOpcode::G_ATOMICRMW_MIN;
1564     break;
1565   case AtomicRMWInst::UMax:
1566     Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
1567     break;
1568   case AtomicRMWInst::UMin:
1569     Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
1570     break;
1571   }
1572 
1573   MIRBuilder.buildAtomicRMW(
1574       Opcode, Res, Addr, Val,
1575       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1576                                 Flags, DL->getTypeStoreSize(ResType),
1577                                 getMemOpAlignment(I), AAMDNodes(), nullptr,
1578                                 I.getSyncScopeID(), I.getOrdering()));
1579   return true;
1580 }
1581 
1582 void IRTranslator::finishPendingPhis() {
1583 #ifndef NDEBUG
1584   DILocationVerifier Verifier;
1585   GISelObserverWrapper WrapperObserver(&Verifier);
1586   RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
1587 #endif // ifndef NDEBUG
1588   for (auto &Phi : PendingPHIs) {
1589     const PHINode *PI = Phi.first;
1590     ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
1591     EntryBuilder->setDebugLoc(PI->getDebugLoc());
1592 #ifndef NDEBUG
1593     Verifier.setCurrentInst(PI);
1594 #endif // ifndef NDEBUG
1595 
1596     // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
1597     // won't create extra control flow here, otherwise we need to find the
1598     // dominating predecessor here (or perhaps force the weirder IRTranslators
1599     // to provide a simple boundary).
1600     SmallSet<const BasicBlock *, 4> HandledPreds;
1601 
1602     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
1603       auto IRPred = PI->getIncomingBlock(i);
1604       if (HandledPreds.count(IRPred))
1605         continue;
1606 
1607       HandledPreds.insert(IRPred);
1608       ArrayRef<unsigned> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
1609       for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
1610         assert(Pred->isSuccessor(ComponentPHIs[0]->getParent()) &&
1611                "incorrect CFG at MachineBasicBlock level");
1612         for (unsigned j = 0; j < ValRegs.size(); ++j) {
1613           MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
1614           MIB.addUse(ValRegs[j]);
1615           MIB.addMBB(Pred);
1616         }
1617       }
1618     }
1619   }
1620 }
1621 
1622 bool IRTranslator::valueIsSplit(const Value &V,
1623                                 SmallVectorImpl<uint64_t> *Offsets) {
1624   SmallVector<LLT, 4> SplitTys;
1625   if (Offsets && !Offsets->empty())
1626     Offsets->clear();
1627   computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
1628   return SplitTys.size() > 1;
1629 }
1630 
1631 bool IRTranslator::translate(const Instruction &Inst) {
1632   CurBuilder->setDebugLoc(Inst.getDebugLoc());
1633   EntryBuilder->setDebugLoc(Inst.getDebugLoc());
1634   switch(Inst.getOpcode()) {
1635 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
1636   case Instruction::OPCODE:                                                    \
1637     return translate##OPCODE(Inst, *CurBuilder.get());
1638 #include "llvm/IR/Instruction.def"
1639   default:
1640     return false;
1641   }
1642 }
1643 
1644 bool IRTranslator::translate(const Constant &C, unsigned Reg) {
1645   if (auto CI = dyn_cast<ConstantInt>(&C))
1646     EntryBuilder->buildConstant(Reg, *CI);
1647   else if (auto CF = dyn_cast<ConstantFP>(&C))
1648     EntryBuilder->buildFConstant(Reg, *CF);
1649   else if (isa<UndefValue>(C))
1650     EntryBuilder->buildUndef(Reg);
1651   else if (isa<ConstantPointerNull>(C)) {
1652     // As we are trying to build a constant val of 0 into a pointer,
1653     // insert a cast to make them correct with respect to types.
1654     unsigned NullSize = DL->getTypeSizeInBits(C.getType());
1655     auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize);
1656     auto *ZeroVal = ConstantInt::get(ZeroTy, 0);
1657     unsigned ZeroReg = getOrCreateVReg(*ZeroVal);
1658     EntryBuilder->buildCast(Reg, ZeroReg);
1659   } else if (auto GV = dyn_cast<GlobalValue>(&C))
1660     EntryBuilder->buildGlobalValue(Reg, GV);
1661   else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
1662     if (!CAZ->getType()->isVectorTy())
1663       return false;
1664     // Return the scalar if it is a <1 x Ty> vector.
1665     if (CAZ->getNumElements() == 1)
1666       return translate(*CAZ->getElementValue(0u), Reg);
1667     SmallVector<unsigned, 4> Ops;
1668     for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
1669       Constant &Elt = *CAZ->getElementValue(i);
1670       Ops.push_back(getOrCreateVReg(Elt));
1671     }
1672     EntryBuilder->buildBuildVector(Reg, Ops);
1673   } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
1674     // Return the scalar if it is a <1 x Ty> vector.
1675     if (CV->getNumElements() == 1)
1676       return translate(*CV->getElementAsConstant(0), Reg);
1677     SmallVector<unsigned, 4> Ops;
1678     for (unsigned i = 0; i < CV->getNumElements(); ++i) {
1679       Constant &Elt = *CV->getElementAsConstant(i);
1680       Ops.push_back(getOrCreateVReg(Elt));
1681     }
1682     EntryBuilder->buildBuildVector(Reg, Ops);
1683   } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
1684     switch(CE->getOpcode()) {
1685 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
1686   case Instruction::OPCODE:                                                    \
1687     return translate##OPCODE(*CE, *EntryBuilder.get());
1688 #include "llvm/IR/Instruction.def"
1689     default:
1690       return false;
1691     }
1692   } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
1693     if (CV->getNumOperands() == 1)
1694       return translate(*CV->getOperand(0), Reg);
1695     SmallVector<unsigned, 4> Ops;
1696     for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
1697       Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
1698     }
1699     EntryBuilder->buildBuildVector(Reg, Ops);
1700   } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
1701     EntryBuilder->buildBlockAddress(Reg, BA);
1702   } else
1703     return false;
1704 
1705   return true;
1706 }
1707 
1708 void IRTranslator::finalizeFunction() {
1709   // Release the memory used by the different maps we
1710   // needed during the translation.
1711   PendingPHIs.clear();
1712   VMap.reset();
1713   FrameIndices.clear();
1714   MachinePreds.clear();
1715   // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
1716   // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
1717   // destroying it twice (in ~IRTranslator() and ~LLVMContext())
1718   EntryBuilder.reset();
1719   CurBuilder.reset();
1720 }
1721 
1722 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1723   MF = &CurMF;
1724   const Function &F = MF->getFunction();
1725   if (F.empty())
1726     return false;
1727   GISelCSEAnalysisWrapper &Wrapper =
1728       getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
1729   // Set the CSEConfig and run the analysis.
1730   GISelCSEInfo *CSEInfo = nullptr;
1731   TPC = &getAnalysis<TargetPassConfig>();
1732   bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences()
1733                        ? EnableCSEInIRTranslator
1734                        : TPC->isGISelCSEEnabled();
1735 
1736   if (EnableCSE) {
1737     EntryBuilder = make_unique<CSEMIRBuilder>(CurMF);
1738     CSEInfo = &Wrapper.get(TPC->getCSEConfig());
1739     EntryBuilder->setCSEInfo(CSEInfo);
1740     CurBuilder = make_unique<CSEMIRBuilder>(CurMF);
1741     CurBuilder->setCSEInfo(CSEInfo);
1742   } else {
1743     EntryBuilder = make_unique<MachineIRBuilder>();
1744     CurBuilder = make_unique<MachineIRBuilder>();
1745   }
1746   CLI = MF->getSubtarget().getCallLowering();
1747   CurBuilder->setMF(*MF);
1748   EntryBuilder->setMF(*MF);
1749   MRI = &MF->getRegInfo();
1750   DL = &F.getParent()->getDataLayout();
1751   ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F);
1752 
1753   assert(PendingPHIs.empty() && "stale PHIs");
1754 
1755   if (!DL->isLittleEndian()) {
1756     // Currently we don't properly handle big endian code.
1757     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1758                                F.getSubprogram(), &F.getEntryBlock());
1759     R << "unable to translate in big endian mode";
1760     reportTranslationError(*MF, *TPC, *ORE, R);
1761   }
1762 
1763   // Release the per-function state when we return, whether we succeeded or not.
1764   auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1765 
1766   // Setup a separate basic-block for the arguments and constants
1767   MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1768   MF->push_back(EntryBB);
1769   EntryBuilder->setMBB(*EntryBB);
1770 
1771   // Create all blocks, in IR order, to preserve the layout.
1772   for (const BasicBlock &BB: F) {
1773     auto *&MBB = BBToMBB[&BB];
1774 
1775     MBB = MF->CreateMachineBasicBlock(&BB);
1776     MF->push_back(MBB);
1777 
1778     if (BB.hasAddressTaken())
1779       MBB->setHasAddressTaken();
1780   }
1781 
1782   // Make our arguments/constants entry block fallthrough to the IR entry block.
1783   EntryBB->addSuccessor(&getMBB(F.front()));
1784 
1785   // Lower the actual args into this basic block.
1786   SmallVector<unsigned, 8> VRegArgs;
1787   for (const Argument &Arg: F.args()) {
1788     if (DL->getTypeStoreSize(Arg.getType()) == 0)
1789       continue; // Don't handle zero sized types.
1790     VRegArgs.push_back(
1791         MRI->createGenericVirtualRegister(getLLTForType(*Arg.getType(), *DL)));
1792   }
1793 
1794   // We don't currently support translating swifterror or swiftself functions.
1795   for (auto &Arg : F.args()) {
1796     if (Arg.hasSwiftErrorAttr() || Arg.hasSwiftSelfAttr()) {
1797       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1798                                  F.getSubprogram(), &F.getEntryBlock());
1799       R << "unable to lower arguments due to swifterror/swiftself: "
1800         << ore::NV("Prototype", F.getType());
1801       reportTranslationError(*MF, *TPC, *ORE, R);
1802       return false;
1803     }
1804   }
1805 
1806   if (!CLI->lowerFormalArguments(*EntryBuilder.get(), F, VRegArgs)) {
1807     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1808                                F.getSubprogram(), &F.getEntryBlock());
1809     R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1810     reportTranslationError(*MF, *TPC, *ORE, R);
1811     return false;
1812   }
1813 
1814   auto ArgIt = F.arg_begin();
1815   for (auto &VArg : VRegArgs) {
1816     // If the argument is an unsplit scalar then don't use unpackRegs to avoid
1817     // creating redundant copies.
1818     if (!valueIsSplit(*ArgIt, VMap.getOffsets(*ArgIt))) {
1819       auto &VRegs = *VMap.getVRegs(cast<Value>(*ArgIt));
1820       assert(VRegs.empty() && "VRegs already populated?");
1821       VRegs.push_back(VArg);
1822     } else {
1823       unpackRegs(*ArgIt, VArg, *EntryBuilder.get());
1824     }
1825     ArgIt++;
1826   }
1827 
1828   // Need to visit defs before uses when translating instructions.
1829   GISelObserverWrapper WrapperObserver;
1830   if (EnableCSE && CSEInfo)
1831     WrapperObserver.addObserver(CSEInfo);
1832   {
1833     ReversePostOrderTraversal<const Function *> RPOT(&F);
1834 #ifndef NDEBUG
1835     DILocationVerifier Verifier;
1836     WrapperObserver.addObserver(&Verifier);
1837 #endif // ifndef NDEBUG
1838     RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
1839     for (const BasicBlock *BB : RPOT) {
1840       MachineBasicBlock &MBB = getMBB(*BB);
1841       // Set the insertion point of all the following translations to
1842       // the end of this basic block.
1843       CurBuilder->setMBB(MBB);
1844 
1845       for (const Instruction &Inst : *BB) {
1846 #ifndef NDEBUG
1847         Verifier.setCurrentInst(&Inst);
1848 #endif // ifndef NDEBUG
1849         if (translate(Inst))
1850           continue;
1851 
1852         OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1853                                    Inst.getDebugLoc(), BB);
1854         R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
1855 
1856         if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
1857           std::string InstStrStorage;
1858           raw_string_ostream InstStr(InstStrStorage);
1859           InstStr << Inst;
1860 
1861           R << ": '" << InstStr.str() << "'";
1862         }
1863 
1864         reportTranslationError(*MF, *TPC, *ORE, R);
1865         return false;
1866       }
1867     }
1868 #ifndef NDEBUG
1869     WrapperObserver.removeObserver(&Verifier);
1870 #endif
1871   }
1872 
1873   finishPendingPhis();
1874 
1875   // Merge the argument lowering and constants block with its single
1876   // successor, the LLVM-IR entry block.  We want the basic block to
1877   // be maximal.
1878   assert(EntryBB->succ_size() == 1 &&
1879          "Custom BB used for lowering should have only one successor");
1880   // Get the successor of the current entry block.
1881   MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1882   assert(NewEntryBB.pred_size() == 1 &&
1883          "LLVM-IR entry block has a predecessor!?");
1884   // Move all the instruction from the current entry block to the
1885   // new entry block.
1886   NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1887                     EntryBB->end());
1888 
1889   // Update the live-in information for the new entry block.
1890   for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1891     NewEntryBB.addLiveIn(LiveIn);
1892   NewEntryBB.sortUniqueLiveIns();
1893 
1894   // Get rid of the now empty basic block.
1895   EntryBB->removeSuccessor(&NewEntryBB);
1896   MF->remove(EntryBB);
1897   MF->DeleteMachineBasicBlock(EntryBB);
1898 
1899   assert(&MF->front() == &NewEntryBB &&
1900          "New entry wasn't next in the list of basic block!");
1901 
1902   // Initialize stack protector information.
1903   StackProtector &SP = getAnalysis<StackProtector>();
1904   SP.copyToMachineFrameInfo(MF->getFrameInfo());
1905 
1906   return false;
1907 }
1908