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