LCOV - code coverage report
Current view: top level - lib/CodeGen/GlobalISel - IRTranslator.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 632 651 97.1 %
Date: 2018-02-22 04:41:24 Functions: 44 44 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       59636 : INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
      78             :                 false, false)
      79       59636 : INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
      80      602226 : 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         616 : IRTranslator::IRTranslator() : MachineFunctionPass(ID) {
     101         154 :   initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
     102         154 : }
     103             : 
     104         151 : void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
     105             :   AU.addRequired<TargetPassConfig>();
     106         151 :   MachineFunctionPass::getAnalysisUsage(AU);
     107         151 : }
     108             : 
     109        5879 : unsigned IRTranslator::getOrCreateVReg(const Value &Val) {
     110       11758 :   unsigned &ValReg = ValToVReg[&Val];
     111             : 
     112        5879 :   if (ValReg)
     113             :     return ValReg;
     114             : 
     115             :   // Fill ValRegsSequence with the sequence of registers
     116             :   // we need to concat together to produce the value.
     117             :   assert(Val.getType()->isSized() &&
     118             :          "Don't know how to create an empty vreg");
     119             :   unsigned VReg =
     120        3250 :       MRI->createGenericVirtualRegister(getLLTForType(*Val.getType(), *DL));
     121        3250 :   ValReg = VReg;
     122             : 
     123             :   if (auto CV = dyn_cast<Constant>(&Val)) {
     124         561 :     bool Success = translate(*CV, VReg);
     125         561 :     if (!Success) {
     126             :       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
     127           2 :                                  MF->getFunction().getSubprogram(),
     128           6 :                                  &MF->getFunction().getEntryBlock());
     129           4 :       R << "unable to translate constant: " << ore::NV("Type", Val.getType());
     130           2 :       reportTranslationError(*MF, *TPC, *ORE, R);
     131             :       return VReg;
     132             :     }
     133             :   }
     134             : 
     135             :   return VReg;
     136             : }
     137             : 
     138          30 : int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
     139          30 :   if (FrameIndices.find(&AI) != FrameIndices.end())
     140           4 :     return FrameIndices[&AI];
     141             : 
     142          56 :   unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
     143             :   unsigned Size =
     144          28 :       ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
     145             : 
     146             :   // Always allocate at least one byte.
     147          56 :   Size = std::max(Size, 1u);
     148             : 
     149             :   unsigned Alignment = AI.getAlignment();
     150          28 :   if (!Alignment)
     151          13 :     Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
     152             : 
     153          56 :   int &FI = FrameIndices[&AI];
     154          28 :   FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
     155          28 :   return FI;
     156             : }
     157             : 
     158         408 : unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
     159             :   unsigned Alignment = 0;
     160             :   Type *ValTy = nullptr;
     161             :   if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
     162             :     Alignment = SI->getAlignment();
     163         195 :     ValTy = SI->getValueOperand()->getType();
     164             :   } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
     165             :     Alignment = LI->getAlignment();
     166         213 :     ValTy = LI->getType();
     167             :   } else {
     168           0 :     OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
     169           0 :     R << "unable to translate memop: " << ore::NV("Opcode", &I);
     170           0 :     reportTranslationError(*MF, *TPC, *ORE, R);
     171             :     return 1;
     172             :   }
     173             : 
     174         408 :   return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
     175             : }
     176             : 
     177        2280 : MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
     178        4560 :   MachineBasicBlock *&MBB = BBToMBB[&BB];
     179             :   assert(MBB && "BasicBlock was not encountered before");
     180        2280 :   return *MBB;
     181             : }
     182             : 
     183          11 : void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
     184             :   assert(NewPred && "new predecessor must be a real MachineBasicBlock");
     185          22 :   MachinePreds[Edge].push_back(NewPred);
     186          11 : }
     187             : 
     188         397 : bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
     189             :                                      MachineIRBuilder &MIRBuilder) {
     190             :   // FIXME: handle signed/unsigned wrapping flags.
     191             : 
     192             :   // Get or create a virtual register for each value.
     193             :   // Unless the value is a Constant => loadimm cst?
     194             :   // or inline constant each time?
     195             :   // Creation of a virtual register needs to have a size.
     196         397 :   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
     197         397 :   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
     198         397 :   unsigned Res = getOrCreateVReg(U);
     199         794 :   MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
     200         397 :   return true;
     201             : }
     202             : 
     203          23 : bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
     204             :   // -0.0 - X --> G_FNEG
     205          25 :   if (isa<Constant>(U.getOperand(0)) &&
     206           2 :       U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
     207           4 :     MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
     208           2 :         .addDef(getOrCreateVReg(U))
     209           2 :         .addUse(getOrCreateVReg(*U.getOperand(1)));
     210           2 :     return true;
     211             :   }
     212          21 :   return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
     213             : }
     214             : 
     215          45 : bool IRTranslator::translateCompare(const User &U,
     216             :                                     MachineIRBuilder &MIRBuilder) {
     217             :   const CmpInst *CI = dyn_cast<CmpInst>(&U);
     218          45 :   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
     219          45 :   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
     220          45 :   unsigned Res = getOrCreateVReg(U);
     221             :   CmpInst::Predicate Pred =
     222          45 :       CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
     223             :                                     cast<ConstantExpr>(U).getPredicate());
     224          45 :   if (CmpInst::isIntPredicate(Pred))
     225          36 :     MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
     226           9 :   else if (Pred == CmpInst::FCMP_FALSE)
     227           1 :     MIRBuilder.buildCopy(
     228           1 :         Res, getOrCreateVReg(*Constant::getNullValue(CI->getType())));
     229           8 :   else if (Pred == CmpInst::FCMP_TRUE)
     230           1 :     MIRBuilder.buildCopy(
     231           1 :         Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType())));
     232             :   else
     233           7 :     MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
     234             : 
     235          45 :   return true;
     236             : }
     237             : 
     238         932 : bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
     239             :   const ReturnInst &RI = cast<ReturnInst>(U);
     240             :   const Value *Ret = RI.getReturnValue();
     241        1466 :   if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
     242             :     Ret = nullptr;
     243             :   // The target may mess up with the insertion point, but
     244             :   // this is not important as a return is the last instruction
     245             :   // of the block anyway.
     246         932 :   return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret));
     247             : }
     248             : 
     249          70 : bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
     250             :   const BranchInst &BrInst = cast<BranchInst>(U);
     251             :   unsigned Succ = 0;
     252          70 :   if (!BrInst.isUnconditional()) {
     253             :     // We want a G_BRCOND to the true BB followed by an unconditional branch.
     254          22 :     unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
     255             :     const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
     256          22 :     MachineBasicBlock &TrueBB = getMBB(TrueTgt);
     257          22 :     MIRBuilder.buildBrCond(Tst, TrueBB);
     258             :   }
     259             : 
     260             :   const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
     261          70 :   MachineBasicBlock &TgtBB = getMBB(BrTgt);
     262          70 :   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
     263             : 
     264             :   // If the unconditional target is the layout successor, fallthrough.
     265          70 :   if (!CurBB.isLayoutSuccessor(&TgtBB))
     266          46 :     MIRBuilder.buildBr(TgtBB);
     267             : 
     268             :   // Link successors.
     269         232 :   for (const BasicBlock *Succ : BrInst.successors())
     270          92 :     CurBB.addSuccessor(&getMBB(*Succ));
     271          70 :   return true;
     272             : }
     273             : 
     274           3 : bool IRTranslator::translateSwitch(const User &U,
     275             :                                    MachineIRBuilder &MIRBuilder) {
     276             :   // For now, just translate as a chain of conditional branches.
     277             :   // FIXME: could we share most of the logic/code in
     278             :   // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
     279             :   // At first sight, it seems most of the logic in there is independent of
     280             :   // SelectionDAG-specifics and a lot of work went in to optimize switch
     281             :   // lowering in there.
     282             : 
     283             :   const SwitchInst &SwInst = cast<SwitchInst>(U);
     284           3 :   const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
     285           3 :   const BasicBlock *OrigBB = SwInst.getParent();
     286             : 
     287           3 :   LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
     288          14 :   for (auto &CaseIt : SwInst.cases()) {
     289           8 :     const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
     290           8 :     const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
     291           8 :     MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
     292           8 :     MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
     293           8 :     const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
     294           8 :     MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
     295             : 
     296           8 :     MIRBuilder.buildBrCond(Tst, TrueMBB);
     297           8 :     CurMBB.addSuccessor(&TrueMBB);
     298           8 :     addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
     299             : 
     300             :     MachineBasicBlock *FalseMBB =
     301           8 :         MF->CreateMachineBasicBlock(SwInst.getParent());
     302             :     // Insert the comparison blocks one after the other.
     303           8 :     MF->insert(std::next(CurMBB.getIterator()), FalseMBB);
     304           8 :     MIRBuilder.buildBr(*FalseMBB);
     305           8 :     CurMBB.addSuccessor(FalseMBB);
     306             : 
     307           8 :     MIRBuilder.setMBB(*FalseMBB);
     308             :   }
     309             :   // handle default case
     310             :   const BasicBlock *DefaultBB = SwInst.getDefaultDest();
     311           3 :   MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
     312           3 :   MIRBuilder.buildBr(DefaultMBB);
     313           3 :   MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
     314           3 :   CurMBB.addSuccessor(&DefaultMBB);
     315           3 :   addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
     316             : 
     317           3 :   return true;
     318             : }
     319             : 
     320           2 : bool IRTranslator::translateIndirectBr(const User &U,
     321             :                                        MachineIRBuilder &MIRBuilder) {
     322             :   const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
     323             : 
     324           2 :   const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
     325           2 :   MIRBuilder.buildBrIndirect(Tgt);
     326             : 
     327             :   // Link successors.
     328           2 :   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
     329           8 :   for (const BasicBlock *Succ : BrInst.successors())
     330           4 :     CurBB.addSuccessor(&getMBB(*Succ));
     331             : 
     332           2 :   return true;
     333             : }
     334             : 
     335         214 : bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
     336             :   const LoadInst &LI = cast<LoadInst>(U);
     337             : 
     338         214 :   auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
     339             :                                : MachineMemOperand::MONone;
     340             :   Flags |= MachineMemOperand::MOLoad;
     341             : 
     342         428 :   if (DL->getTypeStoreSize(LI.getType()) == 0)
     343             :     return true;
     344             : 
     345         213 :   unsigned Res = getOrCreateVReg(LI);
     346         213 :   unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
     347             : 
     348         213 :   MIRBuilder.buildLoad(
     349             :       Res, Addr,
     350        1491 :       *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()),
     351         213 :                                 Flags, DL->getTypeStoreSize(LI.getType()),
     352         213 :                                 getMemOpAlignment(LI), AAMDNodes(), nullptr,
     353         213 :                                 LI.getSyncScopeID(), LI.getOrdering()));
     354         213 :   return true;
     355             : }
     356             : 
     357         196 : bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
     358             :   const StoreInst &SI = cast<StoreInst>(U);
     359         196 :   auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
     360             :                                : MachineMemOperand::MONone;
     361             :   Flags |= MachineMemOperand::MOStore;
     362             : 
     363         588 :   if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
     364             :     return true;
     365             : 
     366         195 :   unsigned Val = getOrCreateVReg(*SI.getValueOperand());
     367         195 :   unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
     368             : 
     369         195 :   MIRBuilder.buildStore(
     370             :       Val, Addr,
     371        1365 :       *MF->getMachineMemOperand(
     372             :           MachinePointerInfo(SI.getPointerOperand()), Flags,
     373         195 :           DL->getTypeStoreSize(SI.getValueOperand()->getType()),
     374         390 :           getMemOpAlignment(SI), AAMDNodes(), nullptr, SI.getSyncScopeID(),
     375             :           SI.getOrdering()));
     376         195 :   return true;
     377             : }
     378             : 
     379           9 : bool IRTranslator::translateExtractValue(const User &U,
     380             :                                          MachineIRBuilder &MIRBuilder) {
     381             :   const Value *Src = U.getOperand(0);
     382           9 :   Type *Int32Ty = Type::getInt32Ty(U.getContext());
     383             :   SmallVector<Value *, 1> Indices;
     384             : 
     385             :   // If Src is a single element ConstantStruct, translate extractvalue
     386             :   // to that element to avoid inserting a cast instruction.
     387             :   if (auto CS = dyn_cast<ConstantStruct>(Src))
     388           4 :     if (CS->getNumOperands() == 1) {
     389           4 :       unsigned Res = getOrCreateVReg(*CS->getOperand(0));
     390           4 :       ValToVReg[&U] = Res;
     391           2 :       return true;
     392             :     }
     393             : 
     394             :   // getIndexedOffsetInType is designed for GEPs, so the first index is the
     395             :   // usual array element rather than looking into the actual aggregate.
     396           7 :   Indices.push_back(ConstantInt::get(Int32Ty, 0));
     397             : 
     398             :   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
     399          23 :     for (auto Idx : EVI->indices())
     400           8 :       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
     401             :   } else {
     402           0 :     for (unsigned i = 1; i < U.getNumOperands(); ++i)
     403           0 :       Indices.push_back(U.getOperand(i));
     404             :   }
     405             : 
     406          14 :   uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
     407             : 
     408           7 :   unsigned Res = getOrCreateVReg(U);
     409           7 :   MIRBuilder.buildExtract(Res, getOrCreateVReg(*Src), Offset);
     410             : 
     411           7 :   return true;
     412             : }
     413             : 
     414           7 : bool IRTranslator::translateInsertValue(const User &U,
     415             :                                         MachineIRBuilder &MIRBuilder) {
     416             :   const Value *Src = U.getOperand(0);
     417           7 :   Type *Int32Ty = Type::getInt32Ty(U.getContext());
     418             :   SmallVector<Value *, 1> Indices;
     419             : 
     420             :   // getIndexedOffsetInType is designed for GEPs, so the first index is the
     421             :   // usual array element rather than looking into the actual aggregate.
     422           7 :   Indices.push_back(ConstantInt::get(Int32Ty, 0));
     423             : 
     424             :   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
     425          23 :     for (auto Idx : IVI->indices())
     426           8 :       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
     427             :   } else {
     428           0 :     for (unsigned i = 2; i < U.getNumOperands(); ++i)
     429           0 :       Indices.push_back(U.getOperand(i));
     430             :   }
     431             : 
     432          14 :   uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
     433             : 
     434           7 :   unsigned Res = getOrCreateVReg(U);
     435           7 :   unsigned Inserted = getOrCreateVReg(*U.getOperand(1));
     436           7 :   MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), Inserted, Offset);
     437             : 
     438           7 :   return true;
     439             : }
     440             : 
     441           6 : bool IRTranslator::translateSelect(const User &U,
     442             :                                    MachineIRBuilder &MIRBuilder) {
     443           6 :   unsigned Res = getOrCreateVReg(U);
     444           6 :   unsigned Tst = getOrCreateVReg(*U.getOperand(0));
     445           6 :   unsigned Op0 = getOrCreateVReg(*U.getOperand(1));
     446           6 :   unsigned Op1 = getOrCreateVReg(*U.getOperand(2));
     447           6 :   MIRBuilder.buildSelect(Res, Tst, Op0, Op1);
     448           6 :   return true;
     449             : }
     450             : 
     451          15 : bool IRTranslator::translateBitCast(const User &U,
     452             :                                     MachineIRBuilder &MIRBuilder) {
     453             :   // If we're bitcasting to the source type, we can reuse the source vreg.
     454          45 :   if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
     455          30 :       getLLTForType(*U.getType(), *DL)) {
     456             :     // Get the source vreg now, to avoid invalidating ValToVReg.
     457          13 :     unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
     458          26 :     unsigned &Reg = ValToVReg[&U];
     459             :     // If we already assigned a vreg for this bitcast, we can't change that.
     460             :     // Emit a copy to satisfy the users we already emitted.
     461          13 :     if (Reg)
     462           3 :       MIRBuilder.buildCopy(Reg, SrcReg);
     463             :     else
     464          10 :       Reg = SrcReg;
     465             :     return true;
     466             :   }
     467           2 :   return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
     468             : }
     469             : 
     470         135 : bool IRTranslator::translateCast(unsigned Opcode, const User &U,
     471             :                                  MachineIRBuilder &MIRBuilder) {
     472         135 :   unsigned Op = getOrCreateVReg(*U.getOperand(0));
     473         135 :   unsigned Res = getOrCreateVReg(U);
     474         270 :   MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
     475         135 :   return true;
     476             : }
     477             : 
     478          47 : bool IRTranslator::translateGetElementPtr(const User &U,
     479             :                                           MachineIRBuilder &MIRBuilder) {
     480             :   // FIXME: support vector GEPs.
     481          94 :   if (U.getType()->isVectorTy())
     482             :     return false;
     483             : 
     484             :   Value &Op0 = *U.getOperand(0);
     485          47 :   unsigned BaseReg = getOrCreateVReg(Op0);
     486          47 :   Type *PtrIRTy = Op0.getType();
     487          47 :   LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
     488          47 :   Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
     489          47 :   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
     490             : 
     491             :   int64_t Offset = 0;
     492         114 :   for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
     493         114 :        GTI != E; ++GTI) {
     494             :     const Value *Idx = GTI.getOperand();
     495           6 :     if (StructType *StTy = GTI.getStructTypeOrNull()) {
     496          12 :       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
     497          12 :       Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
     498           6 :       continue;
     499             :     } else {
     500          61 :       uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
     501             : 
     502             :       // If this is a scalar constant or a splat vector of constants,
     503             :       // handle it quickly.
     504          49 :       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
     505          49 :         Offset += ElementSize * CI->getSExtValue();
     506          49 :         continue;
     507             :       }
     508             : 
     509          12 :       if (Offset != 0) {
     510           1 :         unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
     511             :         unsigned OffsetReg =
     512           1 :             getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
     513           1 :         MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
     514             : 
     515             :         BaseReg = NewBaseReg;
     516             :         Offset = 0;
     517             :       }
     518             : 
     519          12 :       unsigned IdxReg = getOrCreateVReg(*Idx);
     520          24 :       if (MRI->getType(IdxReg) != OffsetTy) {
     521           5 :         unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
     522           5 :         MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
     523             :         IdxReg = NewIdxReg;
     524             :       }
     525             : 
     526             :       // N = N + Idx * ElementSize;
     527             :       // Avoid doing it for ElementSize of 1.
     528             :       unsigned GepOffsetReg;
     529          12 :       if (ElementSize != 1) {
     530             :         unsigned ElementSizeReg =
     531          10 :             getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize));
     532             : 
     533          10 :         GepOffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
     534          10 :         MIRBuilder.buildMul(GepOffsetReg, ElementSizeReg, IdxReg);
     535             :       } else
     536             :         GepOffsetReg = IdxReg;
     537             : 
     538          12 :       unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
     539          12 :       MIRBuilder.buildGEP(NewBaseReg, BaseReg, GepOffsetReg);
     540             :       BaseReg = NewBaseReg;
     541             :     }
     542             :   }
     543             : 
     544          47 :   if (Offset != 0) {
     545          27 :     unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
     546          27 :     MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
     547          27 :     return true;
     548             :   }
     549             : 
     550          20 :   MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
     551          20 :   return true;
     552             : }
     553             : 
     554           3 : bool IRTranslator::translateMemfunc(const CallInst &CI,
     555             :                                     MachineIRBuilder &MIRBuilder,
     556             :                                     unsigned ID) {
     557           6 :   LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
     558           3 :   Type *DstTy = CI.getArgOperand(0)->getType();
     559           6 :   if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
     560           3 :       SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
     561             :     return false;
     562             : 
     563             :   SmallVector<CallLowering::ArgInfo, 8> Args;
     564          21 :   for (int i = 0; i < 3; ++i) {
     565           9 :     const auto &Arg = CI.getArgOperand(i);
     566           9 :     Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
     567             :   }
     568             : 
     569             :   const char *Callee;
     570           3 :   switch (ID) {
     571             :   case Intrinsic::memmove:
     572             :   case Intrinsic::memcpy: {
     573           2 :     Type *SrcTy = CI.getArgOperand(1)->getType();
     574           2 :     if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
     575             :       return false;
     576           2 :     Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
     577             :     break;
     578             :   }
     579             :   case Intrinsic::memset:
     580             :     Callee = "memset";
     581             :     break;
     582             :   default:
     583             :     return false;
     584             :   }
     585             : 
     586           6 :   return CLI->lowerCall(MIRBuilder, CI.getCallingConv(),
     587           3 :                         MachineOperand::CreateES(Callee),
     588          12 :                         CallLowering::ArgInfo(0, CI.getType()), Args);
     589             : }
     590             : 
     591           1 : void IRTranslator::getStackGuard(unsigned DstReg,
     592             :                                  MachineIRBuilder &MIRBuilder) {
     593           1 :   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
     594           1 :   MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
     595           1 :   auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
     596             :   MIB.addDef(DstReg);
     597             : 
     598           1 :   auto &TLI = *MF->getSubtarget().getTargetLowering();
     599           1 :   Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
     600           1 :   if (!Global)
     601           0 :     return;
     602             : 
     603             :   MachinePointerInfo MPInfo(Global);
     604           1 :   MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
     605             :   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
     606             :                MachineMemOperand::MODereferenceable;
     607           1 :   *MemRefs =
     608           4 :       MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
     609           1 :                                DL->getPointerABIAlignment(0));
     610             :   MIB.setMemRefs(MemRefs, MemRefs + 1);
     611             : }
     612             : 
     613           6 : bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
     614             :                                               MachineIRBuilder &MIRBuilder) {
     615          12 :   LLT Ty = getLLTForType(*CI.getOperand(0)->getType(), *DL);
     616           6 :   LLT s1 = LLT::scalar(1);
     617           6 :   unsigned Width = Ty.getSizeInBits();
     618           6 :   unsigned Res = MRI->createGenericVirtualRegister(Ty);
     619           6 :   unsigned Overflow = MRI->createGenericVirtualRegister(s1);
     620          12 :   auto MIB = MIRBuilder.buildInstr(Op)
     621             :                  .addDef(Res)
     622             :                  .addDef(Overflow)
     623           6 :                  .addUse(getOrCreateVReg(*CI.getOperand(0)))
     624          12 :                  .addUse(getOrCreateVReg(*CI.getOperand(1)));
     625             : 
     626           6 :   if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
     627           2 :     unsigned Zero = getOrCreateVReg(
     628           4 :         *Constant::getNullValue(Type::getInt1Ty(CI.getContext())));
     629             :     MIB.addUse(Zero);
     630             :   }
     631             : 
     632          18 :   MIRBuilder.buildSequence(getOrCreateVReg(CI), {Res, Overflow}, {0, Width});
     633           6 :   return true;
     634             : }
     635             : 
     636          60 : bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
     637             :                                            MachineIRBuilder &MIRBuilder) {
     638          60 :   switch (ID) {
     639             :   default:
     640             :     break;
     641           2 :   case Intrinsic::lifetime_start:
     642             :   case Intrinsic::lifetime_end:
     643             :     // Stack coloring is not enabled in O0 (which we care about now) so we can
     644             :     // drop these. Make sure someone notices when we start compiling at higher
     645             :     // opts though.
     646           2 :     if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
     647             :       return false;
     648           2 :     return true;
     649             :   case Intrinsic::dbg_declare: {
     650             :     const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
     651             :     assert(DI.getVariable() && "Missing variable");
     652             : 
     653             :     const Value *Address = DI.getAddress();
     654           6 :     if (!Address || isa<UndefValue>(Address)) {
     655             :       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
     656             :       return true;
     657             :     }
     658             : 
     659             :     assert(DI.getVariable()->isValidLocationForIntrinsic(
     660             :                MIRBuilder.getDebugLoc()) &&
     661             :            "Expected inlined-at fields to agree");
     662             :     auto AI = dyn_cast<AllocaInst>(Address);
     663           2 :     if (AI && AI->isStaticAlloca()) {
     664             :       // Static allocas are tracked at the MF level, no need for DBG_VALUE
     665             :       // instructions (in fact, they get ignored if they *do* exist).
     666           2 :       MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
     667           1 :                              getOrCreateFrameIndex(*AI), DI.getDebugLoc());
     668             :     } else
     669           2 :       MIRBuilder.buildDirectDbgValue(getOrCreateVReg(*Address),
     670           2 :                                      DI.getVariable(), DI.getExpression());
     671             :     return true;
     672             :   }
     673             :   case Intrinsic::vaend:
     674             :     // No target I know of cares about va_end. Certainly no in-tree target
     675             :     // does. Simplest intrinsic ever!
     676             :     return true;
     677           3 :   case Intrinsic::vastart: {
     678           3 :     auto &TLI = *MF->getSubtarget().getTargetLowering();
     679             :     Value *Ptr = CI.getArgOperand(0);
     680           3 :     unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
     681             : 
     682           6 :     MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
     683           3 :         .addUse(getOrCreateVReg(*Ptr))
     684           3 :         .addMemOperand(MF->getMachineMemOperand(
     685           9 :             MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
     686           3 :     return true;
     687             :   }
     688             :   case Intrinsic::dbg_value: {
     689             :     // This form of DBG_VALUE is target-independent.
     690             :     const DbgValueInst &DI = cast<DbgValueInst>(CI);
     691             :     const Value *V = DI.getValue();
     692             :     assert(DI.getVariable()->isValidLocationForIntrinsic(
     693             :                MIRBuilder.getDebugLoc()) &&
     694             :            "Expected inlined-at fields to agree");
     695          13 :     if (!V) {
     696             :       // Currently the optimizer can produce this; insert an undef to
     697             :       // help debugging.  Probably the optimizer should not do this.
     698           0 :       MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
     699             :     } else if (const auto *CI = dyn_cast<Constant>(V)) {
     700           5 :       MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
     701             :     } else {
     702           8 :       unsigned Reg = getOrCreateVReg(*V);
     703             :       // FIXME: This does not handle register-indirect values at offset 0. The
     704             :       // direct/indirect thing shouldn't really be handled by something as
     705             :       // implicit as reg+noreg vs reg+imm in the first palce, but it seems
     706             :       // pretty baked in right now.
     707           8 :       MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
     708             :     }
     709             :     return true;
     710             :   }
     711           1 :   case Intrinsic::uadd_with_overflow:
     712           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
     713           1 :   case Intrinsic::sadd_with_overflow:
     714           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
     715           1 :   case Intrinsic::usub_with_overflow:
     716           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
     717           1 :   case Intrinsic::ssub_with_overflow:
     718           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
     719           1 :   case Intrinsic::umul_with_overflow:
     720           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
     721           1 :   case Intrinsic::smul_with_overflow:
     722           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
     723           7 :   case Intrinsic::pow:
     724          14 :     MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
     725           7 :         .addDef(getOrCreateVReg(CI))
     726           7 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
     727           7 :         .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
     728           7 :     return true;
     729           1 :   case Intrinsic::exp:
     730           2 :     MIRBuilder.buildInstr(TargetOpcode::G_FEXP)
     731           1 :         .addDef(getOrCreateVReg(CI))
     732           1 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     733           1 :     return true;
     734           1 :   case Intrinsic::exp2:
     735           2 :     MIRBuilder.buildInstr(TargetOpcode::G_FEXP2)
     736           1 :         .addDef(getOrCreateVReg(CI))
     737           1 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     738           1 :     return true;
     739           1 :   case Intrinsic::log:
     740           2 :     MIRBuilder.buildInstr(TargetOpcode::G_FLOG)
     741           1 :         .addDef(getOrCreateVReg(CI))
     742           1 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     743           1 :     return true;
     744           1 :   case Intrinsic::log2:
     745           2 :     MIRBuilder.buildInstr(TargetOpcode::G_FLOG2)
     746           1 :         .addDef(getOrCreateVReg(CI))
     747           1 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     748           1 :     return true;
     749           1 :   case Intrinsic::fma:
     750           2 :     MIRBuilder.buildInstr(TargetOpcode::G_FMA)
     751           1 :         .addDef(getOrCreateVReg(CI))
     752           1 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
     753           1 :         .addUse(getOrCreateVReg(*CI.getArgOperand(1)))
     754           1 :         .addUse(getOrCreateVReg(*CI.getArgOperand(2)));
     755           1 :     return true;
     756           2 :   case Intrinsic::fmuladd: {
     757           2 :     const TargetMachine &TM = MF->getTarget();
     758           2 :     const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
     759           2 :     unsigned Dst = getOrCreateVReg(CI);
     760           2 :     unsigned Op0 = getOrCreateVReg(*CI.getArgOperand(0));
     761           2 :     unsigned Op1 = getOrCreateVReg(*CI.getArgOperand(1));
     762           2 :     unsigned Op2 = getOrCreateVReg(*CI.getArgOperand(2));
     763           3 :     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
     764           1 :         TLI.isFMAFasterThanFMulAndFAdd(TLI.getValueType(*DL, CI.getType()))) {
     765             :       // TODO: Revisit this to see if we should move this part of the
     766             :       // lowering to the combiner.
     767           1 :       MIRBuilder.buildInstr(TargetOpcode::G_FMA, Dst, Op0, Op1, Op2);
     768             :     } else {
     769           1 :       LLT Ty = getLLTForType(*CI.getType(), *DL);
     770           1 :       auto FMul = MIRBuilder.buildInstr(TargetOpcode::G_FMUL, Ty, Op0, Op1);
     771           1 :       MIRBuilder.buildInstr(TargetOpcode::G_FADD, Dst, FMul, Op2);
     772             :     }
     773             :     return true;
     774             :   }
     775           3 :   case Intrinsic::memcpy:
     776             :   case Intrinsic::memmove:
     777             :   case Intrinsic::memset:
     778           3 :     return translateMemfunc(CI, MIRBuilder, ID);
     779             :   case Intrinsic::eh_typeid_for: {
     780           1 :     GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
     781           1 :     unsigned Reg = getOrCreateVReg(CI);
     782           1 :     unsigned TypeID = MF->getTypeIDFor(GV);
     783           1 :     MIRBuilder.buildConstant(Reg, TypeID);
     784           1 :     return true;
     785             :   }
     786             :   case Intrinsic::objectsize: {
     787             :     // If we don't know by now, we're never going to know.
     788             :     const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
     789             : 
     790           4 :     MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
     791           4 :     return true;
     792             :   }
     793           0 :   case Intrinsic::stackguard:
     794           0 :     getStackGuard(getOrCreateVReg(CI), MIRBuilder);
     795           0 :     return true;
     796           1 :   case Intrinsic::stackprotector: {
     797           2 :     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
     798           1 :     unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
     799           1 :     getStackGuard(GuardVal, MIRBuilder);
     800             : 
     801             :     AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
     802           1 :     MIRBuilder.buildStore(
     803             :         GuardVal, getOrCreateVReg(*Slot),
     804           4 :         *MF->getMachineMemOperand(
     805           1 :             MachinePointerInfo::getFixedStack(*MF,
     806             :                                               getOrCreateFrameIndex(*Slot)),
     807             :             MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
     808           2 :             PtrTy.getSizeInBits() / 8, 8));
     809             :     return true;
     810             :   }
     811             :   }
     812           9 :   return false;
     813             : }
     814             : 
     815           3 : bool IRTranslator::translateInlineAsm(const CallInst &CI,
     816             :                                       MachineIRBuilder &MIRBuilder) {
     817             :   const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
     818           3 :   if (!IA.getConstraintString().empty())
     819             :     return false;
     820             : 
     821             :   unsigned ExtraInfo = 0;
     822           2 :   if (IA.hasSideEffects())
     823             :     ExtraInfo |= InlineAsm::Extra_HasSideEffects;
     824           2 :   if (IA.getDialect() == InlineAsm::AD_Intel)
     825           0 :     ExtraInfo |= InlineAsm::Extra_AsmDialect;
     826             : 
     827           2 :   MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
     828             :     .addExternalSymbol(IA.getAsmString().c_str())
     829           2 :     .addImm(ExtraInfo);
     830             : 
     831           2 :   return true;
     832             : }
     833             : 
     834         194 : bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
     835             :   const CallInst &CI = cast<CallInst>(U);
     836         194 :   auto TII = MF->getTarget().getIntrinsicInfo();
     837             :   const Function *F = CI.getCalledFunction();
     838             : 
     839             :   // FIXME: support Windows dllimport function calls.
     840         183 :   if (F && F->hasDLLImportStorageClass())
     841             :     return false;
     842             : 
     843         193 :   if (CI.isInlineAsm())
     844           3 :     return translateInlineAsm(CI, MIRBuilder);
     845             : 
     846             :   Intrinsic::ID ID = Intrinsic::not_intrinsic;
     847         372 :   if (F && F->isIntrinsic()) {
     848          61 :     ID = F->getIntrinsicID();
     849          61 :     if (TII && ID == Intrinsic::not_intrinsic)
     850           0 :       ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
     851             :   }
     852             : 
     853         372 :   if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) {
     854         260 :     unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
     855             :     SmallVector<unsigned, 8> Args;
     856         368 :     for (auto &Arg: CI.arg_operands())
     857         238 :       Args.push_back(getOrCreateVReg(*Arg));
     858             : 
     859         130 :     MF->getFrameInfo().setHasCalls(true);
     860         390 :     return CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
     861           8 :       return getOrCreateVReg(*CI.getCalledValue());
     862         138 :     });
     863             :   }
     864             : 
     865             :   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
     866             : 
     867          60 :   if (translateKnownIntrinsic(CI, ID, MIRBuilder))
     868             :     return true;
     869             : 
     870          18 :   unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
     871             :   MachineInstrBuilder MIB =
     872           9 :       MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
     873             : 
     874          46 :   for (auto &Arg : CI.arg_operands()) {
     875             :     // Some intrinsics take metadata parameters. Reject them.
     876          39 :     if (isa<MetadataAsValue>(Arg))
     877             :       return false;
     878          37 :     MIB.addUse(getOrCreateVReg(*Arg));
     879             :   }
     880             : 
     881             :   // Add a MachineMemOperand if it is a target mem intrinsic.
     882           7 :   const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
     883           7 :   TargetLowering::IntrinsicInfo Info;
     884             :   // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
     885           7 :   if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
     886           2 :     uint64_t Size = Info.memVT.getStoreSize();
     887           2 :     MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
     888           4 :                                                Info.flags, Size, Info.align));
     889             :   }
     890             : 
     891             :   return true;
     892             : }
     893             : 
     894           6 : bool IRTranslator::translateInvoke(const User &U,
     895             :                                    MachineIRBuilder &MIRBuilder) {
     896             :   const InvokeInst &I = cast<InvokeInst>(U);
     897           6 :   MCContext &Context = MF->getContext();
     898             : 
     899             :   const BasicBlock *ReturnBB = I.getSuccessor(0);
     900             :   const BasicBlock *EHPadBB = I.getSuccessor(1);
     901             : 
     902             :   const Value *Callee = I.getCalledValue();
     903             :   const Function *Fn = dyn_cast<Function>(Callee);
     904           6 :   if (isa<InlineAsm>(Callee))
     905             :     return false;
     906             : 
     907             :   // FIXME: support invoking patchpoint and statepoint intrinsics.
     908           9 :   if (Fn && Fn->isIntrinsic())
     909             :     return false;
     910             : 
     911             :   // FIXME: support whatever these are.
     912           6 :   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
     913             :     return false;
     914             : 
     915             :   // FIXME: support Windows exception handling.
     916           6 :   if (!isa<LandingPadInst>(EHPadBB->front()))
     917             :     return false;
     918             : 
     919             :   // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
     920             :   // the region covered by the try.
     921           6 :   MCSymbol *BeginSymbol = Context.createTempSymbol();
     922          12 :   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
     923             : 
     924          12 :   unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I);
     925             :   SmallVector<unsigned, 8> Args;
     926          13 :   for (auto &Arg: I.arg_operands())
     927           7 :     Args.push_back(getOrCreateVReg(*Arg));
     928             : 
     929          18 :   if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
     930           6 :                       [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
     931             :     return false;
     932             : 
     933           4 :   MCSymbol *EndSymbol = Context.createTempSymbol();
     934           8 :   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
     935             : 
     936             :   // FIXME: track probabilities.
     937           4 :   MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
     938           4 :                     &ReturnMBB = getMBB(*ReturnBB);
     939           4 :   MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
     940           4 :   MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
     941           4 :   MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
     942           4 :   MIRBuilder.buildBr(ReturnMBB);
     943             : 
     944           4 :   return true;
     945             : }
     946             : 
     947           4 : bool IRTranslator::translateLandingPad(const User &U,
     948             :                                        MachineIRBuilder &MIRBuilder) {
     949             :   const LandingPadInst &LP = cast<LandingPadInst>(U);
     950             : 
     951           4 :   MachineBasicBlock &MBB = MIRBuilder.getMBB();
     952           4 :   addLandingPadInfo(LP, MBB);
     953             : 
     954             :   MBB.setIsEHPad();
     955             : 
     956             :   // If there aren't registers to copy the values into (e.g., during SjLj
     957             :   // exceptions), then don't bother.
     958           4 :   auto &TLI = *MF->getSubtarget().getTargetLowering();
     959           4 :   const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
     960           4 :   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
     961           0 :       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
     962             :     return true;
     963             : 
     964             :   // If landingpad's return type is token type, we don't create DAG nodes
     965             :   // for its exception pointer and selector value. The extraction of exception
     966             :   // pointer or selector value from token type landingpads is not currently
     967             :   // supported.
     968           8 :   if (LP.getType()->isTokenTy())
     969             :     return true;
     970             : 
     971             :   // Add a label to mark the beginning of the landing pad.  Deletion of the
     972             :   // landing pad can thus be detected via the MachineModuleInfo.
     973           8 :   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
     974           4 :     .addSym(MF->addLandingPad(&MBB));
     975             : 
     976           4 :   LLT Ty = getLLTForType(*LP.getType(), *DL);
     977           4 :   unsigned Undef = MRI->createGenericVirtualRegister(Ty);
     978           4 :   MIRBuilder.buildUndef(Undef);
     979             : 
     980             :   SmallVector<LLT, 2> Tys;
     981          24 :   for (Type *Ty : cast<StructType>(LP.getType())->elements())
     982           8 :     Tys.push_back(getLLTForType(*Ty, *DL));
     983             :   assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
     984             : 
     985             :   // Mark exception register as live in.
     986           4 :   unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
     987           4 :   if (!ExceptionReg)
     988             :     return false;
     989             : 
     990           4 :   MBB.addLiveIn(ExceptionReg);
     991           8 :   unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]),
     992           4 :            Tmp = MRI->createGenericVirtualRegister(Ty);
     993           4 :   MIRBuilder.buildCopy(VReg, ExceptionReg);
     994           4 :   MIRBuilder.buildInsert(Tmp, Undef, VReg, 0);
     995             : 
     996           4 :   unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
     997           4 :   if (!SelectorReg)
     998             :     return false;
     999             : 
    1000           4 :   MBB.addLiveIn(SelectorReg);
    1001             : 
    1002             :   // N.b. the exception selector register always has pointer type and may not
    1003             :   // match the actual IR-level type in the landingpad so an extra cast is
    1004             :   // needed.
    1005           8 :   unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
    1006           4 :   MIRBuilder.buildCopy(PtrVReg, SelectorReg);
    1007             : 
    1008           8 :   VReg = MRI->createGenericVirtualRegister(Tys[1]);
    1009           8 :   MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT).addDef(VReg).addUse(PtrVReg);
    1010           4 :   MIRBuilder.buildInsert(getOrCreateVReg(LP), Tmp, VReg,
    1011           4 :                          Tys[0].getSizeInBits());
    1012           4 :   return true;
    1013             : }
    1014             : 
    1015          33 : bool IRTranslator::translateAlloca(const User &U,
    1016             :                                    MachineIRBuilder &MIRBuilder) {
    1017             :   auto &AI = cast<AllocaInst>(U);
    1018             : 
    1019          33 :   if (AI.isStaticAlloca()) {
    1020          28 :     unsigned Res = getOrCreateVReg(AI);
    1021          28 :     int FI = getOrCreateFrameIndex(AI);
    1022          28 :     MIRBuilder.buildFrameIndex(Res, FI);
    1023          28 :     return true;
    1024             :   }
    1025             : 
    1026             :   // FIXME: support stack probing for Windows.
    1027          10 :   if (MF->getTarget().getTargetTriple().isOSWindows())
    1028             :     return false;
    1029             : 
    1030             :   // Now we're in the harder dynamic case.
    1031           4 :   Type *Ty = AI.getAllocatedType();
    1032             :   unsigned Align =
    1033           8 :       std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
    1034             : 
    1035           4 :   unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
    1036             : 
    1037           8 :   Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
    1038           4 :   LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
    1039           4 :   if (MRI->getType(NumElts) != IntPtrTy) {
    1040           4 :     unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
    1041           4 :     MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
    1042             :     NumElts = ExtElts;
    1043             :   }
    1044             : 
    1045           4 :   unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
    1046             :   unsigned TySize =
    1047           4 :       getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
    1048           4 :   MIRBuilder.buildMul(AllocSize, NumElts, TySize);
    1049             : 
    1050           8 :   LLT PtrTy = getLLTForType(*AI.getType(), *DL);
    1051           4 :   auto &TLI = *MF->getSubtarget().getTargetLowering();
    1052           4 :   unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
    1053             : 
    1054           4 :   unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
    1055           4 :   MIRBuilder.buildCopy(SPTmp, SPReg);
    1056             : 
    1057           4 :   unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
    1058           4 :   MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
    1059             : 
    1060             :   // Handle alignment. We have to realign if the allocation granule was smaller
    1061             :   // than stack alignment, or the specific alloca requires more than stack
    1062             :   // alignment.
    1063             :   unsigned StackAlign =
    1064           4 :       MF->getSubtarget().getFrameLowering()->getStackAlignment();
    1065           4 :   Align = std::max(Align, StackAlign);
    1066           4 :   if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
    1067             :     // Round the size of the allocation up to the stack alignment size
    1068             :     // by add SA-1 to the size. This doesn't overflow because we're computing
    1069             :     // an address inside an alloca.
    1070           3 :     unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
    1071           3 :     MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
    1072             :     AllocTmp = AlignedAlloc;
    1073             :   }
    1074             : 
    1075           4 :   MIRBuilder.buildCopy(SPReg, AllocTmp);
    1076           4 :   MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
    1077             : 
    1078           4 :   MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
    1079             :   assert(MF->getFrameInfo().hasVarSizedObjects());
    1080           4 :   return true;
    1081             : }
    1082             : 
    1083           3 : bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
    1084             :   // FIXME: We may need more info about the type. Because of how LLT works,
    1085             :   // we're completely discarding the i64/double distinction here (amongst
    1086             :   // others). Fortunately the ABIs I know of where that matters don't use va_arg
    1087             :   // anyway but that's not guaranteed.
    1088           6 :   MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
    1089           3 :     .addDef(getOrCreateVReg(U))
    1090           3 :     .addUse(getOrCreateVReg(*U.getOperand(0)))
    1091           3 :     .addImm(DL->getABITypeAlignment(U.getType()));
    1092           3 :   return true;
    1093             : }
    1094             : 
    1095          25 : bool IRTranslator::translateInsertElement(const User &U,
    1096             :                                           MachineIRBuilder &MIRBuilder) {
    1097             :   // If it is a <1 x Ty> vector, use the scalar as it is
    1098             :   // not a legal vector type in LLT.
    1099          50 :   if (U.getType()->getVectorNumElements() == 1) {
    1100           6 :     unsigned Elt = getOrCreateVReg(*U.getOperand(1));
    1101          12 :     ValToVReg[&U] = Elt;
    1102           6 :     return true;
    1103             :   }
    1104          19 :   unsigned Res = getOrCreateVReg(U);
    1105          19 :   unsigned Val = getOrCreateVReg(*U.getOperand(0));
    1106          19 :   unsigned Elt = getOrCreateVReg(*U.getOperand(1));
    1107          19 :   unsigned Idx = getOrCreateVReg(*U.getOperand(2));
    1108          19 :   MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
    1109          19 :   return true;
    1110             : }
    1111             : 
    1112          24 : bool IRTranslator::translateExtractElement(const User &U,
    1113             :                                            MachineIRBuilder &MIRBuilder) {
    1114             :   // If it is a <1 x Ty> vector, use the scalar as it is
    1115             :   // not a legal vector type in LLT.
    1116          48 :   if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
    1117           4 :     unsigned Elt = getOrCreateVReg(*U.getOperand(0));
    1118           8 :     ValToVReg[&U] = Elt;
    1119           4 :     return true;
    1120             :   }
    1121          20 :   unsigned Res = getOrCreateVReg(U);
    1122          20 :   unsigned Val = getOrCreateVReg(*U.getOperand(0));
    1123          20 :   unsigned Idx = getOrCreateVReg(*U.getOperand(1));
    1124          20 :   MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
    1125          20 :   return true;
    1126             : }
    1127             : 
    1128          15 : bool IRTranslator::translateShuffleVector(const User &U,
    1129             :                                           MachineIRBuilder &MIRBuilder) {
    1130          30 :   MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
    1131          15 :       .addDef(getOrCreateVReg(U))
    1132          15 :       .addUse(getOrCreateVReg(*U.getOperand(0)))
    1133          15 :       .addUse(getOrCreateVReg(*U.getOperand(1)))
    1134          15 :       .addUse(getOrCreateVReg(*U.getOperand(2)));
    1135          15 :   return true;
    1136             : }
    1137             : 
    1138          15 : bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
    1139             :   const PHINode &PI = cast<PHINode>(U);
    1140          15 :   auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI);
    1141          15 :   MIB.addDef(getOrCreateVReg(PI));
    1142             : 
    1143          15 :   PendingPHIs.emplace_back(&PI, MIB.getInstr());
    1144          15 :   return true;
    1145             : }
    1146             : 
    1147         920 : void IRTranslator::finishPendingPhis() {
    1148         950 :   for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) {
    1149          15 :     const PHINode *PI = Phi.first;
    1150          15 :     MachineInstrBuilder MIB(*MF, Phi.second);
    1151             : 
    1152             :     // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
    1153             :     // won't create extra control flow here, otherwise we need to find the
    1154             :     // dominating predecessor here (or perhaps force the weirder IRTranslators
    1155             :     // to provide a simple boundary).
    1156             :     SmallSet<const BasicBlock *, 4> HandledPreds;
    1157             : 
    1158          77 :     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
    1159             :       auto IRPred = PI->getIncomingBlock(i);
    1160          31 :       if (HandledPreds.count(IRPred))
    1161             :         continue;
    1162             : 
    1163          30 :       HandledPreds.insert(IRPred);
    1164          30 :       unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i));
    1165         152 :       for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
    1166             :         assert(Pred->isSuccessor(MIB->getParent()) &&
    1167             :                "incorrect CFG at MachineBasicBlock level");
    1168             :         MIB.addUse(ValReg);
    1169             :         MIB.addMBB(Pred);
    1170             :       }
    1171             :     }
    1172             :   }
    1173         920 : }
    1174             : 
    1175        2388 : bool IRTranslator::translate(const Instruction &Inst) {
    1176             :   CurBuilder.setDebugLoc(Inst.getDebugLoc());
    1177        2388 :   switch(Inst.getOpcode()) {
    1178             : #define HANDLE_INST(NUM, OPCODE, CLASS) \
    1179             :     case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
    1180             : #include "llvm/IR/Instruction.def"
    1181             :   default:
    1182             :     return false;
    1183             :   }
    1184             : }
    1185             : 
    1186         564 : bool IRTranslator::translate(const Constant &C, unsigned Reg) {
    1187             :   if (auto CI = dyn_cast<ConstantInt>(&C))
    1188         288 :     EntryBuilder.buildConstant(Reg, *CI);
    1189             :   else if (auto CF = dyn_cast<ConstantFP>(&C))
    1190          46 :     EntryBuilder.buildFConstant(Reg, *CF);
    1191         230 :   else if (isa<UndefValue>(C))
    1192          61 :     EntryBuilder.buildUndef(Reg);
    1193         169 :   else if (isa<ConstantPointerNull>(C))
    1194          11 :     EntryBuilder.buildConstant(Reg, 0);
    1195             :   else if (auto GV = dyn_cast<GlobalValue>(&C))
    1196         113 :     EntryBuilder.buildGlobalValue(Reg, GV);
    1197             :   else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
    1198          18 :     if (!CAZ->getType()->isVectorTy())
    1199           1 :       return false;
    1200             :     // Return the scalar if it is a <1 x Ty> vector.
    1201           9 :     if (CAZ->getNumElements() == 1)
    1202           1 :       return translate(*CAZ->getElementValue(0u), Reg);
    1203             :     std::vector<unsigned> Ops;
    1204          50 :     for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
    1205          21 :       Constant &Elt = *CAZ->getElementValue(i);
    1206          42 :       Ops.push_back(getOrCreateVReg(Elt));
    1207             :     }
    1208          16 :     EntryBuilder.buildMerge(Reg, Ops);
    1209             :   } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
    1210             :     // Return the scalar if it is a <1 x Ty> vector.
    1211          19 :     if (CV->getNumElements() == 1)
    1212           2 :       return translate(*CV->getElementAsConstant(0), Reg);
    1213             :     std::vector<unsigned> Ops;
    1214         129 :     for (unsigned i = 0; i < CV->getNumElements(); ++i) {
    1215          56 :       Constant &Elt = *CV->getElementAsConstant(i);
    1216         112 :       Ops.push_back(getOrCreateVReg(Elt));
    1217             :     }
    1218          34 :     EntryBuilder.buildMerge(Reg, Ops);
    1219             :   } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
    1220          12 :     switch(CE->getOpcode()) {
    1221             : #define HANDLE_INST(NUM, OPCODE, CLASS)                         \
    1222             :       case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
    1223             : #include "llvm/IR/Instruction.def"
    1224             :     default:
    1225             :       return false;
    1226             :     }
    1227             :   } else if (auto CS = dyn_cast<ConstantStruct>(&C)) {
    1228             :     // Return the element if it is a single element ConstantStruct.
    1229           2 :     if (CS->getNumOperands() == 1) {
    1230           0 :       unsigned EltReg = getOrCreateVReg(*CS->getOperand(0));
    1231           0 :       EntryBuilder.buildCast(Reg, EltReg);
    1232           0 :       return true;
    1233             :     }
    1234             :     SmallVector<unsigned, 4> Ops;
    1235             :     SmallVector<uint64_t, 4> Indices;
    1236           2 :     uint64_t Offset = 0;
    1237          14 :     for (unsigned i = 0; i < CS->getNumOperands(); ++i) {
    1238          12 :       unsigned OpReg = getOrCreateVReg(*CS->getOperand(i));
    1239           6 :       Ops.push_back(OpReg);
    1240           6 :       Indices.push_back(Offset);
    1241           6 :       Offset += MRI->getType(OpReg).getSizeInBits();
    1242             :     }
    1243           4 :     EntryBuilder.buildSequence(Reg, Ops, Indices);
    1244             :   } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
    1245           1 :     if (CV->getNumOperands() == 1)
    1246           0 :       return translate(*CV->getOperand(0), Reg);
    1247             :     SmallVector<unsigned, 4> Ops;
    1248           9 :     for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
    1249           8 :       Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
    1250             :     }
    1251           2 :     EntryBuilder.buildMerge(Reg, Ops);
    1252             :   } else
    1253             :     return false;
    1254             : 
    1255             :   return true;
    1256             : }
    1257             : 
    1258        1002 : void IRTranslator::finalizeFunction() {
    1259             :   // Release the memory used by the different maps we
    1260             :   // needed during the translation.
    1261             :   PendingPHIs.clear();
    1262        1002 :   ValToVReg.clear();
    1263        1002 :   FrameIndices.clear();
    1264        1002 :   MachinePreds.clear();
    1265             :   // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
    1266             :   // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
    1267             :   // destroying it twice (in ~IRTranslator() and ~LLVMContext())
    1268        2004 :   EntryBuilder = MachineIRBuilder();
    1269        2004 :   CurBuilder = MachineIRBuilder();
    1270        1002 : }
    1271             : 
    1272        1004 : bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
    1273        1004 :   MF = &CurMF;
    1274        1004 :   const Function &F = MF->getFunction();
    1275        1004 :   if (F.empty())
    1276             :     return false;
    1277        1004 :   CLI = MF->getSubtarget().getCallLowering();
    1278        1004 :   CurBuilder.setMF(*MF);
    1279        1004 :   EntryBuilder.setMF(*MF);
    1280        1004 :   MRI = &MF->getRegInfo();
    1281        1004 :   DL = &F.getParent()->getDataLayout();
    1282        1004 :   TPC = &getAnalysis<TargetPassConfig>();
    1283        1004 :   ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F);
    1284             : 
    1285             :   assert(PendingPHIs.empty() && "stale PHIs");
    1286             : 
    1287        1004 :   if (!DL->isLittleEndian()) {
    1288             :     // Currently we don't properly handle big endian code.
    1289             :     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
    1290          90 :                                F.getSubprogram(), &F.getEntryBlock());
    1291             :     R << "unable to translate in big endian mode";
    1292          45 :     reportTranslationError(*MF, *TPC, *ORE, R);
    1293             :   }
    1294             : 
    1295             :   // Release the per-function state when we return, whether we succeeded or not.
    1296        1002 :   auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
    1297             : 
    1298             :   // Setup a separate basic-block for the arguments and constants
    1299        1003 :   MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
    1300        1003 :   MF->push_back(EntryBB);
    1301        1003 :   EntryBuilder.setMBB(*EntryBB);
    1302             : 
    1303             :   // Create all blocks, in IR order, to preserve the layout.
    1304        2102 :   for (const BasicBlock &BB: F) {
    1305        2198 :     auto *&MBB = BBToMBB[&BB];
    1306             : 
    1307        1099 :     MBB = MF->CreateMachineBasicBlock(&BB);
    1308        1099 :     MF->push_back(MBB);
    1309             : 
    1310        1099 :     if (BB.hasAddressTaken())
    1311           4 :       MBB->setHasAddressTaken();
    1312             :   }
    1313             : 
    1314             :   // Make our arguments/constants entry block fallthrough to the IR entry block.
    1315        1003 :   EntryBB->addSuccessor(&getMBB(F.front()));
    1316             : 
    1317             :   // Lower the actual args into this basic block.
    1318             :   SmallVector<unsigned, 8> VRegArgs;
    1319        2654 :   for (const Argument &Arg: F.args()) {
    1320        3302 :     if (DL->getTypeStoreSize(Arg.getType()) == 0)
    1321           1 :       continue; // Don't handle zero sized types.
    1322        1650 :     VRegArgs.push_back(getOrCreateVReg(Arg));
    1323             :   }
    1324        2006 :   if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
    1325             :     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
    1326         106 :                                F.getSubprogram(), &F.getEntryBlock());
    1327          53 :     R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
    1328          53 :     reportTranslationError(*MF, *TPC, *ORE, R);
    1329             :     return false;
    1330             :   }
    1331             : 
    1332             :   // And translate the function!
    1333        1962 :   for (const BasicBlock &BB: F) {
    1334        1042 :     MachineBasicBlock &MBB = getMBB(BB);
    1335             :     // Set the insertion point of all the following translations to
    1336             :     // the end of this basic block.
    1337        1042 :     CurBuilder.setMBB(MBB);
    1338             : 
    1339        3400 :     for (const Instruction &Inst: BB) {
    1340        2388 :       if (translate(Inst))
    1341        2358 :         continue;
    1342             : 
    1343             :       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
    1344          90 :                                  Inst.getDebugLoc(), &BB);
    1345          60 :       R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
    1346             : 
    1347          30 :       if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
    1348             :         std::string InstStrStorage;
    1349          24 :         raw_string_ostream InstStr(InstStrStorage);
    1350             :         InstStr << Inst;
    1351             : 
    1352             :         R << ": '" << InstStr.str() << "'";
    1353             :       }
    1354             : 
    1355          30 :       reportTranslationError(*MF, *TPC, *ORE, R);
    1356             :       return false;
    1357             :     }
    1358             :   }
    1359             : 
    1360         920 :   finishPendingPhis();
    1361             : 
    1362             :   // Merge the argument lowering and constants block with its single
    1363             :   // successor, the LLVM-IR entry block.  We want the basic block to
    1364             :   // be maximal.
    1365             :   assert(EntryBB->succ_size() == 1 &&
    1366             :          "Custom BB used for lowering should have only one successor");
    1367             :   // Get the successor of the current entry block.
    1368         920 :   MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
    1369             :   assert(NewEntryBB.pred_size() == 1 &&
    1370             :          "LLVM-IR entry block has a predecessor!?");
    1371             :   // Move all the instruction from the current entry block to the
    1372             :   // new entry block.
    1373             :   NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
    1374             :                     EntryBB->end());
    1375             : 
    1376             :   // Update the live-in information for the new entry block.
    1377        2388 :   for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
    1378             :     NewEntryBB.addLiveIn(LiveIn);
    1379         920 :   NewEntryBB.sortUniqueLiveIns();
    1380             : 
    1381             :   // Get rid of the now empty basic block.
    1382         920 :   EntryBB->removeSuccessor(&NewEntryBB);
    1383         920 :   MF->remove(EntryBB);
    1384         920 :   MF->DeleteMachineBasicBlock(EntryBB);
    1385             : 
    1386             :   assert(&MF->front() == &NewEntryBB &&
    1387             :          "New entry wasn't next in the list of basic block!");
    1388             : 
    1389         920 :   return false;
    1390             : }

Generated by: LCOV version 1.13