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   Type *OffsetIRTy = DL->getIntPtrType(LI.getPointerOperandType());
465   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
466 
467   for (unsigned i = 0; i < Regs.size(); ++i) {
468     unsigned Addr = 0;
469     MIRBuilder.materializeGEP(Addr, Base, OffsetTy, Offsets[i] / 8);
470 
471     MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
472     unsigned BaseAlign = getMemOpAlignment(LI);
473     auto MMO = MF->getMachineMemOperand(
474         Ptr, Flags, (MRI->getType(Regs[i]).getSizeInBits() + 7) / 8,
475         MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
476         LI.getSyncScopeID(), LI.getOrdering());
477     MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
478   }
479 
480   return true;
481 }
482 
483 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
484   const StoreInst &SI = cast<StoreInst>(U);
485   auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
486                                : MachineMemOperand::MONone;
487   Flags |= MachineMemOperand::MOStore;
488 
489   if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
490     return true;
491 
492   ArrayRef<unsigned> Vals = getOrCreateVRegs(*SI.getValueOperand());
493   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
494   unsigned Base = getOrCreateVReg(*SI.getPointerOperand());
495 
496   Type *OffsetIRTy = DL->getIntPtrType(SI.getPointerOperandType());
497   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
498 
499   for (unsigned i = 0; i < Vals.size(); ++i) {
500     unsigned Addr = 0;
501     MIRBuilder.materializeGEP(Addr, Base, OffsetTy, Offsets[i] / 8);
502 
503     MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
504     unsigned BaseAlign = getMemOpAlignment(SI);
505     auto MMO = MF->getMachineMemOperand(
506         Ptr, Flags, (MRI->getType(Vals[i]).getSizeInBits() + 7) / 8,
507         MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
508         SI.getSyncScopeID(), SI.getOrdering());
509     MIRBuilder.buildStore(Vals[i], Addr, *MMO);
510   }
511   return true;
512 }
513 
514 static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
515   const Value *Src = U.getOperand(0);
516   Type *Int32Ty = Type::getInt32Ty(U.getContext());
517 
518   // getIndexedOffsetInType is designed for GEPs, so the first index is the
519   // usual array element rather than looking into the actual aggregate.
520   SmallVector<Value *, 1> Indices;
521   Indices.push_back(ConstantInt::get(Int32Ty, 0));
522 
523   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
524     for (auto Idx : EVI->indices())
525       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
526   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
527     for (auto Idx : IVI->indices())
528       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
529   } else {
530     for (unsigned i = 1; i < U.getNumOperands(); ++i)
531       Indices.push_back(U.getOperand(i));
532   }
533 
534   return 8 * static_cast<uint64_t>(
535                  DL.getIndexedOffsetInType(Src->getType(), Indices));
536 }
537 
538 bool IRTranslator::translateExtractValue(const User &U,
539                                          MachineIRBuilder &MIRBuilder) {
540   const Value *Src = U.getOperand(0);
541   uint64_t Offset = getOffsetFromIndices(U, *DL);
542   ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
543   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
544   unsigned Idx = llvm::lower_bound(Offsets, Offset) - Offsets.begin();
545   auto &DstRegs = allocateVRegs(U);
546 
547   for (unsigned i = 0; i < DstRegs.size(); ++i)
548     DstRegs[i] = SrcRegs[Idx++];
549 
550   return true;
551 }
552 
553 bool IRTranslator::translateInsertValue(const User &U,
554                                         MachineIRBuilder &MIRBuilder) {
555   const Value *Src = U.getOperand(0);
556   uint64_t Offset = getOffsetFromIndices(U, *DL);
557   auto &DstRegs = allocateVRegs(U);
558   ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
559   ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
560   ArrayRef<unsigned> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
561   auto InsertedIt = InsertedRegs.begin();
562 
563   for (unsigned i = 0; i < DstRegs.size(); ++i) {
564     if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
565       DstRegs[i] = *InsertedIt++;
566     else
567       DstRegs[i] = SrcRegs[i];
568   }
569 
570   return true;
571 }
572 
573 bool IRTranslator::translateSelect(const User &U,
574                                    MachineIRBuilder &MIRBuilder) {
575   unsigned Tst = getOrCreateVReg(*U.getOperand(0));
576   ArrayRef<unsigned> ResRegs = getOrCreateVRegs(U);
577   ArrayRef<unsigned> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
578   ArrayRef<unsigned> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
579 
580   const SelectInst &SI = cast<SelectInst>(U);
581   uint16_t Flags = 0;
582   if (const CmpInst *Cmp = dyn_cast<CmpInst>(SI.getCondition()))
583     Flags = MachineInstr::copyFlagsFromInstruction(*Cmp);
584 
585   for (unsigned i = 0; i < ResRegs.size(); ++i) {
586     MIRBuilder.buildInstr(TargetOpcode::G_SELECT, {ResRegs[i]},
587                           {Tst, Op0Regs[i], Op1Regs[i]}, Flags);
588   }
589 
590   return true;
591 }
592 
593 bool IRTranslator::translateBitCast(const User &U,
594                                     MachineIRBuilder &MIRBuilder) {
595   // If we're bitcasting to the source type, we can reuse the source vreg.
596   if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
597       getLLTForType(*U.getType(), *DL)) {
598     unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
599     auto &Regs = *VMap.getVRegs(U);
600     // If we already assigned a vreg for this bitcast, we can't change that.
601     // Emit a copy to satisfy the users we already emitted.
602     if (!Regs.empty())
603       MIRBuilder.buildCopy(Regs[0], SrcReg);
604     else {
605       Regs.push_back(SrcReg);
606       VMap.getOffsets(U)->push_back(0);
607     }
608     return true;
609   }
610   return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
611 }
612 
613 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
614                                  MachineIRBuilder &MIRBuilder) {
615   unsigned Op = getOrCreateVReg(*U.getOperand(0));
616   unsigned Res = getOrCreateVReg(U);
617   MIRBuilder.buildInstr(Opcode, {Res}, {Op});
618   return true;
619 }
620 
621 bool IRTranslator::translateGetElementPtr(const User &U,
622                                           MachineIRBuilder &MIRBuilder) {
623   // FIXME: support vector GEPs.
624   if (U.getType()->isVectorTy())
625     return false;
626 
627   Value &Op0 = *U.getOperand(0);
628   unsigned BaseReg = getOrCreateVReg(Op0);
629   Type *PtrIRTy = Op0.getType();
630   LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
631   Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
632   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
633 
634   int64_t Offset = 0;
635   for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
636        GTI != E; ++GTI) {
637     const Value *Idx = GTI.getOperand();
638     if (StructType *StTy = GTI.getStructTypeOrNull()) {
639       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
640       Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
641       continue;
642     } else {
643       uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
644 
645       // If this is a scalar constant or a splat vector of constants,
646       // handle it quickly.
647       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
648         Offset += ElementSize * CI->getSExtValue();
649         continue;
650       }
651 
652       if (Offset != 0) {
653         unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
654         LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
655         auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset);
656         MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetMIB.getReg(0));
657 
658         BaseReg = NewBaseReg;
659         Offset = 0;
660       }
661 
662       unsigned IdxReg = getOrCreateVReg(*Idx);
663       if (MRI->getType(IdxReg) != OffsetTy) {
664         unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
665         MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
666         IdxReg = NewIdxReg;
667       }
668 
669       // N = N + Idx * ElementSize;
670       // Avoid doing it for ElementSize of 1.
671       unsigned GepOffsetReg;
672       if (ElementSize != 1) {
673         GepOffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
674         auto ElementSizeMIB = MIRBuilder.buildConstant(
675             getLLTForType(*OffsetIRTy, *DL), ElementSize);
676         MIRBuilder.buildMul(GepOffsetReg, ElementSizeMIB.getReg(0), IdxReg);
677       } else
678         GepOffsetReg = IdxReg;
679 
680       unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
681       MIRBuilder.buildGEP(NewBaseReg, BaseReg, GepOffsetReg);
682       BaseReg = NewBaseReg;
683     }
684   }
685 
686   if (Offset != 0) {
687     auto OffsetMIB =
688         MIRBuilder.buildConstant(getLLTForType(*OffsetIRTy, *DL), Offset);
689     MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0));
690     return true;
691   }
692 
693   MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
694   return true;
695 }
696 
697 bool IRTranslator::translateMemfunc(const CallInst &CI,
698                                     MachineIRBuilder &MIRBuilder,
699                                     unsigned ID) {
700   LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
701   Type *DstTy = CI.getArgOperand(0)->getType();
702   if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
703       SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
704     return false;
705 
706   SmallVector<CallLowering::ArgInfo, 8> Args;
707   for (int i = 0; i < 3; ++i) {
708     const auto &Arg = CI.getArgOperand(i);
709     Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
710   }
711 
712   const char *Callee;
713   switch (ID) {
714   case Intrinsic::memmove:
715   case Intrinsic::memcpy: {
716     Type *SrcTy = CI.getArgOperand(1)->getType();
717     if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
718       return false;
719     Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
720     break;
721   }
722   case Intrinsic::memset:
723     Callee = "memset";
724     break;
725   default:
726     return false;
727   }
728 
729   return CLI->lowerCall(MIRBuilder, CI.getCallingConv(),
730                         MachineOperand::CreateES(Callee),
731                         CallLowering::ArgInfo(0, CI.getType()), Args);
732 }
733 
734 void IRTranslator::getStackGuard(unsigned DstReg,
735                                  MachineIRBuilder &MIRBuilder) {
736   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
737   MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
738   auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
739   MIB.addDef(DstReg);
740 
741   auto &TLI = *MF->getSubtarget().getTargetLowering();
742   Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
743   if (!Global)
744     return;
745 
746   MachinePointerInfo MPInfo(Global);
747   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
748                MachineMemOperand::MODereferenceable;
749   MachineMemOperand *MemRef =
750       MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
751                                DL->getPointerABIAlignment(0));
752   MIB.setMemRefs({MemRef});
753 }
754 
755 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
756                                               MachineIRBuilder &MIRBuilder) {
757   ArrayRef<unsigned> ResRegs = getOrCreateVRegs(CI);
758   MIRBuilder.buildInstr(Op)
759       .addDef(ResRegs[0])
760       .addDef(ResRegs[1])
761       .addUse(getOrCreateVReg(*CI.getOperand(0)))
762       .addUse(getOrCreateVReg(*CI.getOperand(1)));
763 
764   return true;
765 }
766 
767 unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) {
768   switch (ID) {
769     default:
770       break;
771     case Intrinsic::bswap:
772       return TargetOpcode::G_BSWAP;
773     case Intrinsic::ceil:
774       return TargetOpcode::G_FCEIL;
775     case Intrinsic::cos:
776       return TargetOpcode::G_FCOS;
777     case Intrinsic::ctpop:
778       return TargetOpcode::G_CTPOP;
779     case Intrinsic::exp:
780       return TargetOpcode::G_FEXP;
781     case Intrinsic::exp2:
782       return TargetOpcode::G_FEXP2;
783     case Intrinsic::fabs:
784       return TargetOpcode::G_FABS;
785     case Intrinsic::canonicalize:
786       return TargetOpcode::G_FCANONICALIZE;
787     case Intrinsic::floor:
788       return TargetOpcode::G_FFLOOR;
789     case Intrinsic::fma:
790       return TargetOpcode::G_FMA;
791     case Intrinsic::log:
792       return TargetOpcode::G_FLOG;
793     case Intrinsic::log2:
794       return TargetOpcode::G_FLOG2;
795     case Intrinsic::log10:
796       return TargetOpcode::G_FLOG10;
797     case Intrinsic::nearbyint:
798       return TargetOpcode::G_FNEARBYINT;
799     case Intrinsic::pow:
800       return TargetOpcode::G_FPOW;
801     case Intrinsic::rint:
802       return TargetOpcode::G_FRINT;
803     case Intrinsic::round:
804       return TargetOpcode::G_INTRINSIC_ROUND;
805     case Intrinsic::sin:
806       return TargetOpcode::G_FSIN;
807     case Intrinsic::sqrt:
808       return TargetOpcode::G_FSQRT;
809     case Intrinsic::trunc:
810       return TargetOpcode::G_INTRINSIC_TRUNC;
811   }
812   return Intrinsic::not_intrinsic;
813 }
814 
815 bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI,
816                                             Intrinsic::ID ID,
817                                             MachineIRBuilder &MIRBuilder) {
818 
819   unsigned Op = getSimpleIntrinsicOpcode(ID);
820 
821   // Is this a simple intrinsic?
822   if (Op == Intrinsic::not_intrinsic)
823     return false;
824 
825   // Yes. Let's translate it.
826   SmallVector<llvm::SrcOp, 4> VRegs;
827   for (auto &Arg : CI.arg_operands())
828     VRegs.push_back(getOrCreateVReg(*Arg));
829 
830   MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
831                         MachineInstr::copyFlagsFromInstruction(CI));
832   return true;
833 }
834 
835 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
836                                            MachineIRBuilder &MIRBuilder) {
837 
838   // If this is a simple intrinsic (that is, we just need to add a def of
839   // a vreg, and uses for each arg operand, then translate it.
840   if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
841     return true;
842 
843   switch (ID) {
844   default:
845     break;
846   case Intrinsic::lifetime_start:
847   case Intrinsic::lifetime_end: {
848     // No stack colouring in O0, discard region information.
849     if (MF->getTarget().getOptLevel() == CodeGenOpt::None)
850       return true;
851 
852     unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START
853                                                   : TargetOpcode::LIFETIME_END;
854 
855     // Get the underlying objects for the location passed on the lifetime
856     // marker.
857     SmallVector<const Value *, 4> Allocas;
858     GetUnderlyingObjects(CI.getArgOperand(1), Allocas, *DL);
859 
860     // Iterate over each underlying object, creating lifetime markers for each
861     // static alloca. Quit if we find a non-static alloca.
862     for (const Value *V : Allocas) {
863       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
864       if (!AI)
865         continue;
866 
867       if (!AI->isStaticAlloca())
868         return true;
869 
870       MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI));
871     }
872     return true;
873   }
874   case Intrinsic::dbg_declare: {
875     const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
876     assert(DI.getVariable() && "Missing variable");
877 
878     const Value *Address = DI.getAddress();
879     if (!Address || isa<UndefValue>(Address)) {
880       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
881       return true;
882     }
883 
884     assert(DI.getVariable()->isValidLocationForIntrinsic(
885                MIRBuilder.getDebugLoc()) &&
886            "Expected inlined-at fields to agree");
887     auto AI = dyn_cast<AllocaInst>(Address);
888     if (AI && AI->isStaticAlloca()) {
889       // Static allocas are tracked at the MF level, no need for DBG_VALUE
890       // instructions (in fact, they get ignored if they *do* exist).
891       MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
892                              getOrCreateFrameIndex(*AI), DI.getDebugLoc());
893     } else {
894       // A dbg.declare describes the address of a source variable, so lower it
895       // into an indirect DBG_VALUE.
896       MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address),
897                                        DI.getVariable(), DI.getExpression());
898     }
899     return true;
900   }
901   case Intrinsic::dbg_label: {
902     const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
903     assert(DI.getLabel() && "Missing label");
904 
905     assert(DI.getLabel()->isValidLocationForIntrinsic(
906                MIRBuilder.getDebugLoc()) &&
907            "Expected inlined-at fields to agree");
908 
909     MIRBuilder.buildDbgLabel(DI.getLabel());
910     return true;
911   }
912   case Intrinsic::vaend:
913     // No target I know of cares about va_end. Certainly no in-tree target
914     // does. Simplest intrinsic ever!
915     return true;
916   case Intrinsic::vastart: {
917     auto &TLI = *MF->getSubtarget().getTargetLowering();
918     Value *Ptr = CI.getArgOperand(0);
919     unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
920 
921     // FIXME: Get alignment
922     MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
923         .addUse(getOrCreateVReg(*Ptr))
924         .addMemOperand(MF->getMachineMemOperand(
925             MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 1));
926     return true;
927   }
928   case Intrinsic::dbg_value: {
929     // This form of DBG_VALUE is target-independent.
930     const DbgValueInst &DI = cast<DbgValueInst>(CI);
931     const Value *V = DI.getValue();
932     assert(DI.getVariable()->isValidLocationForIntrinsic(
933                MIRBuilder.getDebugLoc()) &&
934            "Expected inlined-at fields to agree");
935     if (!V) {
936       // Currently the optimizer can produce this; insert an undef to
937       // help debugging.  Probably the optimizer should not do this.
938       MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
939     } else if (const auto *CI = dyn_cast<Constant>(V)) {
940       MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
941     } else {
942       unsigned Reg = getOrCreateVReg(*V);
943       // FIXME: This does not handle register-indirect values at offset 0. The
944       // direct/indirect thing shouldn't really be handled by something as
945       // implicit as reg+noreg vs reg+imm in the first palce, but it seems
946       // pretty baked in right now.
947       MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
948     }
949     return true;
950   }
951   case Intrinsic::uadd_with_overflow:
952     return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
953   case Intrinsic::sadd_with_overflow:
954     return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
955   case Intrinsic::usub_with_overflow:
956     return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
957   case Intrinsic::ssub_with_overflow:
958     return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
959   case Intrinsic::umul_with_overflow:
960     return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
961   case Intrinsic::smul_with_overflow:
962     return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
963   case Intrinsic::fmuladd: {
964     const TargetMachine &TM = MF->getTarget();
965     const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
966     unsigned Dst = getOrCreateVReg(CI);
967     unsigned Op0 = getOrCreateVReg(*CI.getArgOperand(0));
968     unsigned Op1 = getOrCreateVReg(*CI.getArgOperand(1));
969     unsigned Op2 = getOrCreateVReg(*CI.getArgOperand(2));
970     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
971         TLI.isFMAFasterThanFMulAndFAdd(TLI.getValueType(*DL, CI.getType()))) {
972       // TODO: Revisit this to see if we should move this part of the
973       // lowering to the combiner.
974       MIRBuilder.buildInstr(TargetOpcode::G_FMA, {Dst}, {Op0, Op1, Op2},
975                             MachineInstr::copyFlagsFromInstruction(CI));
976     } else {
977       LLT Ty = getLLTForType(*CI.getType(), *DL);
978       auto FMul = MIRBuilder.buildInstr(TargetOpcode::G_FMUL, {Ty}, {Op0, Op1},
979                                         MachineInstr::copyFlagsFromInstruction(CI));
980       MIRBuilder.buildInstr(TargetOpcode::G_FADD, {Dst}, {FMul, Op2},
981                             MachineInstr::copyFlagsFromInstruction(CI));
982     }
983     return true;
984   }
985   case Intrinsic::memcpy:
986   case Intrinsic::memmove:
987   case Intrinsic::memset:
988     return translateMemfunc(CI, MIRBuilder, ID);
989   case Intrinsic::eh_typeid_for: {
990     GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
991     unsigned Reg = getOrCreateVReg(CI);
992     unsigned TypeID = MF->getTypeIDFor(GV);
993     MIRBuilder.buildConstant(Reg, TypeID);
994     return true;
995   }
996   case Intrinsic::objectsize: {
997     // If we don't know by now, we're never going to know.
998     const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
999 
1000     MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
1001     return true;
1002   }
1003   case Intrinsic::is_constant:
1004     // If this wasn't constant-folded away by now, then it's not a
1005     // constant.
1006     MIRBuilder.buildConstant(getOrCreateVReg(CI), 0);
1007     return true;
1008   case Intrinsic::stackguard:
1009     getStackGuard(getOrCreateVReg(CI), MIRBuilder);
1010     return true;
1011   case Intrinsic::stackprotector: {
1012     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1013     unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
1014     getStackGuard(GuardVal, MIRBuilder);
1015 
1016     AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
1017     int FI = getOrCreateFrameIndex(*Slot);
1018     MF->getFrameInfo().setStackProtectorIndex(FI);
1019 
1020     MIRBuilder.buildStore(
1021         GuardVal, getOrCreateVReg(*Slot),
1022         *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
1023                                   MachineMemOperand::MOStore |
1024                                       MachineMemOperand::MOVolatile,
1025                                   PtrTy.getSizeInBits() / 8, 8));
1026     return true;
1027   }
1028   case Intrinsic::stacksave: {
1029     // Save the stack pointer to the location provided by the intrinsic.
1030     unsigned Reg = getOrCreateVReg(CI);
1031     unsigned StackPtr = MF->getSubtarget()
1032                             .getTargetLowering()
1033                             ->getStackPointerRegisterToSaveRestore();
1034 
1035     // If the target doesn't specify a stack pointer, then fall back.
1036     if (!StackPtr)
1037       return false;
1038 
1039     MIRBuilder.buildCopy(Reg, StackPtr);
1040     return true;
1041   }
1042   case Intrinsic::stackrestore: {
1043     // Restore the stack pointer from the location provided by the intrinsic.
1044     unsigned Reg = getOrCreateVReg(*CI.getArgOperand(0));
1045     unsigned StackPtr = MF->getSubtarget()
1046                             .getTargetLowering()
1047                             ->getStackPointerRegisterToSaveRestore();
1048 
1049     // If the target doesn't specify a stack pointer, then fall back.
1050     if (!StackPtr)
1051       return false;
1052 
1053     MIRBuilder.buildCopy(StackPtr, Reg);
1054     return true;
1055   }
1056   case Intrinsic::cttz:
1057   case Intrinsic::ctlz: {
1058     ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
1059     bool isTrailing = ID == Intrinsic::cttz;
1060     unsigned Opcode = isTrailing
1061                           ? Cst->isZero() ? TargetOpcode::G_CTTZ
1062                                           : TargetOpcode::G_CTTZ_ZERO_UNDEF
1063                           : Cst->isZero() ? TargetOpcode::G_CTLZ
1064                                           : TargetOpcode::G_CTLZ_ZERO_UNDEF;
1065     MIRBuilder.buildInstr(Opcode)
1066         .addDef(getOrCreateVReg(CI))
1067         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
1068     return true;
1069   }
1070   case Intrinsic::invariant_start: {
1071     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1072     unsigned Undef = MRI->createGenericVirtualRegister(PtrTy);
1073     MIRBuilder.buildUndef(Undef);
1074     return true;
1075   }
1076   case Intrinsic::invariant_end:
1077     return true;
1078   }
1079   return false;
1080 }
1081 
1082 bool IRTranslator::translateInlineAsm(const CallInst &CI,
1083                                       MachineIRBuilder &MIRBuilder) {
1084   const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
1085   if (!IA.getConstraintString().empty())
1086     return false;
1087 
1088   unsigned ExtraInfo = 0;
1089   if (IA.hasSideEffects())
1090     ExtraInfo |= InlineAsm::Extra_HasSideEffects;
1091   if (IA.getDialect() == InlineAsm::AD_Intel)
1092     ExtraInfo |= InlineAsm::Extra_AsmDialect;
1093 
1094   MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
1095     .addExternalSymbol(IA.getAsmString().c_str())
1096     .addImm(ExtraInfo);
1097 
1098   return true;
1099 }
1100 
1101 unsigned IRTranslator::packRegs(const Value &V,
1102                                   MachineIRBuilder &MIRBuilder) {
1103   ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
1104   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
1105   LLT BigTy = getLLTForType(*V.getType(), *DL);
1106 
1107   if (Regs.size() == 1)
1108     return Regs[0];
1109 
1110   unsigned Dst = MRI->createGenericVirtualRegister(BigTy);
1111   MIRBuilder.buildUndef(Dst);
1112   for (unsigned i = 0; i < Regs.size(); ++i) {
1113     unsigned NewDst = MRI->createGenericVirtualRegister(BigTy);
1114     MIRBuilder.buildInsert(NewDst, Dst, Regs[i], Offsets[i]);
1115     Dst = NewDst;
1116   }
1117   return Dst;
1118 }
1119 
1120 void IRTranslator::unpackRegs(const Value &V, unsigned Src,
1121                                 MachineIRBuilder &MIRBuilder) {
1122   ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
1123   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
1124 
1125   for (unsigned i = 0; i < Regs.size(); ++i)
1126     MIRBuilder.buildExtract(Regs[i], Src, Offsets[i]);
1127 }
1128 
1129 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
1130   const CallInst &CI = cast<CallInst>(U);
1131   auto TII = MF->getTarget().getIntrinsicInfo();
1132   const Function *F = CI.getCalledFunction();
1133 
1134   // FIXME: support Windows dllimport function calls.
1135   if (F && F->hasDLLImportStorageClass())
1136     return false;
1137 
1138   if (CI.isInlineAsm())
1139     return translateInlineAsm(CI, MIRBuilder);
1140 
1141   Intrinsic::ID ID = Intrinsic::not_intrinsic;
1142   if (F && F->isIntrinsic()) {
1143     ID = F->getIntrinsicID();
1144     if (TII && ID == Intrinsic::not_intrinsic)
1145       ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
1146   }
1147 
1148   if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) {
1149     bool IsSplitType = valueIsSplit(CI);
1150     unsigned Res = IsSplitType ? MRI->createGenericVirtualRegister(
1151                                      getLLTForType(*CI.getType(), *DL))
1152                                : getOrCreateVReg(CI);
1153 
1154     SmallVector<unsigned, 8> Args;
1155     for (auto &Arg: CI.arg_operands())
1156       Args.push_back(packRegs(*Arg, MIRBuilder));
1157 
1158     MF->getFrameInfo().setHasCalls(true);
1159     bool Success = CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
1160       return getOrCreateVReg(*CI.getCalledValue());
1161     });
1162 
1163     if (IsSplitType)
1164       unpackRegs(CI, Res, MIRBuilder);
1165     return Success;
1166   }
1167 
1168   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
1169 
1170   if (translateKnownIntrinsic(CI, ID, MIRBuilder))
1171     return true;
1172 
1173   ArrayRef<unsigned> ResultRegs;
1174   if (!CI.getType()->isVoidTy())
1175     ResultRegs = getOrCreateVRegs(CI);
1176 
1177   MachineInstrBuilder MIB =
1178       MIRBuilder.buildIntrinsic(ID, ResultRegs, !CI.doesNotAccessMemory());
1179   if (isa<FPMathOperator>(CI))
1180     MIB->copyIRFlags(CI);
1181 
1182   for (auto &Arg : CI.arg_operands()) {
1183     // Some intrinsics take metadata parameters. Reject them.
1184     if (isa<MetadataAsValue>(Arg))
1185       return false;
1186     MIB.addUse(packRegs(*Arg, MIRBuilder));
1187   }
1188 
1189   // Add a MachineMemOperand if it is a target mem intrinsic.
1190   const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1191   TargetLowering::IntrinsicInfo Info;
1192   // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
1193   if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
1194     unsigned Align = Info.align;
1195     if (Align == 0)
1196       Align = DL->getABITypeAlignment(Info.memVT.getTypeForEVT(F->getContext()));
1197 
1198     uint64_t Size = Info.memVT.getStoreSize();
1199     MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
1200                                                Info.flags, Size, Align));
1201   }
1202 
1203   return true;
1204 }
1205 
1206 bool IRTranslator::translateInvoke(const User &U,
1207                                    MachineIRBuilder &MIRBuilder) {
1208   const InvokeInst &I = cast<InvokeInst>(U);
1209   MCContext &Context = MF->getContext();
1210 
1211   const BasicBlock *ReturnBB = I.getSuccessor(0);
1212   const BasicBlock *EHPadBB = I.getSuccessor(1);
1213 
1214   const Value *Callee = I.getCalledValue();
1215   const Function *Fn = dyn_cast<Function>(Callee);
1216   if (isa<InlineAsm>(Callee))
1217     return false;
1218 
1219   // FIXME: support invoking patchpoint and statepoint intrinsics.
1220   if (Fn && Fn->isIntrinsic())
1221     return false;
1222 
1223   // FIXME: support whatever these are.
1224   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
1225     return false;
1226 
1227   // FIXME: support Windows exception handling.
1228   if (!isa<LandingPadInst>(EHPadBB->front()))
1229     return false;
1230 
1231   // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
1232   // the region covered by the try.
1233   MCSymbol *BeginSymbol = Context.createTempSymbol();
1234   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
1235 
1236   unsigned Res = 0;
1237   if (!I.getType()->isVoidTy())
1238     Res = MRI->createGenericVirtualRegister(getLLTForType(*I.getType(), *DL));
1239   SmallVector<unsigned, 8> Args;
1240   for (auto &Arg: I.arg_operands())
1241     Args.push_back(packRegs(*Arg, MIRBuilder));
1242 
1243   if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
1244                       [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
1245     return false;
1246 
1247   unpackRegs(I, Res, MIRBuilder);
1248 
1249   MCSymbol *EndSymbol = Context.createTempSymbol();
1250   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
1251 
1252   // FIXME: track probabilities.
1253   MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
1254                     &ReturnMBB = getMBB(*ReturnBB);
1255   MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
1256   MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
1257   MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
1258   MIRBuilder.buildBr(ReturnMBB);
1259 
1260   return true;
1261 }
1262 
1263 bool IRTranslator::translateCallBr(const User &U,
1264                                    MachineIRBuilder &MIRBuilder) {
1265   // FIXME: Implement this.
1266   return false;
1267 }
1268 
1269 bool IRTranslator::translateLandingPad(const User &U,
1270                                        MachineIRBuilder &MIRBuilder) {
1271   const LandingPadInst &LP = cast<LandingPadInst>(U);
1272 
1273   MachineBasicBlock &MBB = MIRBuilder.getMBB();
1274 
1275   MBB.setIsEHPad();
1276 
1277   // If there aren't registers to copy the values into (e.g., during SjLj
1278   // exceptions), then don't bother.
1279   auto &TLI = *MF->getSubtarget().getTargetLowering();
1280   const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
1281   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
1282       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
1283     return true;
1284 
1285   // If landingpad's return type is token type, we don't create DAG nodes
1286   // for its exception pointer and selector value. The extraction of exception
1287   // pointer or selector value from token type landingpads is not currently
1288   // supported.
1289   if (LP.getType()->isTokenTy())
1290     return true;
1291 
1292   // Add a label to mark the beginning of the landing pad.  Deletion of the
1293   // landing pad can thus be detected via the MachineModuleInfo.
1294   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
1295     .addSym(MF->addLandingPad(&MBB));
1296 
1297   LLT Ty = getLLTForType(*LP.getType(), *DL);
1298   unsigned Undef = MRI->createGenericVirtualRegister(Ty);
1299   MIRBuilder.buildUndef(Undef);
1300 
1301   SmallVector<LLT, 2> Tys;
1302   for (Type *Ty : cast<StructType>(LP.getType())->elements())
1303     Tys.push_back(getLLTForType(*Ty, *DL));
1304   assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
1305 
1306   // Mark exception register as live in.
1307   unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
1308   if (!ExceptionReg)
1309     return false;
1310 
1311   MBB.addLiveIn(ExceptionReg);
1312   ArrayRef<unsigned> ResRegs = getOrCreateVRegs(LP);
1313   MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
1314 
1315   unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
1316   if (!SelectorReg)
1317     return false;
1318 
1319   MBB.addLiveIn(SelectorReg);
1320   unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
1321   MIRBuilder.buildCopy(PtrVReg, SelectorReg);
1322   MIRBuilder.buildCast(ResRegs[1], PtrVReg);
1323 
1324   return true;
1325 }
1326 
1327 bool IRTranslator::translateAlloca(const User &U,
1328                                    MachineIRBuilder &MIRBuilder) {
1329   auto &AI = cast<AllocaInst>(U);
1330 
1331   if (AI.isSwiftError())
1332     return false;
1333 
1334   if (AI.isStaticAlloca()) {
1335     unsigned Res = getOrCreateVReg(AI);
1336     int FI = getOrCreateFrameIndex(AI);
1337     MIRBuilder.buildFrameIndex(Res, FI);
1338     return true;
1339   }
1340 
1341   // FIXME: support stack probing for Windows.
1342   if (MF->getTarget().getTargetTriple().isOSWindows())
1343     return false;
1344 
1345   // Now we're in the harder dynamic case.
1346   Type *Ty = AI.getAllocatedType();
1347   unsigned Align =
1348       std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
1349 
1350   unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
1351 
1352   Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
1353   LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
1354   if (MRI->getType(NumElts) != IntPtrTy) {
1355     unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
1356     MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
1357     NumElts = ExtElts;
1358   }
1359 
1360   unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
1361   unsigned TySize =
1362       getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
1363   MIRBuilder.buildMul(AllocSize, NumElts, TySize);
1364 
1365   LLT PtrTy = getLLTForType(*AI.getType(), *DL);
1366   auto &TLI = *MF->getSubtarget().getTargetLowering();
1367   unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1368 
1369   unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
1370   MIRBuilder.buildCopy(SPTmp, SPReg);
1371 
1372   unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
1373   MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
1374 
1375   // Handle alignment. We have to realign if the allocation granule was smaller
1376   // than stack alignment, or the specific alloca requires more than stack
1377   // alignment.
1378   unsigned StackAlign =
1379       MF->getSubtarget().getFrameLowering()->getStackAlignment();
1380   Align = std::max(Align, StackAlign);
1381   if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
1382     // Round the size of the allocation up to the stack alignment size
1383     // by add SA-1 to the size. This doesn't overflow because we're computing
1384     // an address inside an alloca.
1385     unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
1386     MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
1387     AllocTmp = AlignedAlloc;
1388   }
1389 
1390   MIRBuilder.buildCopy(SPReg, AllocTmp);
1391   MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
1392 
1393   MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
1394   assert(MF->getFrameInfo().hasVarSizedObjects());
1395   return true;
1396 }
1397 
1398 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
1399   // FIXME: We may need more info about the type. Because of how LLT works,
1400   // we're completely discarding the i64/double distinction here (amongst
1401   // others). Fortunately the ABIs I know of where that matters don't use va_arg
1402   // anyway but that's not guaranteed.
1403   MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
1404     .addDef(getOrCreateVReg(U))
1405     .addUse(getOrCreateVReg(*U.getOperand(0)))
1406     .addImm(DL->getABITypeAlignment(U.getType()));
1407   return true;
1408 }
1409 
1410 bool IRTranslator::translateInsertElement(const User &U,
1411                                           MachineIRBuilder &MIRBuilder) {
1412   // If it is a <1 x Ty> vector, use the scalar as it is
1413   // not a legal vector type in LLT.
1414   if (U.getType()->getVectorNumElements() == 1) {
1415     unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1416     auto &Regs = *VMap.getVRegs(U);
1417     if (Regs.empty()) {
1418       Regs.push_back(Elt);
1419       VMap.getOffsets(U)->push_back(0);
1420     } else {
1421       MIRBuilder.buildCopy(Regs[0], Elt);
1422     }
1423     return true;
1424   }
1425 
1426   unsigned Res = getOrCreateVReg(U);
1427   unsigned Val = getOrCreateVReg(*U.getOperand(0));
1428   unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1429   unsigned Idx = getOrCreateVReg(*U.getOperand(2));
1430   MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
1431   return true;
1432 }
1433 
1434 bool IRTranslator::translateExtractElement(const User &U,
1435                                            MachineIRBuilder &MIRBuilder) {
1436   // If it is a <1 x Ty> vector, use the scalar as it is
1437   // not a legal vector type in LLT.
1438   if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
1439     unsigned Elt = getOrCreateVReg(*U.getOperand(0));
1440     auto &Regs = *VMap.getVRegs(U);
1441     if (Regs.empty()) {
1442       Regs.push_back(Elt);
1443       VMap.getOffsets(U)->push_back(0);
1444     } else {
1445       MIRBuilder.buildCopy(Regs[0], Elt);
1446     }
1447     return true;
1448   }
1449   unsigned Res = getOrCreateVReg(U);
1450   unsigned Val = getOrCreateVReg(*U.getOperand(0));
1451   const auto &TLI = *MF->getSubtarget().getTargetLowering();
1452   unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits();
1453   unsigned Idx = 0;
1454   if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) {
1455     if (CI->getBitWidth() != PreferredVecIdxWidth) {
1456       APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth);
1457       auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
1458       Idx = getOrCreateVReg(*NewIdxCI);
1459     }
1460   }
1461   if (!Idx)
1462     Idx = getOrCreateVReg(*U.getOperand(1));
1463   if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
1464     const LLT &VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
1465     Idx = MIRBuilder.buildSExtOrTrunc(VecIdxTy, Idx)->getOperand(0).getReg();
1466   }
1467   MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
1468   return true;
1469 }
1470 
1471 bool IRTranslator::translateShuffleVector(const User &U,
1472                                           MachineIRBuilder &MIRBuilder) {
1473   MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
1474       .addDef(getOrCreateVReg(U))
1475       .addUse(getOrCreateVReg(*U.getOperand(0)))
1476       .addUse(getOrCreateVReg(*U.getOperand(1)))
1477       .addUse(getOrCreateVReg(*U.getOperand(2)));
1478   return true;
1479 }
1480 
1481 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
1482   const PHINode &PI = cast<PHINode>(U);
1483 
1484   SmallVector<MachineInstr *, 4> Insts;
1485   for (auto Reg : getOrCreateVRegs(PI)) {
1486     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {});
1487     Insts.push_back(MIB.getInstr());
1488   }
1489 
1490   PendingPHIs.emplace_back(&PI, std::move(Insts));
1491   return true;
1492 }
1493 
1494 bool IRTranslator::translateAtomicCmpXchg(const User &U,
1495                                           MachineIRBuilder &MIRBuilder) {
1496   const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
1497 
1498   if (I.isWeak())
1499     return false;
1500 
1501   auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1502                               : MachineMemOperand::MONone;
1503   Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1504 
1505   Type *ResType = I.getType();
1506   Type *ValType = ResType->Type::getStructElementType(0);
1507 
1508   auto Res = getOrCreateVRegs(I);
1509   unsigned OldValRes = Res[0];
1510   unsigned SuccessRes = Res[1];
1511   unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1512   unsigned Cmp = getOrCreateVReg(*I.getCompareOperand());
1513   unsigned NewVal = getOrCreateVReg(*I.getNewValOperand());
1514 
1515   MIRBuilder.buildAtomicCmpXchgWithSuccess(
1516       OldValRes, SuccessRes, Addr, Cmp, NewVal,
1517       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1518                                 Flags, DL->getTypeStoreSize(ValType),
1519                                 getMemOpAlignment(I), AAMDNodes(), nullptr,
1520                                 I.getSyncScopeID(), I.getSuccessOrdering(),
1521                                 I.getFailureOrdering()));
1522   return true;
1523 }
1524 
1525 bool IRTranslator::translateAtomicRMW(const User &U,
1526                                       MachineIRBuilder &MIRBuilder) {
1527   const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
1528 
1529   auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1530                               : MachineMemOperand::MONone;
1531   Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1532 
1533   Type *ResType = I.getType();
1534 
1535   unsigned Res = getOrCreateVReg(I);
1536   unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1537   unsigned Val = getOrCreateVReg(*I.getValOperand());
1538 
1539   unsigned Opcode = 0;
1540   switch (I.getOperation()) {
1541   default:
1542     llvm_unreachable("Unknown atomicrmw op");
1543     return false;
1544   case AtomicRMWInst::Xchg:
1545     Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
1546     break;
1547   case AtomicRMWInst::Add:
1548     Opcode = TargetOpcode::G_ATOMICRMW_ADD;
1549     break;
1550   case AtomicRMWInst::Sub:
1551     Opcode = TargetOpcode::G_ATOMICRMW_SUB;
1552     break;
1553   case AtomicRMWInst::And:
1554     Opcode = TargetOpcode::G_ATOMICRMW_AND;
1555     break;
1556   case AtomicRMWInst::Nand:
1557     Opcode = TargetOpcode::G_ATOMICRMW_NAND;
1558     break;
1559   case AtomicRMWInst::Or:
1560     Opcode = TargetOpcode::G_ATOMICRMW_OR;
1561     break;
1562   case AtomicRMWInst::Xor:
1563     Opcode = TargetOpcode::G_ATOMICRMW_XOR;
1564     break;
1565   case AtomicRMWInst::Max:
1566     Opcode = TargetOpcode::G_ATOMICRMW_MAX;
1567     break;
1568   case AtomicRMWInst::Min:
1569     Opcode = TargetOpcode::G_ATOMICRMW_MIN;
1570     break;
1571   case AtomicRMWInst::UMax:
1572     Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
1573     break;
1574   case AtomicRMWInst::UMin:
1575     Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
1576     break;
1577   }
1578 
1579   MIRBuilder.buildAtomicRMW(
1580       Opcode, Res, Addr, Val,
1581       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1582                                 Flags, DL->getTypeStoreSize(ResType),
1583                                 getMemOpAlignment(I), AAMDNodes(), nullptr,
1584                                 I.getSyncScopeID(), I.getOrdering()));
1585   return true;
1586 }
1587 
1588 void IRTranslator::finishPendingPhis() {
1589 #ifndef NDEBUG
1590   DILocationVerifier Verifier;
1591   GISelObserverWrapper WrapperObserver(&Verifier);
1592   RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
1593 #endif // ifndef NDEBUG
1594   for (auto &Phi : PendingPHIs) {
1595     const PHINode *PI = Phi.first;
1596     ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
1597     EntryBuilder->setDebugLoc(PI->getDebugLoc());
1598 #ifndef NDEBUG
1599     Verifier.setCurrentInst(PI);
1600 #endif // ifndef NDEBUG
1601 
1602     // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
1603     // won't create extra control flow here, otherwise we need to find the
1604     // dominating predecessor here (or perhaps force the weirder IRTranslators
1605     // to provide a simple boundary).
1606     SmallSet<const BasicBlock *, 4> HandledPreds;
1607 
1608     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
1609       auto IRPred = PI->getIncomingBlock(i);
1610       if (HandledPreds.count(IRPred))
1611         continue;
1612 
1613       HandledPreds.insert(IRPred);
1614       ArrayRef<unsigned> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
1615       for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
1616         assert(Pred->isSuccessor(ComponentPHIs[0]->getParent()) &&
1617                "incorrect CFG at MachineBasicBlock level");
1618         for (unsigned j = 0; j < ValRegs.size(); ++j) {
1619           MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
1620           MIB.addUse(ValRegs[j]);
1621           MIB.addMBB(Pred);
1622         }
1623       }
1624     }
1625   }
1626 }
1627 
1628 bool IRTranslator::valueIsSplit(const Value &V,
1629                                 SmallVectorImpl<uint64_t> *Offsets) {
1630   SmallVector<LLT, 4> SplitTys;
1631   if (Offsets && !Offsets->empty())
1632     Offsets->clear();
1633   computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
1634   return SplitTys.size() > 1;
1635 }
1636 
1637 bool IRTranslator::translate(const Instruction &Inst) {
1638   CurBuilder->setDebugLoc(Inst.getDebugLoc());
1639   EntryBuilder->setDebugLoc(Inst.getDebugLoc());
1640   switch(Inst.getOpcode()) {
1641 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
1642   case Instruction::OPCODE:                                                    \
1643     return translate##OPCODE(Inst, *CurBuilder.get());
1644 #include "llvm/IR/Instruction.def"
1645   default:
1646     return false;
1647   }
1648 }
1649 
1650 bool IRTranslator::translate(const Constant &C, unsigned Reg) {
1651   if (auto CI = dyn_cast<ConstantInt>(&C))
1652     EntryBuilder->buildConstant(Reg, *CI);
1653   else if (auto CF = dyn_cast<ConstantFP>(&C))
1654     EntryBuilder->buildFConstant(Reg, *CF);
1655   else if (isa<UndefValue>(C))
1656     EntryBuilder->buildUndef(Reg);
1657   else if (isa<ConstantPointerNull>(C)) {
1658     // As we are trying to build a constant val of 0 into a pointer,
1659     // insert a cast to make them correct with respect to types.
1660     unsigned NullSize = DL->getTypeSizeInBits(C.getType());
1661     auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize);
1662     auto *ZeroVal = ConstantInt::get(ZeroTy, 0);
1663     unsigned ZeroReg = getOrCreateVReg(*ZeroVal);
1664     EntryBuilder->buildCast(Reg, ZeroReg);
1665   } else if (auto GV = dyn_cast<GlobalValue>(&C))
1666     EntryBuilder->buildGlobalValue(Reg, GV);
1667   else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
1668     if (!CAZ->getType()->isVectorTy())
1669       return false;
1670     // Return the scalar if it is a <1 x Ty> vector.
1671     if (CAZ->getNumElements() == 1)
1672       return translate(*CAZ->getElementValue(0u), Reg);
1673     SmallVector<unsigned, 4> Ops;
1674     for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
1675       Constant &Elt = *CAZ->getElementValue(i);
1676       Ops.push_back(getOrCreateVReg(Elt));
1677     }
1678     EntryBuilder->buildBuildVector(Reg, Ops);
1679   } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
1680     // Return the scalar if it is a <1 x Ty> vector.
1681     if (CV->getNumElements() == 1)
1682       return translate(*CV->getElementAsConstant(0), Reg);
1683     SmallVector<unsigned, 4> Ops;
1684     for (unsigned i = 0; i < CV->getNumElements(); ++i) {
1685       Constant &Elt = *CV->getElementAsConstant(i);
1686       Ops.push_back(getOrCreateVReg(Elt));
1687     }
1688     EntryBuilder->buildBuildVector(Reg, Ops);
1689   } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
1690     switch(CE->getOpcode()) {
1691 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
1692   case Instruction::OPCODE:                                                    \
1693     return translate##OPCODE(*CE, *EntryBuilder.get());
1694 #include "llvm/IR/Instruction.def"
1695     default:
1696       return false;
1697     }
1698   } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
1699     if (CV->getNumOperands() == 1)
1700       return translate(*CV->getOperand(0), Reg);
1701     SmallVector<unsigned, 4> Ops;
1702     for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
1703       Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
1704     }
1705     EntryBuilder->buildBuildVector(Reg, Ops);
1706   } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
1707     EntryBuilder->buildBlockAddress(Reg, BA);
1708   } else
1709     return false;
1710 
1711   return true;
1712 }
1713 
1714 void IRTranslator::finalizeFunction() {
1715   // Release the memory used by the different maps we
1716   // needed during the translation.
1717   PendingPHIs.clear();
1718   VMap.reset();
1719   FrameIndices.clear();
1720   MachinePreds.clear();
1721   // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
1722   // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
1723   // destroying it twice (in ~IRTranslator() and ~LLVMContext())
1724   EntryBuilder.reset();
1725   CurBuilder.reset();
1726 }
1727 
1728 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1729   MF = &CurMF;
1730   const Function &F = MF->getFunction();
1731   if (F.empty())
1732     return false;
1733   GISelCSEAnalysisWrapper &Wrapper =
1734       getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
1735   // Set the CSEConfig and run the analysis.
1736   GISelCSEInfo *CSEInfo = nullptr;
1737   TPC = &getAnalysis<TargetPassConfig>();
1738   bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences()
1739                        ? EnableCSEInIRTranslator
1740                        : TPC->isGISelCSEEnabled();
1741 
1742   if (EnableCSE) {
1743     EntryBuilder = make_unique<CSEMIRBuilder>(CurMF);
1744     CSEInfo = &Wrapper.get(TPC->getCSEConfig());
1745     EntryBuilder->setCSEInfo(CSEInfo);
1746     CurBuilder = make_unique<CSEMIRBuilder>(CurMF);
1747     CurBuilder->setCSEInfo(CSEInfo);
1748   } else {
1749     EntryBuilder = make_unique<MachineIRBuilder>();
1750     CurBuilder = make_unique<MachineIRBuilder>();
1751   }
1752   CLI = MF->getSubtarget().getCallLowering();
1753   CurBuilder->setMF(*MF);
1754   EntryBuilder->setMF(*MF);
1755   MRI = &MF->getRegInfo();
1756   DL = &F.getParent()->getDataLayout();
1757   ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F);
1758 
1759   assert(PendingPHIs.empty() && "stale PHIs");
1760 
1761   if (!DL->isLittleEndian()) {
1762     // Currently we don't properly handle big endian code.
1763     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1764                                F.getSubprogram(), &F.getEntryBlock());
1765     R << "unable to translate in big endian mode";
1766     reportTranslationError(*MF, *TPC, *ORE, R);
1767   }
1768 
1769   // Release the per-function state when we return, whether we succeeded or not.
1770   auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1771 
1772   // Setup a separate basic-block for the arguments and constants
1773   MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1774   MF->push_back(EntryBB);
1775   EntryBuilder->setMBB(*EntryBB);
1776 
1777   // Create all blocks, in IR order, to preserve the layout.
1778   for (const BasicBlock &BB: F) {
1779     auto *&MBB = BBToMBB[&BB];
1780 
1781     MBB = MF->CreateMachineBasicBlock(&BB);
1782     MF->push_back(MBB);
1783 
1784     if (BB.hasAddressTaken())
1785       MBB->setHasAddressTaken();
1786   }
1787 
1788   // Make our arguments/constants entry block fallthrough to the IR entry block.
1789   EntryBB->addSuccessor(&getMBB(F.front()));
1790 
1791   // Lower the actual args into this basic block.
1792   SmallVector<unsigned, 8> VRegArgs;
1793   for (const Argument &Arg: F.args()) {
1794     if (DL->getTypeStoreSize(Arg.getType()) == 0)
1795       continue; // Don't handle zero sized types.
1796     VRegArgs.push_back(
1797         MRI->createGenericVirtualRegister(getLLTForType(*Arg.getType(), *DL)));
1798   }
1799 
1800   // We don't currently support translating swifterror or swiftself functions.
1801   for (auto &Arg : F.args()) {
1802     if (Arg.hasSwiftErrorAttr() || Arg.hasSwiftSelfAttr()) {
1803       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1804                                  F.getSubprogram(), &F.getEntryBlock());
1805       R << "unable to lower arguments due to swifterror/swiftself: "
1806         << ore::NV("Prototype", F.getType());
1807       reportTranslationError(*MF, *TPC, *ORE, R);
1808       return false;
1809     }
1810   }
1811 
1812   if (!CLI->lowerFormalArguments(*EntryBuilder.get(), F, VRegArgs)) {
1813     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1814                                F.getSubprogram(), &F.getEntryBlock());
1815     R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1816     reportTranslationError(*MF, *TPC, *ORE, R);
1817     return false;
1818   }
1819 
1820   auto ArgIt = F.arg_begin();
1821   for (auto &VArg : VRegArgs) {
1822     // If the argument is an unsplit scalar then don't use unpackRegs to avoid
1823     // creating redundant copies.
1824     if (!valueIsSplit(*ArgIt, VMap.getOffsets(*ArgIt))) {
1825       auto &VRegs = *VMap.getVRegs(cast<Value>(*ArgIt));
1826       assert(VRegs.empty() && "VRegs already populated?");
1827       VRegs.push_back(VArg);
1828     } else {
1829       unpackRegs(*ArgIt, VArg, *EntryBuilder.get());
1830     }
1831     ArgIt++;
1832   }
1833 
1834   // Need to visit defs before uses when translating instructions.
1835   GISelObserverWrapper WrapperObserver;
1836   if (EnableCSE && CSEInfo)
1837     WrapperObserver.addObserver(CSEInfo);
1838   {
1839     ReversePostOrderTraversal<const Function *> RPOT(&F);
1840 #ifndef NDEBUG
1841     DILocationVerifier Verifier;
1842     WrapperObserver.addObserver(&Verifier);
1843 #endif // ifndef NDEBUG
1844     RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
1845     for (const BasicBlock *BB : RPOT) {
1846       MachineBasicBlock &MBB = getMBB(*BB);
1847       // Set the insertion point of all the following translations to
1848       // the end of this basic block.
1849       CurBuilder->setMBB(MBB);
1850 
1851       for (const Instruction &Inst : *BB) {
1852 #ifndef NDEBUG
1853         Verifier.setCurrentInst(&Inst);
1854 #endif // ifndef NDEBUG
1855         if (translate(Inst))
1856           continue;
1857 
1858         OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1859                                    Inst.getDebugLoc(), BB);
1860         R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
1861 
1862         if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
1863           std::string InstStrStorage;
1864           raw_string_ostream InstStr(InstStrStorage);
1865           InstStr << Inst;
1866 
1867           R << ": '" << InstStr.str() << "'";
1868         }
1869 
1870         reportTranslationError(*MF, *TPC, *ORE, R);
1871         return false;
1872       }
1873     }
1874 #ifndef NDEBUG
1875     WrapperObserver.removeObserver(&Verifier);
1876 #endif
1877   }
1878 
1879   finishPendingPhis();
1880 
1881   // Merge the argument lowering and constants block with its single
1882   // successor, the LLVM-IR entry block.  We want the basic block to
1883   // be maximal.
1884   assert(EntryBB->succ_size() == 1 &&
1885          "Custom BB used for lowering should have only one successor");
1886   // Get the successor of the current entry block.
1887   MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1888   assert(NewEntryBB.pred_size() == 1 &&
1889          "LLVM-IR entry block has a predecessor!?");
1890   // Move all the instruction from the current entry block to the
1891   // new entry block.
1892   NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1893                     EntryBB->end());
1894 
1895   // Update the live-in information for the new entry block.
1896   for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1897     NewEntryBB.addLiveIn(LiveIn);
1898   NewEntryBB.sortUniqueLiveIns();
1899 
1900   // Get rid of the now empty basic block.
1901   EntryBB->removeSuccessor(&NewEntryBB);
1902   MF->remove(EntryBB);
1903   MF->DeleteMachineBasicBlock(EntryBB);
1904 
1905   assert(&MF->front() == &NewEntryBB &&
1906          "New entry wasn't next in the list of basic block!");
1907 
1908   // Initialize stack protector information.
1909   StackProtector &SP = getAnalysis<StackProtector>();
1910   SP.copyToMachineFrameInfo(MF->getFrameInfo());
1911 
1912   return false;
1913 }
1914