LCOV - code coverage report
Current view: top level - lib/CodeGen/GlobalISel - IRTranslator.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 745 771 96.6 %
Date: 2018-07-13 00:08:38 Functions: 54 54 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13