LCOV - code coverage report
Current view: top level - lib/CodeGen/SelectionDAG - FastISel.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 847 941 90.0 %
Date: 2018-02-23 15:42:53 Functions: 60 67 89.6 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- FastISel.cpp - Implementation of the FastISel class ----------------===//
       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             : //
      10             : // This file contains the implementation of the FastISel class.
      11             : //
      12             : // "Fast" instruction selection is designed to emit very poor code quickly.
      13             : // Also, it is not designed to be able to do much lowering, so most illegal
      14             : // types (e.g. i64 on 32-bit targets) and operations are not supported.  It is
      15             : // also not intended to be able to do much optimization, except in a few cases
      16             : // where doing optimizations reduces overall compile time.  For example, folding
      17             : // constants into immediate fields is often done, because it's cheap and it
      18             : // reduces the number of instructions later phases have to examine.
      19             : //
      20             : // "Fast" instruction selection is able to fail gracefully and transfer
      21             : // control to the SelectionDAG selector for operations that it doesn't
      22             : // support.  In many cases, this allows us to avoid duplicating a lot of
      23             : // the complicated lowering logic that SelectionDAG currently has.
      24             : //
      25             : // The intended use for "fast" instruction selection is "-O0" mode
      26             : // compilation, where the quality of the generated code is irrelevant when
      27             : // weighed against the speed at which the code can be generated.  Also,
      28             : // at -O0, the LLVM optimizers are not running, and this makes the
      29             : // compile time of codegen a much higher portion of the overall compile
      30             : // time.  Despite its limitations, "fast" instruction selection is able to
      31             : // handle enough code on its own to provide noticeable overall speedups
      32             : // in -O0 compiles.
      33             : //
      34             : // Basic operations are supported in a target-independent way, by reading
      35             : // the same instruction descriptions that the SelectionDAG selector reads,
      36             : // and identifying simple arithmetic operations that can be directly selected
      37             : // from simple operators.  More complicated operations currently require
      38             : // target-specific code.
      39             : //
      40             : //===----------------------------------------------------------------------===//
      41             : 
      42             : #include "llvm/CodeGen/FastISel.h"
      43             : #include "llvm/ADT/APFloat.h"
      44             : #include "llvm/ADT/APSInt.h"
      45             : #include "llvm/ADT/DenseMap.h"
      46             : #include "llvm/ADT/Optional.h"
      47             : #include "llvm/ADT/SmallPtrSet.h"
      48             : #include "llvm/ADT/SmallString.h"
      49             : #include "llvm/ADT/SmallVector.h"
      50             : #include "llvm/ADT/Statistic.h"
      51             : #include "llvm/Analysis/BranchProbabilityInfo.h"
      52             : #include "llvm/Analysis/TargetLibraryInfo.h"
      53             : #include "llvm/CodeGen/Analysis.h"
      54             : #include "llvm/CodeGen/FunctionLoweringInfo.h"
      55             : #include "llvm/CodeGen/ISDOpcodes.h"
      56             : #include "llvm/CodeGen/MachineBasicBlock.h"
      57             : #include "llvm/CodeGen/MachineFrameInfo.h"
      58             : #include "llvm/CodeGen/MachineInstr.h"
      59             : #include "llvm/CodeGen/MachineInstrBuilder.h"
      60             : #include "llvm/CodeGen/MachineMemOperand.h"
      61             : #include "llvm/CodeGen/MachineModuleInfo.h"
      62             : #include "llvm/CodeGen/MachineOperand.h"
      63             : #include "llvm/CodeGen/MachineRegisterInfo.h"
      64             : #include "llvm/CodeGen/MachineValueType.h"
      65             : #include "llvm/CodeGen/StackMaps.h"
      66             : #include "llvm/CodeGen/TargetInstrInfo.h"
      67             : #include "llvm/CodeGen/TargetLowering.h"
      68             : #include "llvm/CodeGen/TargetSubtargetInfo.h"
      69             : #include "llvm/CodeGen/ValueTypes.h"
      70             : #include "llvm/IR/Argument.h"
      71             : #include "llvm/IR/Attributes.h"
      72             : #include "llvm/IR/BasicBlock.h"
      73             : #include "llvm/IR/CallSite.h"
      74             : #include "llvm/IR/CallingConv.h"
      75             : #include "llvm/IR/Constant.h"
      76             : #include "llvm/IR/Constants.h"
      77             : #include "llvm/IR/DataLayout.h"
      78             : #include "llvm/IR/DebugInfo.h"
      79             : #include "llvm/IR/DebugLoc.h"
      80             : #include "llvm/IR/DerivedTypes.h"
      81             : #include "llvm/IR/Function.h"
      82             : #include "llvm/IR/GetElementPtrTypeIterator.h"
      83             : #include "llvm/IR/GlobalValue.h"
      84             : #include "llvm/IR/InlineAsm.h"
      85             : #include "llvm/IR/InstrTypes.h"
      86             : #include "llvm/IR/Instruction.h"
      87             : #include "llvm/IR/Instructions.h"
      88             : #include "llvm/IR/IntrinsicInst.h"
      89             : #include "llvm/IR/LLVMContext.h"
      90             : #include "llvm/IR/Mangler.h"
      91             : #include "llvm/IR/Metadata.h"
      92             : #include "llvm/IR/Operator.h"
      93             : #include "llvm/IR/Type.h"
      94             : #include "llvm/IR/User.h"
      95             : #include "llvm/IR/Value.h"
      96             : #include "llvm/MC/MCContext.h"
      97             : #include "llvm/MC/MCInstrDesc.h"
      98             : #include "llvm/MC/MCRegisterInfo.h"
      99             : #include "llvm/Support/Casting.h"
     100             : #include "llvm/Support/Debug.h"
     101             : #include "llvm/Support/ErrorHandling.h"
     102             : #include "llvm/Support/MathExtras.h"
     103             : #include "llvm/Support/raw_ostream.h"
     104             : #include "llvm/Target/TargetMachine.h"
     105             : #include "llvm/Target/TargetOptions.h"
     106             : #include <algorithm>
     107             : #include <cassert>
     108             : #include <cstdint>
     109             : #include <iterator>
     110             : #include <utility>
     111             : 
     112             : using namespace llvm;
     113             : 
     114             : #define DEBUG_TYPE "isel"
     115             : 
     116             : STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
     117             :                                          "target-independent selector");
     118             : STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
     119             :                                     "target-specific selector");
     120             : STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
     121             : 
     122             : /// Set the current block to which generated machine instructions will be
     123             : /// appended, and clear the local CSE map.
     124       10594 : void FastISel::startNewBlock() {
     125       10594 :   LocalValueMap.clear();
     126             : 
     127             :   // Instructions are appended to FuncInfo.MBB. If the basic block already
     128             :   // contains labels or copies, use the last instruction as the last local
     129             :   // value.
     130       10594 :   EmitStartPt = nullptr;
     131       21188 :   if (!FuncInfo.MBB->empty())
     132         230 :     EmitStartPt = &FuncInfo.MBB->back();
     133       10594 :   LastLocalValue = EmitStartPt;
     134       10594 : }
     135             : 
     136        8591 : bool FastISel::lowerArguments() {
     137        8591 :   if (!FuncInfo.CanLowerReturn)
     138             :     // Fallback to SDISel argument lowering code to deal with sret pointer
     139             :     // parameter.
     140             :     return false;
     141             : 
     142        8587 :   if (!fastLowerArguments())
     143             :     return false;
     144             : 
     145             :   // Enter arguments into ValueMap for uses in non-entry BBs.
     146        8943 :   for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
     147        4015 :                                     E = FuncInfo.Fn->arg_end();
     148        8943 :        I != E; ++I) {
     149        4928 :     DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(&*I);
     150             :     assert(VI != LocalValueMap.end() && "Missed an argument?");
     151        9856 :     FuncInfo.ValueMap[&*I] = VI->second;
     152             :   }
     153             :   return true;
     154             : }
     155             : 
     156        1983 : void FastISel::flushLocalValueMap() {
     157        1983 :   LocalValueMap.clear();
     158        1983 :   LastLocalValue = EmitStartPt;
     159        1983 :   recomputeInsertPt();
     160        1983 :   SavedInsertPt = FuncInfo.InsertPt;
     161        1983 : }
     162             : 
     163        8755 : bool FastISel::hasTrivialKill(const Value *V) {
     164             :   // Don't consider constants or arguments to have trivial kills.
     165             :   const Instruction *I = dyn_cast<Instruction>(V);
     166             :   if (!I)
     167             :     return false;
     168             : 
     169             :   // No-op casts are trivially coalesced by fast-isel.
     170             :   if (const auto *Cast = dyn_cast<CastInst>(I))
     171         959 :     if (Cast->isNoopCast(DL) && !hasTrivialKill(Cast->getOperand(0)))
     172             :       return false;
     173             : 
     174             :   // Even the value might have only one use in the LLVM IR, it is possible that
     175             :   // FastISel might fold the use into another instruction and now there is more
     176             :   // than one use at the Machine Instruction level.
     177        3875 :   unsigned Reg = lookUpRegForValue(V);
     178        7604 :   if (Reg && !MRI.use_empty(Reg))
     179             :     return false;
     180             : 
     181             :   // GEPs with all zero indices are trivially coalesced by fast-isel.
     182             :   if (const auto *GEP = dyn_cast<GetElementPtrInst>(I))
     183          68 :     if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
     184             :       return false;
     185             : 
     186             :   // Only instructions with a single use in the same basic block are considered
     187             :   // to have trivial kills.
     188        3237 :   return I->hasOneUse() &&
     189        3211 :          !(I->getOpcode() == Instruction::BitCast ||
     190             :            I->getOpcode() == Instruction::PtrToInt ||
     191        6881 :            I->getOpcode() == Instruction::IntToPtr) &&
     192             :          cast<Instruction>(*I->user_begin())->getParent() == I->getParent();
     193             : }
     194             : 
     195       29299 : unsigned FastISel::getRegForValue(const Value *V) {
     196       29299 :   EVT RealVT = TLI.getValueType(DL, V->getType(), /*AllowUnknown=*/true);
     197             :   // Don't handle non-simple values in FastISel.
     198       29299 :   if (!RealVT.isSimple())
     199             :     return 0;
     200             : 
     201             :   // Ignore illegal types. We must do this before looking up the value
     202             :   // in ValueMap because Arguments are given virtual registers regardless
     203             :   // of whether FastISel can handle them.
     204             :   MVT VT = RealVT.getSimpleVT();
     205       29289 :   if (!TLI.isTypeLegal(VT)) {
     206             :     // Handle integer promotions, though, because they're common and easy.
     207        3167 :     if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
     208        2840 :       VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
     209             :     else
     210             :       return 0;
     211             :   }
     212             : 
     213             :   // Look up the value to see if we already have a register for it.
     214       28962 :   unsigned Reg = lookUpRegForValue(V);
     215       28962 :   if (Reg)
     216             :     return Reg;
     217             : 
     218             :   // In bottom-up mode, just create the virtual register which will be used
     219             :   // to hold the value. It will be materialized later.
     220       14950 :   if (isa<Instruction>(V) &&
     221             :       (!isa<AllocaInst>(V) ||
     222         427 :        !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
     223       10849 :     return FuncInfo.InitializeRegForValue(V);
     224             : 
     225        4101 :   SavePoint SaveInsertPt = enterLocalValueArea();
     226             : 
     227             :   // Materialize the value in a register. Emit any instructions in the
     228             :   // local value area.
     229        4101 :   Reg = materializeRegForValue(V, VT);
     230             : 
     231        8202 :   leaveLocalValueArea(SaveInsertPt);
     232             : 
     233             :   return Reg;
     234             : }
     235             : 
     236        1034 : unsigned FastISel::materializeConstant(const Value *V, MVT VT) {
     237             :   unsigned Reg = 0;
     238             :   if (const auto *CI = dyn_cast<ConstantInt>(V)) {
     239          89 :     if (CI->getValue().getActiveBits() <= 64)
     240         178 :       Reg = fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
     241             :   } else if (isa<AllocaInst>(V))
     242         413 :     Reg = fastMaterializeAlloca(cast<AllocaInst>(V));
     243         532 :   else if (isa<ConstantPointerNull>(V))
     244             :     // Translate this as an integer zero so that it can be
     245             :     // local-CSE'd with actual integer zeros.
     246          30 :     Reg = getRegForValue(
     247          30 :         Constant::getNullValue(DL.getIntPtrType(V->getContext())));
     248             :   else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
     249           1 :     if (CF->isNullValue())
     250           1 :       Reg = fastMaterializeFloatZero(CF);
     251             :     else
     252             :       // Try to emit the constant directly.
     253           0 :       Reg = fastEmit_f(VT, VT, ISD::ConstantFP, CF);
     254             : 
     255           1 :     if (!Reg) {
     256             :       // Try to emit the constant by using an integer constant with a cast.
     257             :       const APFloat &Flt = CF->getValueAPF();
     258           1 :       EVT IntVT = TLI.getPointerTy(DL);
     259           1 :       uint32_t IntBitWidth = IntVT.getSizeInBits();
     260           1 :       APSInt SIntVal(IntBitWidth, /*isUnsigned=*/false);
     261             :       bool isExact;
     262           1 :       (void)Flt.convertToInteger(SIntVal, APFloat::rmTowardZero, &isExact);
     263           1 :       if (isExact) {
     264             :         unsigned IntegerReg =
     265           1 :             getRegForValue(ConstantInt::get(V->getContext(), SIntVal));
     266           1 :         if (IntegerReg != 0)
     267           1 :           Reg = fastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, IntegerReg,
     268           1 :                            /*Kill=*/false);
     269             :       }
     270             :     }
     271             :   } else if (const auto *Op = dyn_cast<Operator>(V)) {
     272         199 :     if (!selectOperator(Op, Op->getOpcode()))
     273          32 :       if (!isa<Instruction>(Op) ||
     274           0 :           !fastSelectInstruction(cast<Instruction>(Op)))
     275             :         return 0;
     276         167 :     Reg = lookUpRegForValue(Op);
     277         302 :   } else if (isa<UndefValue>(V)) {
     278         164 :     Reg = createResultReg(TLI.getRegClassFor(VT));
     279         164 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
     280         328 :             TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
     281             :   }
     282             :   return Reg;
     283             : }
     284             : 
     285             : /// Helper for getRegForValue. This function is called when the value isn't
     286             : /// already available in a register and must be materialized with new
     287             : /// instructions.
     288        4101 : unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
     289             :   unsigned Reg = 0;
     290             :   // Give the target-specific code a try first.
     291        8202 :   if (isa<Constant>(V))
     292        3688 :     Reg = fastMaterializeConstant(cast<Constant>(V));
     293             : 
     294             :   // If target-specific code couldn't or didn't want to handle the value, then
     295             :   // give target-independent code a try.
     296        3688 :   if (!Reg)
     297        1034 :     Reg = materializeConstant(V, VT);
     298             : 
     299             :   // Don't cache constant materializations in the general ValueMap.
     300             :   // To do so would require tracking what uses they dominate.
     301        4101 :   if (Reg) {
     302        7860 :     LocalValueMap[V] = Reg;
     303        3930 :     LastLocalValue = MRI.getVRegDef(Reg);
     304             :   }
     305        4101 :   return Reg;
     306             : }
     307             : 
     308       33607 : unsigned FastISel::lookUpRegForValue(const Value *V) {
     309             :   // Look up the value to see if we already have a register for it. We
     310             :   // cache values defined by Instructions across blocks, and other values
     311             :   // only locally. This is because Instructions already have the SSA
     312             :   // def-dominates-use requirement enforced.
     313       33607 :   DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
     314       67214 :   if (I != FuncInfo.ValueMap.end())
     315       16171 :     return I->second;
     316       34872 :   return LocalValueMap[V];
     317             : }
     318             : 
     319       13833 : void FastISel::updateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
     320       27666 :   if (!isa<Instruction>(I)) {
     321       10190 :     LocalValueMap[I] = Reg;
     322        5095 :     return;
     323             :   }
     324             : 
     325        8738 :   unsigned &AssignedReg = FuncInfo.ValueMap[I];
     326        8738 :   if (AssignedReg == 0)
     327             :     // Use the new register.
     328         257 :     AssignedReg = Reg;
     329        8481 :   else if (Reg != AssignedReg) {
     330             :     // Arrange for uses of AssignedReg to be replaced by uses of Reg.
     331       25691 :     for (unsigned i = 0; i < NumRegs; i++)
     332       17210 :       FuncInfo.RegFixups[AssignedReg + i] = Reg + i;
     333             : 
     334        8481 :     AssignedReg = Reg;
     335             :   }
     336             : }
     337             : 
     338         103 : std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
     339         103 :   unsigned IdxN = getRegForValue(Idx);
     340         103 :   if (IdxN == 0)
     341             :     // Unhandled operand. Halt "fast" selection and bail.
     342           9 :     return std::pair<unsigned, bool>(0, false);
     343             : 
     344          94 :   bool IdxNIsKill = hasTrivialKill(Idx);
     345             : 
     346             :   // If the index is smaller or larger than intptr_t, truncate or extend it.
     347          94 :   MVT PtrVT = TLI.getPointerTy(DL);
     348          94 :   EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
     349          94 :   if (IdxVT.bitsLT(PtrVT)) {
     350          12 :     IdxN = fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND, IdxN,
     351          12 :                       IdxNIsKill);
     352             :     IdxNIsKill = true;
     353          82 :   } else if (IdxVT.bitsGT(PtrVT)) {
     354             :     IdxN =
     355           9 :         fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE, IdxN, IdxNIsKill);
     356             :     IdxNIsKill = true;
     357             :   }
     358          94 :   return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
     359             : }
     360             : 
     361       68847 : void FastISel::recomputeInsertPt() {
     362       68847 :   if (getLastLocalValue()) {
     363       51591 :     FuncInfo.InsertPt = getLastLocalValue();
     364      103182 :     FuncInfo.MBB = FuncInfo.InsertPt->getParent();
     365       51591 :     ++FuncInfo.InsertPt;
     366             :   } else
     367       17256 :     FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
     368             : 
     369             :   // Now skip past any EH_LABELs, which must remain at the beginning.
     370      183914 :   while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
     371       46220 :          FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
     372             :     ++FuncInfo.InsertPt;
     373       68847 : }
     374             : 
     375         161 : void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
     376             :                               MachineBasicBlock::iterator E) {
     377             :   assert(I.isValid() && E.isValid() && std::distance(I, E) > 0 &&
     378             :          "Invalid iterator!");
     379         432 :   while (I != E) {
     380             :     MachineInstr *Dead = &*I;
     381             :     ++I;
     382         271 :     Dead->eraseFromParent();
     383             :     ++NumFastIselDead;
     384             :   }
     385         161 :   recomputeInsertPt();
     386         161 : }
     387             : 
     388        4172 : FastISel::SavePoint FastISel::enterLocalValueArea() {
     389        4172 :   MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
     390             :   DebugLoc OldDL = DbgLoc;
     391        4172 :   recomputeInsertPt();
     392        8344 :   DbgLoc = DebugLoc();
     393        4172 :   SavePoint SP = {OldInsertPt, OldDL};
     394        4172 :   return SP;
     395             : }
     396             : 
     397        4172 : void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
     398        8344 :   if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
     399        4097 :     LastLocalValue = &*std::prev(FuncInfo.InsertPt);
     400             : 
     401             :   // Restore the previous insert position.
     402        4172 :   FuncInfo.InsertPt = OldInsertPt.InsertPt;
     403             :   DbgLoc = OldInsertPt.DL;
     404        4172 : }
     405             : 
     406        1516 : bool FastISel::selectBinaryOp(const User *I, unsigned ISDOpcode) {
     407        1516 :   EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
     408        1516 :   if (VT == MVT::Other || !VT.isSimple())
     409             :     // Unhandled type. Halt "fast" selection and bail.
     410             :     return false;
     411             : 
     412             :   // We only handle legal types. For example, on x86-32 the instruction
     413             :   // selector contains all of the 64-bit instructions from x86-64,
     414             :   // under the assumption that i64 won't be used if the target doesn't
     415             :   // support it.
     416        1516 :   if (!TLI.isTypeLegal(VT)) {
     417             :     // MVT::i1 is special. Allow AND, OR, or XOR because they
     418             :     // don't require additional zeroing, which makes them easy.
     419          38 :     if (VT == MVT::i1 && (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
     420             :                           ISDOpcode == ISD::XOR))
     421          31 :       VT = TLI.getTypeToTransformTo(I->getContext(), VT);
     422             :     else
     423             :       return false;
     424             :   }
     425             : 
     426             :   // Check if the first operand is a constant, and handle it as "ri".  At -O0,
     427             :   // we don't have anything that canonicalizes operand order.
     428             :   if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
     429          50 :     if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
     430          22 :       unsigned Op1 = getRegForValue(I->getOperand(1));
     431          22 :       if (!Op1)
     432             :         return false;
     433          22 :       bool Op1IsKill = hasTrivialKill(I->getOperand(1));
     434             : 
     435             :       unsigned ResultReg =
     436          22 :           fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1, Op1IsKill,
     437          22 :                        CI->getZExtValue(), VT.getSimpleVT());
     438          22 :       if (!ResultReg)
     439             :         return false;
     440             : 
     441             :       // We successfully emitted code for the given LLVM Instruction.
     442          22 :       updateValueMap(I, ResultReg);
     443          22 :       return true;
     444             :     }
     445             : 
     446        1381 :   unsigned Op0 = getRegForValue(I->getOperand(0));
     447        1381 :   if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
     448             :     return false;
     449        1371 :   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
     450             : 
     451             :   // Check if the second operand is a constant and handle it appropriately.
     452             :   if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
     453         408 :     uint64_t Imm = CI->getSExtValue();
     454             : 
     455             :     // Transform "sdiv exact X, 8" -> "sra X, 3".
     456           4 :     if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
     457         412 :         cast<BinaryOperator>(I)->isExact() && isPowerOf2_64(Imm)) {
     458           4 :       Imm = Log2_64(Imm);
     459             :       ISDOpcode = ISD::SRA;
     460             :     }
     461             : 
     462             :     // Transform "urem x, pow2" -> "and x, pow2-1".
     463         404 :     if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
     464             :         isPowerOf2_64(Imm)) {
     465             :       --Imm;
     466             :       ISDOpcode = ISD::AND;
     467             :     }
     468             : 
     469         408 :     unsigned ResultReg = fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
     470         408 :                                       Op0IsKill, Imm, VT.getSimpleVT());
     471         408 :     if (!ResultReg)
     472             :       return false;
     473             : 
     474             :     // We successfully emitted code for the given LLVM Instruction.
     475         397 :     updateValueMap(I, ResultReg);
     476         397 :     return true;
     477             :   }
     478             : 
     479         963 :   unsigned Op1 = getRegForValue(I->getOperand(1));
     480         963 :   if (!Op1) // Unhandled operand. Halt "fast" selection and bail.
     481             :     return false;
     482         938 :   bool Op1IsKill = hasTrivialKill(I->getOperand(1));
     483             : 
     484             :   // Now we have both operands in registers. Emit the instruction.
     485         938 :   unsigned ResultReg = fastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
     486        1876 :                                    ISDOpcode, Op0, Op0IsKill, Op1, Op1IsKill);
     487         938 :   if (!ResultReg)
     488             :     // Target-specific code wasn't able to find a machine opcode for
     489             :     // the given ISD opcode and type. Halt "fast" selection and bail.
     490             :     return false;
     491             : 
     492             :   // We successfully emitted code for the given LLVM Instruction.
     493         768 :   updateValueMap(I, ResultReg);
     494         768 :   return true;
     495             : }
     496             : 
     497         267 : bool FastISel::selectGetElementPtr(const User *I) {
     498         267 :   unsigned N = getRegForValue(I->getOperand(0));
     499         267 :   if (!N) // Unhandled operand. Halt "fast" selection and bail.
     500             :     return false;
     501         234 :   bool NIsKill = hasTrivialKill(I->getOperand(0));
     502             : 
     503             :   // Keep a running tab of the total offset to coalesce multiple N = N + Offset
     504             :   // into a single N = N + TotalOffset.
     505             :   uint64_t TotalOffs = 0;
     506             :   // FIXME: What's a good SWAG number for MaxOffs?
     507             :   uint64_t MaxOffs = 2048;
     508         468 :   MVT VT = TLI.getPointerTy(DL);
     509         725 :   for (gep_type_iterator GTI = gep_type_begin(I), E = gep_type_end(I);
     510         725 :        GTI != E; ++GTI) {
     511             :     const Value *Idx = GTI.getOperand();
     512          50 :     if (StructType *StTy = GTI.getStructTypeOrNull()) {
     513             :       uint64_t Field = cast<ConstantInt>(Idx)->getZExtValue();
     514          50 :       if (Field) {
     515             :         // N = N + Offset
     516          58 :         TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
     517          29 :         if (TotalOffs >= MaxOffs) {
     518           2 :           N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
     519           2 :           if (!N) // Unhandled operand. Halt "fast" selection and bail.
     520          17 :             return false;
     521             :           NIsKill = true;
     522             :           TotalOffs = 0;
     523             :         }
     524             :       }
     525             :     } else {
     526         458 :       Type *Ty = GTI.getIndexedType();
     527             : 
     528             :       // If this is a constant subscript, handle it quickly.
     529             :       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
     530         416 :         if (CI->isZero())
     531         699 :           continue;
     532             :         // N = N + Offset
     533         399 :         uint64_t IdxN = CI->getValue().sextOrTrunc(64).getSExtValue();
     534         133 :         TotalOffs += DL.getTypeAllocSize(Ty) * IdxN;
     535         133 :         if (TotalOffs >= MaxOffs) {
     536          11 :           N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
     537          11 :           if (!N) // Unhandled operand. Halt "fast" selection and bail.
     538          17 :             return false;
     539             :           NIsKill = true;
     540             :           TotalOffs = 0;
     541             :         }
     542         133 :         continue;
     543             :       }
     544          42 :       if (TotalOffs) {
     545           0 :         N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
     546           0 :         if (!N) // Unhandled operand. Halt "fast" selection and bail.
     547             :           return false;
     548             :         NIsKill = true;
     549             :         TotalOffs = 0;
     550             :       }
     551             : 
     552             :       // N = N + Idx * ElementSize;
     553          42 :       uint64_t ElementSize = DL.getTypeAllocSize(Ty);
     554          42 :       std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
     555          42 :       unsigned IdxN = Pair.first;
     556          42 :       bool IdxNIsKill = Pair.second;
     557          42 :       if (!IdxN) // Unhandled operand. Halt "fast" selection and bail.
     558             :         return false;
     559             : 
     560          27 :       if (ElementSize != 1) {
     561          11 :         IdxN = fastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
     562          11 :         if (!IdxN) // Unhandled operand. Halt "fast" selection and bail.
     563             :           return false;
     564             :         IdxNIsKill = true;
     565             :       }
     566          25 :       N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
     567          25 :       if (!N) // Unhandled operand. Halt "fast" selection and bail.
     568             :         return false;
     569             :     }
     570             :   }
     571         217 :   if (TotalOffs) {
     572          81 :     N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
     573          81 :     if (!N) // Unhandled operand. Halt "fast" selection and bail.
     574             :       return false;
     575             :   }
     576             : 
     577             :   // We successfully emitted code for the given LLVM Instruction.
     578         217 :   updateValueMap(I, N);
     579         217 :   return true;
     580             : }
     581             : 
     582          65 : bool FastISel::addStackMapLiveVars(SmallVectorImpl<MachineOperand> &Ops,
     583             :                                    const CallInst *CI, unsigned StartIdx) {
     584         372 :   for (unsigned i = StartIdx, e = CI->getNumArgOperands(); i != e; ++i) {
     585             :     Value *Val = CI->getArgOperand(i);
     586             :     // Check for constants and encode them with a StackMaps::ConstantOp prefix.
     587             :     if (const auto *C = dyn_cast<ConstantInt>(Val)) {
     588          36 :       Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp));
     589          18 :       Ops.push_back(MachineOperand::CreateImm(C->getSExtValue()));
     590         103 :     } else if (isa<ConstantPointerNull>(Val)) {
     591           0 :       Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp));
     592           0 :       Ops.push_back(MachineOperand::CreateImm(0));
     593             :     } else if (auto *AI = dyn_cast<AllocaInst>(Val)) {
     594             :       // Values coming from a stack location also require a special encoding,
     595             :       // but that is added later on by the target specific frame index
     596             :       // elimination implementation.
     597           8 :       auto SI = FuncInfo.StaticAllocaMap.find(AI);
     598          16 :       if (SI != FuncInfo.StaticAllocaMap.end())
     599          16 :         Ops.push_back(MachineOperand::CreateFI(SI->second));
     600             :       else
     601           0 :         return false;
     602             :     } else {
     603          95 :       unsigned Reg = getRegForValue(Val);
     604          95 :       if (!Reg)
     605             :         return false;
     606         190 :       Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false));
     607             :     }
     608             :   }
     609             :   return true;
     610             : }
     611             : 
     612          26 : bool FastISel::selectStackmap(const CallInst *I) {
     613             :   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
     614             :   //                                  [live variables...])
     615             :   assert(I->getCalledFunction()->getReturnType()->isVoidTy() &&
     616             :          "Stackmap cannot return a value.");
     617             : 
     618             :   // The stackmap intrinsic only records the live variables (the arguments
     619             :   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
     620             :   // intrinsic, this won't be lowered to a function call. This means we don't
     621             :   // have to worry about calling conventions and target-specific lowering code.
     622             :   // Instead we perform the call lowering right here.
     623             :   //
     624             :   // CALLSEQ_START(0, 0...)
     625             :   // STACKMAP(id, nbytes, ...)
     626             :   // CALLSEQ_END(0, 0)
     627             :   //
     628             :   SmallVector<MachineOperand, 32> Ops;
     629             : 
     630             :   // Add the <id> and <numBytes> constants.
     631             :   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) &&
     632             :          "Expected a constant integer.");
     633          26 :   const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos));
     634          52 :   Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue()));
     635             : 
     636             :   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) &&
     637             :          "Expected a constant integer.");
     638             :   const auto *NumBytes =
     639             :       cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos));
     640          52 :   Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue()));
     641             : 
     642             :   // Push live variables for the stack map (skipping the first two arguments
     643             :   // <id> and <numBytes>).
     644          26 :   if (!addStackMapLiveVars(Ops, I, 2))
     645             :     return false;
     646             : 
     647             :   // We are not adding any register mask info here, because the stackmap doesn't
     648             :   // clobber anything.
     649             : 
     650             :   // Add scratch registers as implicit def and early clobber.
     651             :   CallingConv::ID CC = I->getCallingConv();
     652          26 :   const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC);
     653         138 :   for (unsigned i = 0; ScratchRegs[i]; ++i)
     654          56 :     Ops.push_back(MachineOperand::CreateReg(
     655             :         ScratchRegs[i], /*IsDef=*/true, /*IsImp=*/true, /*IsKill=*/false,
     656          56 :         /*IsDead=*/false, /*IsUndef=*/false, /*IsEarlyClobber=*/true));
     657             : 
     658             :   // Issue CALLSEQ_START
     659          26 :   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
     660             :   auto Builder =
     661          52 :       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown));
     662          26 :   const MCInstrDesc &MCID = Builder.getInstr()->getDesc();
     663         178 :   for (unsigned I = 0, E = MCID.getNumOperands(); I < E; ++I)
     664             :     Builder.addImm(0);
     665             : 
     666             :   // Issue STACKMAP.
     667          26 :   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
     668          52 :                                     TII.get(TargetOpcode::STACKMAP));
     669         436 :   for (auto const &MO : Ops)
     670             :     MIB.add(MO);
     671             : 
     672             :   // Issue CALLSEQ_END
     673          26 :   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
     674          52 :   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
     675             :       .addImm(0)
     676             :       .addImm(0);
     677             : 
     678             :   // Inform the Frame Information that we have a stackmap in this function.
     679          26 :   FuncInfo.MF->getFrameInfo().setHasStackMap();
     680             : 
     681          26 :   return true;
     682             : }
     683             : 
     684             : /// \brief Lower an argument list according to the target calling convention.
     685             : ///
     686             : /// This is a helper for lowering intrinsics that follow a target calling
     687             : /// convention or require stack pointer adjustment. Only a subset of the
     688             : /// intrinsic's operands need to participate in the calling convention.
     689          39 : bool FastISel::lowerCallOperands(const CallInst *CI, unsigned ArgIdx,
     690             :                                  unsigned NumArgs, const Value *Callee,
     691             :                                  bool ForceRetVoidTy, CallLoweringInfo &CLI) {
     692             :   ArgListTy Args;
     693          39 :   Args.reserve(NumArgs);
     694             : 
     695             :   // Populate the argument list.
     696             :   ImmutableCallSite CS(CI);
     697         151 :   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; ArgI != ArgE; ++ArgI) {
     698         112 :     Value *V = CI->getOperand(ArgI);
     699             : 
     700             :     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
     701             : 
     702             :     ArgListEntry Entry;
     703         112 :     Entry.Val = V;
     704         112 :     Entry.Ty = V->getType();
     705         112 :     Entry.setAttributes(&CS, ArgIdx);
     706         112 :     Args.push_back(Entry);
     707             :   }
     708             : 
     709          39 :   Type *RetTy = ForceRetVoidTy ? Type::getVoidTy(CI->getType()->getContext())
     710             :                                : CI->getType();
     711             :   CLI.setCallee(CI->getCallingConv(), RetTy, Callee, std::move(Args), NumArgs);
     712             : 
     713          78 :   return lowerCallTo(CLI);
     714             : }
     715             : 
     716          16 : FastISel::CallLoweringInfo &FastISel::CallLoweringInfo::setCallee(
     717             :     const DataLayout &DL, MCContext &Ctx, CallingConv::ID CC, Type *ResultTy,
     718             :     StringRef Target, ArgListTy &&ArgsList, unsigned FixedArgs) {
     719             :   SmallString<32> MangledName;
     720          16 :   Mangler::getNameWithPrefix(MangledName, Target, DL);
     721          16 :   MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName);
     722          16 :   return setCallee(CC, ResultTy, Sym, std::move(ArgsList), FixedArgs);
     723             : }
     724             : 
     725          39 : bool FastISel::selectPatchpoint(const CallInst *I) {
     726             :   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
     727             :   //                                                 i32 <numBytes>,
     728             :   //                                                 i8* <target>,
     729             :   //                                                 i32 <numArgs>,
     730             :   //                                                 [Args...],
     731             :   //                                                 [live variables...])
     732             :   CallingConv::ID CC = I->getCallingConv();
     733          39 :   bool IsAnyRegCC = CC == CallingConv::AnyReg;
     734          78 :   bool HasDef = !I->getType()->isVoidTy();
     735          39 :   Value *Callee = I->getOperand(PatchPointOpers::TargetPos)->stripPointerCasts();
     736             : 
     737             :   // Get the real number of arguments participating in the call <numArgs>
     738             :   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos)) &&
     739             :          "Expected a constant integer.");
     740             :   const auto *NumArgsVal =
     741             :       cast<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos));
     742          39 :   unsigned NumArgs = NumArgsVal->getZExtValue();
     743             : 
     744             :   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
     745             :   // This includes all meta-operands up to but not including CC.
     746             :   unsigned NumMetaOpers = PatchPointOpers::CCPos;
     747             :   assert(I->getNumArgOperands() >= NumMetaOpers + NumArgs &&
     748             :          "Not enough arguments provided to the patchpoint intrinsic");
     749             : 
     750             :   // For AnyRegCC the arguments are lowered later on manually.
     751          39 :   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
     752          78 :   CallLoweringInfo CLI;
     753             :   CLI.setIsPatchPoint();
     754          39 :   if (!lowerCallOperands(I, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC, CLI))
     755             :     return false;
     756             : 
     757             :   assert(CLI.Call && "No call instruction specified.");
     758             : 
     759             :   SmallVector<MachineOperand, 32> Ops;
     760             : 
     761             :   // Add an explicit result reg if we use the anyreg calling convention.
     762          39 :   if (IsAnyRegCC && HasDef) {
     763             :     assert(CLI.NumResultRegs == 0 && "Unexpected result register.");
     764           0 :     CLI.ResultReg = createResultReg(TLI.getRegClassFor(MVT::i64));
     765           0 :     CLI.NumResultRegs = 1;
     766           0 :     Ops.push_back(MachineOperand::CreateReg(CLI.ResultReg, /*IsDef=*/true));
     767             :   }
     768             : 
     769             :   // Add the <id> and <numBytes> constants.
     770             :   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) &&
     771             :          "Expected a constant integer.");
     772             :   const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos));
     773          78 :   Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue()));
     774             : 
     775             :   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) &&
     776             :          "Expected a constant integer.");
     777             :   const auto *NumBytes =
     778             :       cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos));
     779          78 :   Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue()));
     780             : 
     781             :   // Add the call target.
     782             :   if (const auto *C = dyn_cast<IntToPtrInst>(Callee)) {
     783             :     uint64_t CalleeConstAddr =
     784             :       cast<ConstantInt>(C->getOperand(0))->getZExtValue();
     785          38 :     Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr));
     786             :   } else if (const auto *C = dyn_cast<ConstantExpr>(Callee)) {
     787           4 :     if (C->getOpcode() == Instruction::IntToPtr) {
     788             :       uint64_t CalleeConstAddr =
     789             :         cast<ConstantInt>(C->getOperand(0))->getZExtValue();
     790           8 :       Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr));
     791             :     } else
     792           0 :       llvm_unreachable("Unsupported ConstantExpr.");
     793             :   } else if (const auto *GV = dyn_cast<GlobalValue>(Callee)) {
     794           3 :     Ops.push_back(MachineOperand::CreateGA(GV, 0));
     795          13 :   } else if (isa<ConstantPointerNull>(Callee))
     796          13 :     Ops.push_back(MachineOperand::CreateImm(0));
     797             :   else
     798           0 :     llvm_unreachable("Unsupported callee address.");
     799             : 
     800             :   // Adjust <numArgs> to account for any arguments that have been passed on
     801             :   // the stack instead.
     802          77 :   unsigned NumCallRegArgs = IsAnyRegCC ? NumArgs : CLI.OutRegs.size();
     803          78 :   Ops.push_back(MachineOperand::CreateImm(NumCallRegArgs));
     804             : 
     805             :   // Add the calling convention
     806          78 :   Ops.push_back(MachineOperand::CreateImm((unsigned)CC));
     807             : 
     808             :   // Add the arguments we omitted previously. The register allocator should
     809             :   // place these in any free register.
     810          39 :   if (IsAnyRegCC) {
     811           3 :     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) {
     812           2 :       unsigned Reg = getRegForValue(I->getArgOperand(i));
     813           2 :       if (!Reg)
     814             :         return false;
     815           2 :       Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false));
     816             :     }
     817             :   }
     818             : 
     819             :   // Push the arguments from the call instruction.
     820         135 :   for (auto Reg : CLI.OutRegs)
     821          48 :     Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false));
     822             : 
     823             :   // Push live variables for the stack map.
     824          39 :   if (!addStackMapLiveVars(Ops, I, NumMetaOpers + NumArgs))
     825             :     return false;
     826             : 
     827             :   // Push the register mask info.
     828          39 :   Ops.push_back(MachineOperand::CreateRegMask(
     829          39 :       TRI.getCallPreservedMask(*FuncInfo.MF, CC)));
     830             : 
     831             :   // Add scratch registers as implicit def and early clobber.
     832          39 :   const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC);
     833         229 :   for (unsigned i = 0; ScratchRegs[i]; ++i)
     834          95 :     Ops.push_back(MachineOperand::CreateReg(
     835             :         ScratchRegs[i], /*IsDef=*/true, /*IsImp=*/true, /*IsKill=*/false,
     836          95 :         /*IsDead=*/false, /*IsUndef=*/false, /*IsEarlyClobber=*/true));
     837             : 
     838             :   // Add implicit defs (return values).
     839          79 :   for (auto Reg : CLI.InRegs)
     840          20 :     Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/true,
     841             :                                             /*IsImpl=*/true));
     842             : 
     843             :   // Insert the patchpoint instruction before the call generated by the target.
     844          39 :   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, CLI.Call, DbgLoc,
     845          78 :                                     TII.get(TargetOpcode::PATCHPOINT));
     846             : 
     847         921 :   for (auto &MO : Ops)
     848             :     MIB.add(MO);
     849             : 
     850          78 :   MIB->setPhysRegsDeadExcept(CLI.InRegs, TRI);
     851             : 
     852             :   // Delete the original call instruction.
     853          39 :   CLI.Call->eraseFromParent();
     854             : 
     855             :   // Inform the Frame Information that we have a patchpoint in this function.
     856          39 :   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
     857             : 
     858          39 :   if (CLI.NumResultRegs)
     859          20 :     updateValueMap(I, CLI.ResultReg, CLI.NumResultRegs);
     860             :   return true;
     861             : }
     862             : 
     863           0 : bool FastISel::selectXRayCustomEvent(const CallInst *I) {
     864           0 :   const auto &Triple = TM.getTargetTriple();
     865           0 :   if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
     866             :     return true; // don't do anything to this instruction.
     867             :   SmallVector<MachineOperand, 8> Ops;
     868           0 :   Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(0)),
     869           0 :                                           /*IsDef=*/false));
     870           0 :   Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(1)),
     871           0 :                                           /*IsDef=*/false));
     872             :   MachineInstrBuilder MIB =
     873           0 :       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
     874           0 :               TII.get(TargetOpcode::PATCHABLE_EVENT_CALL));
     875           0 :   for (auto &MO : Ops)
     876             :     MIB.add(MO);
     877             : 
     878             :   // Insert the Patchable Event Call instruction, that gets lowered properly.
     879             :   return true;
     880             : }
     881             : 
     882             : 
     883             : /// Returns an AttributeList representing the attributes applied to the return
     884             : /// value of the given call.
     885        1941 : static AttributeList getReturnAttrs(FastISel::CallLoweringInfo &CLI) {
     886             :   SmallVector<Attribute::AttrKind, 2> Attrs;
     887        1941 :   if (CLI.RetSExt)
     888          41 :     Attrs.push_back(Attribute::SExt);
     889        1941 :   if (CLI.RetZExt)
     890          36 :     Attrs.push_back(Attribute::ZExt);
     891        1941 :   if (CLI.IsInReg)
     892           0 :     Attrs.push_back(Attribute::InReg);
     893             : 
     894        1941 :   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
     895        3882 :                             Attrs);
     896             : }
     897             : 
     898          25 : bool FastISel::lowerCallTo(const CallInst *CI, const char *SymName,
     899             :                            unsigned NumArgs) {
     900          25 :   MCContext &Ctx = MF->getContext();
     901             :   SmallString<32> MangledName;
     902          50 :   Mangler::getNameWithPrefix(MangledName, SymName, DL);
     903          25 :   MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName);
     904          50 :   return lowerCallTo(CI, Sym, NumArgs);
     905             : }
     906             : 
     907          25 : bool FastISel::lowerCallTo(const CallInst *CI, MCSymbol *Symbol,
     908             :                            unsigned NumArgs) {
     909             :   ImmutableCallSite CS(CI);
     910             : 
     911             :   FunctionType *FTy = CS.getFunctionType();
     912             :   Type *RetTy = CS.getType();
     913             : 
     914             :   ArgListTy Args;
     915          25 :   Args.reserve(NumArgs);
     916             : 
     917             :   // Populate the argument list.
     918             :   // Attributes for args start at offset 1, after the return attribute.
     919         175 :   for (unsigned ArgI = 0; ArgI != NumArgs; ++ArgI) {
     920          75 :     Value *V = CI->getOperand(ArgI);
     921             : 
     922             :     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
     923             : 
     924             :     ArgListEntry Entry;
     925          75 :     Entry.Val = V;
     926          75 :     Entry.Ty = V->getType();
     927          75 :     Entry.setAttributes(&CS, ArgI);
     928          75 :     Args.push_back(Entry);
     929             :   }
     930          50 :   TLI.markLibCallAttributes(MF, CS.getCallingConv(), Args);
     931             : 
     932          50 :   CallLoweringInfo CLI;
     933          25 :   CLI.setCallee(RetTy, FTy, Symbol, std::move(Args), CS, NumArgs);
     934             : 
     935          50 :   return lowerCallTo(CLI);
     936             : }
     937             : 
     938        1941 : bool FastISel::lowerCallTo(CallLoweringInfo &CLI) {
     939             :   // Handle the incoming return values from the call.
     940             :   CLI.clearIns();
     941             :   SmallVector<EVT, 4> RetTys;
     942        1941 :   ComputeValueVTs(TLI, DL, CLI.RetTy, RetTys);
     943             : 
     944             :   SmallVector<ISD::OutputArg, 4> Outs;
     945        1941 :   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, TLI, DL);
     946             : 
     947        7764 :   bool CanLowerReturn = TLI.CanLowerReturn(
     948        7764 :       CLI.CallConv, *FuncInfo.MF, CLI.IsVarArg, Outs, CLI.RetTy->getContext());
     949             : 
     950             :   // FIXME: sret demotion isn't supported yet - bail out.
     951        1941 :   if (!CanLowerReturn)
     952             :     return false;
     953             : 
     954        2751 :   for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
     955        1628 :     EVT VT = RetTys[I];
     956         814 :     MVT RegisterVT = TLI.getRegisterType(CLI.RetTy->getContext(), VT);
     957         814 :     unsigned NumRegs = TLI.getNumRegisters(CLI.RetTy->getContext(), VT);
     958        2442 :     for (unsigned i = 0; i != NumRegs; ++i) {
     959             :       ISD::InputArg MyFlags;
     960         814 :       MyFlags.VT = RegisterVT;
     961         814 :       MyFlags.ArgVT = VT;
     962         814 :       MyFlags.Used = CLI.IsReturnValueUsed;
     963         814 :       if (CLI.RetSExt)
     964             :         MyFlags.Flags.setSExt();
     965         814 :       if (CLI.RetZExt)
     966             :         MyFlags.Flags.setZExt();
     967         814 :       if (CLI.IsInReg)
     968             :         MyFlags.Flags.setInReg();
     969         814 :       CLI.Ins.push_back(MyFlags);
     970             :     }
     971             :   }
     972             : 
     973             :   // Handle all of the outgoing arguments.
     974             :   CLI.clearOuts();
     975        6171 :   for (auto &Arg : CLI.getArgs()) {
     976        4234 :     Type *FinalType = Arg.Ty;
     977        4234 :     if (Arg.IsByVal)
     978          29 :       FinalType = cast<PointerType>(Arg.Ty)->getElementType();
     979        8468 :     bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
     980        8468 :         FinalType, CLI.CallConv, CLI.IsVarArg);
     981             : 
     982             :     ISD::ArgFlagsTy Flags;
     983        4234 :     if (Arg.IsZExt)
     984             :       Flags.setZExt();
     985        4234 :     if (Arg.IsSExt)
     986             :       Flags.setSExt();
     987        4234 :     if (Arg.IsInReg)
     988             :       Flags.setInReg();
     989        4234 :     if (Arg.IsSRet)
     990             :       Flags.setSRet();
     991        4234 :     if (Arg.IsSwiftSelf)
     992             :       Flags.setSwiftSelf();
     993        4234 :     if (Arg.IsSwiftError)
     994             :       Flags.setSwiftError();
     995        4234 :     if (Arg.IsByVal)
     996             :       Flags.setByVal();
     997        4234 :     if (Arg.IsInAlloca) {
     998             :       Flags.setInAlloca();
     999             :       // Set the byval flag for CCAssignFn callbacks that don't know about
    1000             :       // inalloca. This way we can know how many bytes we should've allocated
    1001             :       // and how many bytes a callee cleanup function will pop.  If we port
    1002             :       // inalloca to more targets, we'll have to add custom inalloca handling in
    1003             :       // the various CC lowering callbacks.
    1004             :       Flags.setByVal();
    1005             :     }
    1006        4234 :     if (Arg.IsByVal || Arg.IsInAlloca) {
    1007          35 :       PointerType *Ty = cast<PointerType>(Arg.Ty);
    1008          35 :       Type *ElementTy = Ty->getElementType();
    1009          35 :       unsigned FrameSize = DL.getTypeAllocSize(ElementTy);
    1010             :       // For ByVal, alignment should come from FE. BE will guess if this info is
    1011             :       // not there, but there are cases it cannot get right.
    1012          35 :       unsigned FrameAlign = Arg.Alignment;
    1013          35 :       if (!FrameAlign)
    1014           8 :         FrameAlign = TLI.getByValTypeAlignment(ElementTy, DL);
    1015             :       Flags.setByValSize(FrameSize);
    1016             :       Flags.setByValAlign(FrameAlign);
    1017             :     }
    1018        4234 :     if (Arg.IsNest)
    1019             :       Flags.setNest();
    1020        4234 :     if (NeedsRegBlock)
    1021             :       Flags.setInConsecutiveRegs();
    1022        4234 :     unsigned OriginalAlignment = DL.getABITypeAlignment(Arg.Ty);
    1023             :     Flags.setOrigAlign(OriginalAlignment);
    1024             : 
    1025        4234 :     CLI.OutVals.push_back(Arg.Val);
    1026        4234 :     CLI.OutFlags.push_back(Flags);
    1027             :   }
    1028             : 
    1029        1937 :   if (!fastLowerCall(CLI))
    1030             :     return false;
    1031             : 
    1032             :   // Set all unused physreg defs as dead.
    1033             :   assert(CLI.Call && "No call instruction specified.");
    1034        2076 :   CLI.Call->setPhysRegsDeadExcept(CLI.InRegs, TRI);
    1035             : 
    1036        1038 :   if (CLI.NumResultRegs && CLI.CS)
    1037         518 :     updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
    1038             : 
    1039             :   return true;
    1040             : }
    1041             : 
    1042        1861 : bool FastISel::lowerCall(const CallInst *CI) {
    1043             :   ImmutableCallSite CS(CI);
    1044             : 
    1045             :   FunctionType *FuncTy = CS.getFunctionType();
    1046             :   Type *RetTy = CS.getType();
    1047             : 
    1048             :   ArgListTy Args;
    1049             :   ArgListEntry Entry;
    1050        1861 :   Args.reserve(CS.arg_size());
    1051             : 
    1052        5887 :   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
    1053        5887 :        i != e; ++i) {
    1054        4026 :     Value *V = *i;
    1055             : 
    1056             :     // Skip empty types
    1057        4026 :     if (V->getType()->isEmptyTy())
    1058           0 :       continue;
    1059             : 
    1060        4026 :     Entry.Val = V;
    1061        4026 :     Entry.Ty = V->getType();
    1062             : 
    1063             :     // Skip the first return-type Attribute to get to params.
    1064        8052 :     Entry.setAttributes(&CS, i - CS.arg_begin());
    1065        4026 :     Args.push_back(Entry);
    1066             :   }
    1067             : 
    1068             :   // Check if target-independent constraints permit a tail call here.
    1069             :   // Target-dependent constraints are checked within fastLowerCall.
    1070             :   bool IsTailCall = CI->isTailCall();
    1071        1861 :   if (IsTailCall && !isInTailCallPosition(CS, TM))
    1072             :     IsTailCall = false;
    1073             : 
    1074        3722 :   CallLoweringInfo CLI;
    1075        1861 :   CLI.setCallee(RetTy, FuncTy, CI->getCalledValue(), std::move(Args), CS)
    1076             :       .setTailCall(IsTailCall);
    1077             : 
    1078        3722 :   return lowerCallTo(CLI);
    1079             : }
    1080             : 
    1081        3837 : bool FastISel::selectCall(const User *I) {
    1082             :   const CallInst *Call = cast<CallInst>(I);
    1083             : 
    1084             :   // Handle simple inline asms.
    1085             :   if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
    1086             :     // If the inline asm has side effects, then make sure that no local value
    1087             :     // lives across by flushing the local value map.
    1088         137 :     if (IA->hasSideEffects())
    1089         122 :       flushLocalValueMap();
    1090             : 
    1091             :     // Don't attempt to handle constraints.
    1092         137 :     if (!IA->getConstraintString().empty())
    1093             :       return false;
    1094             : 
    1095             :     unsigned ExtraInfo = 0;
    1096          16 :     if (IA->hasSideEffects())
    1097             :       ExtraInfo |= InlineAsm::Extra_HasSideEffects;
    1098          16 :     if (IA->isAlignStack())
    1099           0 :       ExtraInfo |= InlineAsm::Extra_IsAlignStack;
    1100             : 
    1101          16 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
    1102          32 :             TII.get(TargetOpcode::INLINEASM))
    1103             :         .addExternalSymbol(IA->getAsmString().c_str())
    1104          16 :         .addImm(ExtraInfo);
    1105          16 :     return true;
    1106             :   }
    1107             : 
    1108        3700 :   MachineModuleInfo &MMI = FuncInfo.MF->getMMI();
    1109        3700 :   computeUsesVAFloatArgument(*Call, MMI);
    1110             : 
    1111             :   // Handle intrinsic function calls.
    1112             :   if (const auto *II = dyn_cast<IntrinsicInst>(Call))
    1113        1839 :     return selectIntrinsicCall(II);
    1114             : 
    1115             :   // Usually, it does not make sense to initialize a value,
    1116             :   // make an unrelated function call and use the value, because
    1117             :   // it tends to be spilled on the stack. So, we move the pointer
    1118             :   // to the last local value to the beginning of the block, so that
    1119             :   // all the values which have already been materialized,
    1120             :   // appear after the call. It also makes sense to skip intrinsics
    1121             :   // since they tend to be inlined.
    1122        1861 :   flushLocalValueMap();
    1123             : 
    1124        1861 :   return lowerCall(Call);
    1125             : }
    1126             : 
    1127        1839 : bool FastISel::selectIntrinsicCall(const IntrinsicInst *II) {
    1128        1839 :   switch (II->getIntrinsicID()) {
    1129             :   default:
    1130             :     break;
    1131             :   // At -O0 we don't care about the lifetime intrinsics.
    1132             :   case Intrinsic::lifetime_start:
    1133             :   case Intrinsic::lifetime_end:
    1134             :   // The donothing intrinsic does, well, nothing.
    1135             :   case Intrinsic::donothing:
    1136             :   // Neither does the sideeffect intrinsic.
    1137             :   case Intrinsic::sideeffect:
    1138             :   // Neither does the assume intrinsic; it's also OK not to codegen its operand.
    1139             :   case Intrinsic::assume:
    1140             :     return true;
    1141             :   case Intrinsic::dbg_declare: {
    1142             :     const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
    1143             :     assert(DI->getVariable() && "Missing variable");
    1144         353 :     if (!FuncInfo.MF->getMMI().hasDebugInfo()) {
    1145             :       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
    1146             :       return true;
    1147             :     }
    1148             : 
    1149             :     const Value *Address = DI->getAddress();
    1150         706 :     if (!Address || isa<UndefValue>(Address)) {
    1151             :       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
    1152             :       return true;
    1153             :     }
    1154             : 
    1155             :     // Byval arguments with frame indices were already handled after argument
    1156             :     // lowering and before isel.
    1157             :     const auto *Arg =
    1158         350 :         dyn_cast<Argument>(Address->stripInBoundsConstantOffsets());
    1159          26 :     if (Arg && FuncInfo.getArgumentFrameIndex(Arg) != INT_MAX)
    1160             :       return true;
    1161             : 
    1162             :     Optional<MachineOperand> Op;
    1163         340 :     if (unsigned Reg = lookUpRegForValue(Address))
    1164             :       Op = MachineOperand::CreateReg(Reg, false);
    1165             : 
    1166             :     // If we have a VLA that has a "use" in a metadata node that's then used
    1167             :     // here but it has no other uses, then we have a problem. E.g.,
    1168             :     //
    1169             :     //   int foo (const int *x) {
    1170             :     //     char a[*x];
    1171             :     //     return 0;
    1172             :     //   }
    1173             :     //
    1174             :     // If we assign 'a' a vreg and fast isel later on has to use the selection
    1175             :     // DAG isel, it will want to copy the value to the vreg. However, there are
    1176             :     // no uses, which goes counter to what selection DAG isel expects.
    1177         621 :     if (!Op && !Address->use_empty() && isa<Instruction>(Address) &&
    1178             :         (!isa<AllocaInst>(Address) ||
    1179         280 :          !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
    1180           1 :       Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address),
    1181           1 :                                      false);
    1182             : 
    1183         340 :     if (Op) {
    1184             :       assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
    1185             :              "Expected inlined-at fields to agree");
    1186          37 :       if (Op->isReg()) {
    1187             :         Op->setIsDebug(true);
    1188             :         // A dbg.declare describes the address of a source variable, so lower it
    1189             :         // into an indirect DBG_VALUE.
    1190          37 :         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
    1191          37 :                 TII.get(TargetOpcode::DBG_VALUE), /*IsIndirect*/ true,
    1192         111 :                 Op->getReg(), DI->getVariable(), DI->getExpression());
    1193             :       } else
    1194           0 :         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
    1195           0 :                 TII.get(TargetOpcode::DBG_VALUE))
    1196             :             .add(*Op)
    1197             :             .addImm(0)
    1198             :             .addMetadata(DI->getVariable())
    1199             :             .addMetadata(DI->getExpression());
    1200             :     } else {
    1201             :       // We can't yet handle anything else here because it would require
    1202             :       // generating code, thus altering codegen because of debug info.
    1203             :       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
    1204             :     }
    1205             :     return true;
    1206             :   }
    1207             :   case Intrinsic::dbg_value: {
    1208             :     // This form of DBG_VALUE is target-independent.
    1209             :     const DbgValueInst *DI = cast<DbgValueInst>(II);
    1210          49 :     const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
    1211             :     const Value *V = DI->getValue();
    1212             :     assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
    1213             :            "Expected inlined-at fields to agree");
    1214          49 :     if (!V) {
    1215             :       // Currently the optimizer can produce this; insert an undef to
    1216             :       // help debugging.  Probably the optimizer should not do this.
    1217           0 :       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, false, 0U,
    1218           0 :               DI->getVariable(), DI->getExpression());
    1219             :     } else if (const auto *CI = dyn_cast<ConstantInt>(V)) {
    1220          14 :       if (CI->getBitWidth() > 64)
    1221           0 :         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
    1222             :             .addCImm(CI)
    1223             :             .addImm(0U)
    1224             :             .addMetadata(DI->getVariable())
    1225             :             .addMetadata(DI->getExpression());
    1226             :       else
    1227          14 :         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
    1228          14 :             .addImm(CI->getZExtValue())
    1229             :             .addImm(0U)
    1230             :             .addMetadata(DI->getVariable())
    1231             :             .addMetadata(DI->getExpression());
    1232             :     } else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
    1233           0 :       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
    1234             :           .addFPImm(CF)
    1235             :           .addImm(0U)
    1236             :           .addMetadata(DI->getVariable())
    1237             :           .addMetadata(DI->getExpression());
    1238          35 :     } else if (unsigned Reg = lookUpRegForValue(V)) {
    1239             :       // FIXME: This does not handle register-indirect values at offset 0.
    1240             :       bool IsIndirect = false;
    1241          32 :       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, IsIndirect, Reg,
    1242          32 :               DI->getVariable(), DI->getExpression());
    1243             :     } else {
    1244             :       // We can't yet handle anything else here because it would require
    1245             :       // generating code, thus altering codegen because of debug info.
    1246             :       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
    1247             :     }
    1248             :     return true;
    1249             :   }
    1250           3 :   case Intrinsic::objectsize: {
    1251           3 :     ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
    1252           3 :     unsigned long long Res = CI->isZero() ? -1ULL : 0;
    1253           3 :     Constant *ResCI = ConstantInt::get(II->getType(), Res);
    1254           3 :     unsigned ResultReg = getRegForValue(ResCI);
    1255           3 :     if (!ResultReg)
    1256             :       return false;
    1257           3 :     updateValueMap(II, ResultReg);
    1258           3 :     return true;
    1259             :   }
    1260           6 :   case Intrinsic::invariant_group_barrier:
    1261             :   case Intrinsic::expect: {
    1262          12 :     unsigned ResultReg = getRegForValue(II->getArgOperand(0));
    1263           6 :     if (!ResultReg)
    1264             :       return false;
    1265           6 :     updateValueMap(II, ResultReg);
    1266           6 :     return true;
    1267             :   }
    1268          26 :   case Intrinsic::experimental_stackmap:
    1269          26 :     return selectStackmap(II);
    1270          39 :   case Intrinsic::experimental_patchpoint_void:
    1271             :   case Intrinsic::experimental_patchpoint_i64:
    1272          39 :     return selectPatchpoint(II);
    1273             : 
    1274           0 :   case Intrinsic::xray_customevent:
    1275           0 :     return selectXRayCustomEvent(II);
    1276             :   }
    1277             : 
    1278        1349 :   return fastLowerIntrinsicCall(II);
    1279             : }
    1280             : 
    1281         912 : bool FastISel::selectCast(const User *I, unsigned Opcode) {
    1282        1824 :   EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
    1283         912 :   EVT DstVT = TLI.getValueType(DL, I->getType());
    1284             : 
    1285        1822 :   if (SrcVT == MVT::Other || !SrcVT.isSimple() || DstVT == MVT::Other ||
    1286             :       !DstVT.isSimple())
    1287             :     // Unhandled type. Halt "fast" selection and bail.
    1288             :     return false;
    1289             : 
    1290             :   // Check if the destination type is legal.
    1291         910 :   if (!TLI.isTypeLegal(DstVT))
    1292             :     return false;
    1293             : 
    1294             :   // Check if the source operand is legal.
    1295             :   if (!TLI.isTypeLegal(SrcVT))
    1296             :     return false;
    1297             : 
    1298         284 :   unsigned InputReg = getRegForValue(I->getOperand(0));
    1299         284 :   if (!InputReg)
    1300             :     // Unhandled operand.  Halt "fast" selection and bail.
    1301             :     return false;
    1302             : 
    1303         281 :   bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
    1304             : 
    1305         281 :   unsigned ResultReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
    1306         562 :                                   Opcode, InputReg, InputRegIsKill);
    1307         281 :   if (!ResultReg)
    1308             :     return false;
    1309             : 
    1310         176 :   updateValueMap(I, ResultReg);
    1311         176 :   return true;
    1312             : }
    1313             : 
    1314        2155 : bool FastISel::selectBitCast(const User *I) {
    1315             :   // If the bitcast doesn't change the type, just use the operand value.
    1316        4310 :   if (I->getType() == I->getOperand(0)->getType()) {
    1317           3 :     unsigned Reg = getRegForValue(I->getOperand(0));
    1318           3 :     if (!Reg)
    1319             :       return false;
    1320           3 :     updateValueMap(I, Reg);
    1321           3 :     return true;
    1322             :   }
    1323             : 
    1324             :   // Bitcasts of other values become reg-reg copies or BITCAST operators.
    1325        2152 :   EVT SrcEVT = TLI.getValueType(DL, I->getOperand(0)->getType());
    1326        2152 :   EVT DstEVT = TLI.getValueType(DL, I->getType());
    1327             :   if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
    1328        2152 :       !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
    1329             :     // Unhandled type. Halt "fast" selection and bail.
    1330             :     return false;
    1331             : 
    1332             :   MVT SrcVT = SrcEVT.getSimpleVT();
    1333             :   MVT DstVT = DstEVT.getSimpleVT();
    1334        2118 :   unsigned Op0 = getRegForValue(I->getOperand(0));
    1335        2118 :   if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
    1336             :     return false;
    1337        2110 :   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
    1338             : 
    1339             :   // First, try to perform the bitcast by inserting a reg-reg copy.
    1340             :   unsigned ResultReg = 0;
    1341        2110 :   if (SrcVT == DstVT) {
    1342         270 :     const TargetRegisterClass *SrcClass = TLI.getRegClassFor(SrcVT);
    1343         270 :     const TargetRegisterClass *DstClass = TLI.getRegClassFor(DstVT);
    1344             :     // Don't attempt a cross-class copy. It will likely fail.
    1345         270 :     if (SrcClass == DstClass) {
    1346         270 :       ResultReg = createResultReg(DstClass);
    1347         540 :       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
    1348         810 :               TII.get(TargetOpcode::COPY), ResultReg).addReg(Op0);
    1349             :     }
    1350             :   }
    1351             : 
    1352             :   // If the reg-reg copy failed, select a BITCAST opcode.
    1353         270 :   if (!ResultReg)
    1354        1840 :     ResultReg = fastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
    1355             : 
    1356        2110 :   if (!ResultReg)
    1357             :     return false;
    1358             : 
    1359         286 :   updateValueMap(I, ResultReg);
    1360         286 :   return true;
    1361             : }
    1362             : 
    1363             : // Remove local value instructions starting from the instruction after
    1364             : // SavedLastLocalValue to the current function insert point.
    1365         763 : void FastISel::removeDeadLocalValueCode(MachineInstr *SavedLastLocalValue)
    1366             : {
    1367         763 :   MachineInstr *CurLastLocalValue = getLastLocalValue();
    1368         763 :   if (CurLastLocalValue != SavedLastLocalValue) {
    1369             :     // Find the first local value instruction to be deleted. 
    1370             :     // This is the instruction after SavedLastLocalValue if it is non-NULL.
    1371             :     // Otherwise it's the first instruction in the block.
    1372             :     MachineBasicBlock::iterator FirstDeadInst(SavedLastLocalValue);
    1373          24 :     if (SavedLastLocalValue)
    1374             :       ++FirstDeadInst;
    1375             :     else
    1376          21 :       FirstDeadInst = FuncInfo.MBB->getFirstNonPHI();
    1377             :     setLastLocalValue(SavedLastLocalValue);
    1378          24 :     removeDeadCode(FirstDeadInst, FuncInfo.InsertPt);
    1379             :   }
    1380         763 : }
    1381             : 
    1382       27555 : bool FastISel::selectInstruction(const Instruction *I) {
    1383       27555 :   MachineInstr *SavedLastLocalValue = getLastLocalValue();
    1384             :   // Just before the terminator instruction, insert instructions to
    1385             :   // feed PHI nodes in successor blocks.
    1386       27555 :   if (isa<TerminatorInst>(I)) {
    1387       10592 :     if (!handlePHINodesInSuccessorBlocks(I->getParent())) {
    1388             :       // PHI node handling may have generated local value instructions,
    1389             :       // even though it failed to handle all PHI nodes.
    1390             :       // We remove these instructions because SelectionDAGISel will generate 
    1391             :       // them again.
    1392          58 :       removeDeadLocalValueCode(SavedLastLocalValue);
    1393          58 :       return false;
    1394             :     }
    1395             :   }
    1396             : 
    1397             :   // FastISel does not handle any operand bundles except OB_funclet.
    1398       27497 :   if (ImmutableCallSite CS = ImmutableCallSite(I))
    1399        3925 :     for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i)
    1400           0 :       if (CS.getOperandBundleAt(i).getTagID() != LLVMContext::OB_funclet)
    1401           0 :         return false;
    1402             : 
    1403             :   DbgLoc = I->getDebugLoc();
    1404             : 
    1405       27497 :   SavedInsertPt = FuncInfo.InsertPt;
    1406             : 
    1407             :   if (const auto *Call = dyn_cast<CallInst>(I)) {
    1408             :     const Function *F = Call->getCalledFunction();
    1409             :     LibFunc Func;
    1410             : 
    1411             :     // As a special case, don't handle calls to builtin library functions that
    1412             :     // may be translated directly to target instructions.
    1413        7022 :     if (F && !F->hasLocalLinkage() && F->hasName() &&
    1414        3602 :         LibInfo->getLibFunc(F->getName(), Func) &&
    1415          91 :         LibInfo->hasOptimizedCodeGen(Func))
    1416          12 :       return false;
    1417             : 
    1418             :     // Don't handle Intrinsic::trap if a trap function is specified.
    1419        3792 :     if (F && F->getIntrinsicID() == Intrinsic::trap &&
    1420           8 :         Call->hasFnAttr("trap-func-name"))
    1421             :       return false;
    1422             :   }
    1423             : 
    1424             :   // First, try doing target-independent selection.
    1425       27485 :   if (!SkipTargetIndependentISel) {
    1426       23700 :     if (selectOperator(I, I->getOpcode())) {
    1427             :       ++NumFastIselSuccessIndependent;
    1428        8330 :       DbgLoc = DebugLoc();
    1429        4165 :       return true;
    1430             :     }
    1431             :     // Remove dead code.
    1432       19535 :     recomputeInsertPt();
    1433       39070 :     if (SavedInsertPt != FuncInfo.InsertPt)
    1434          51 :       removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
    1435       19535 :     SavedInsertPt = FuncInfo.InsertPt;
    1436             :   }
    1437             :   // Next, try calling the target to attempt to handle the instruction.
    1438       23320 :   if (fastSelectInstruction(I)) {
    1439             :     ++NumFastIselSuccessTarget;
    1440       36940 :     DbgLoc = DebugLoc();
    1441       18470 :     return true;
    1442             :   }
    1443             :   // Remove dead code.
    1444        4850 :   recomputeInsertPt();
    1445        9700 :   if (SavedInsertPt != FuncInfo.InsertPt)
    1446          15 :     removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
    1447             : 
    1448        9700 :   DbgLoc = DebugLoc();
    1449             :   // Undo phi node updates, because they will be added again by SelectionDAG.
    1450        4850 :   if (isa<TerminatorInst>(I)) {
    1451             :     // PHI node handling may have generated local value instructions. 
    1452             :     // We remove them because SelectionDAGISel will generate them again.
    1453         705 :     removeDeadLocalValueCode(SavedLastLocalValue);
    1454         705 :     FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
    1455             :   }
    1456             :   return false;
    1457             : }
    1458             : 
    1459             : /// Emit an unconditional branch to the given block, unless it is the immediate
    1460             : /// (fall-through) successor, and update the CFG.
    1461        1458 : void FastISel::fastEmitBranch(MachineBasicBlock *MSucc,
    1462             :                               const DebugLoc &DbgLoc) {
    1463        4142 :   if (FuncInfo.MBB->getBasicBlock()->size() > 1 &&
    1464        1226 :       FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
    1465             :     // For more accurate line information if this is the only instruction
    1466             :     // in the block then emit it, otherwise we have the unconditional
    1467             :     // fall-through case, which needs no instructions.
    1468             :   } else {
    1469             :     // The unconditional branch case.
    1470        1068 :     TII.insertBranch(*FuncInfo.MBB, MSucc, nullptr,
    1471        1068 :                      SmallVector<MachineOperand, 0>(), DbgLoc);
    1472             :   }
    1473        1458 :   if (FuncInfo.BPI) {
    1474             :     auto BranchProbability = FuncInfo.BPI->getEdgeProbability(
    1475         240 :         FuncInfo.MBB->getBasicBlock(), MSucc->getBasicBlock());
    1476         240 :     FuncInfo.MBB->addSuccessor(MSucc, BranchProbability);
    1477             :   } else
    1478        1218 :     FuncInfo.MBB->addSuccessorWithoutProb(MSucc);
    1479        1458 : }
    1480             : 
    1481         571 : void FastISel::finishCondBranch(const BasicBlock *BranchBB,
    1482             :                                 MachineBasicBlock *TrueMBB,
    1483             :                                 MachineBasicBlock *FalseMBB) {
    1484             :   // Add TrueMBB as successor unless it is equal to the FalseMBB: This can
    1485             :   // happen in degenerate IR and MachineIR forbids to have a block twice in the
    1486             :   // successor/predecessor lists.
    1487         571 :   if (TrueMBB != FalseMBB) {
    1488         568 :     if (FuncInfo.BPI) {
    1489             :       auto BranchProbability =
    1490         160 :           FuncInfo.BPI->getEdgeProbability(BranchBB, TrueMBB->getBasicBlock());
    1491         160 :       FuncInfo.MBB->addSuccessor(TrueMBB, BranchProbability);
    1492             :     } else
    1493         408 :       FuncInfo.MBB->addSuccessorWithoutProb(TrueMBB);
    1494             :   }
    1495             : 
    1496         571 :   fastEmitBranch(FalseMBB, DbgLoc);
    1497         571 : }
    1498             : 
    1499             : /// Emit an FNeg operation.
    1500           3 : bool FastISel::selectFNeg(const User *I) {
    1501           3 :   unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
    1502           3 :   if (!OpReg)
    1503             :     return false;
    1504           3 :   bool OpRegIsKill = hasTrivialKill(I);
    1505             : 
    1506             :   // If the target has ISD::FNEG, use it.
    1507           3 :   EVT VT = TLI.getValueType(DL, I->getType());
    1508           3 :   unsigned ResultReg = fastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(), ISD::FNEG,
    1509           6 :                                   OpReg, OpRegIsKill);
    1510           3 :   if (ResultReg) {
    1511           0 :     updateValueMap(I, ResultReg);
    1512           0 :     return true;
    1513             :   }
    1514             : 
    1515             :   // Bitcast the value to integer, twiddle the sign bit with xor,
    1516             :   // and then bitcast it back to floating-point.
    1517           3 :   if (VT.getSizeInBits() > 64)
    1518             :     return false;
    1519           3 :   EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
    1520           3 :   if (!TLI.isTypeLegal(IntVT))
    1521             :     return false;
    1522             : 
    1523             :   unsigned IntReg = fastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
    1524           3 :                                ISD::BITCAST, OpReg, OpRegIsKill);
    1525           3 :   if (!IntReg)
    1526             :     return false;
    1527             : 
    1528           3 :   unsigned IntResultReg = fastEmit_ri_(
    1529             :       IntVT.getSimpleVT(), ISD::XOR, IntReg, /*IsKill=*/true,
    1530           6 :       UINT64_C(1) << (VT.getSizeInBits() - 1), IntVT.getSimpleVT());
    1531           3 :   if (!IntResultReg)
    1532             :     return false;
    1533             : 
    1534           3 :   ResultReg = fastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(), ISD::BITCAST,
    1535           3 :                          IntResultReg, /*IsKill=*/true);
    1536           3 :   if (!ResultReg)
    1537             :     return false;
    1538             : 
    1539           3 :   updateValueMap(I, ResultReg);
    1540           3 :   return true;
    1541             : }
    1542             : 
    1543         450 : bool FastISel::selectExtractValue(const User *U) {
    1544             :   const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
    1545             :   if (!EVI)
    1546             :     return false;
    1547             : 
    1548             :   // Make sure we only try to handle extracts with a legal result.  But also
    1549             :   // allow i1 because it's easy.
    1550         450 :   EVT RealVT = TLI.getValueType(DL, EVI->getType(), /*AllowUnknown=*/true);
    1551         450 :   if (!RealVT.isSimple())
    1552             :     return false;
    1553             :   MVT VT = RealVT.getSimpleVT();
    1554         636 :   if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
    1555             :     return false;
    1556             : 
    1557             :   const Value *Op0 = EVI->getOperand(0);
    1558         446 :   Type *AggTy = Op0->getType();
    1559             : 
    1560             :   // Get the base result register.
    1561             :   unsigned ResultReg;
    1562         446 :   DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
    1563         892 :   if (I != FuncInfo.ValueMap.end())
    1564         218 :     ResultReg = I->second;
    1565         228 :   else if (isa<Instruction>(Op0))
    1566         224 :     ResultReg = FuncInfo.InitializeRegForValue(Op0);
    1567             :   else
    1568             :     return false; // fast-isel can't handle aggregate constants at the moment
    1569             : 
    1570             :   // Get the actual result register, which is an offset from the base register.
    1571             :   unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
    1572             : 
    1573             :   SmallVector<EVT, 4> AggValueVTs;
    1574         442 :   ComputeValueVTs(TLI, DL, AggTy, AggValueVTs);
    1575             : 
    1576        1114 :   for (unsigned i = 0; i < VTIndex; i++)
    1577         672 :     ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
    1578             : 
    1579         442 :   updateValueMap(EVI, ResultReg);
    1580             :   return true;
    1581             : }
    1582             : 
    1583       24550 : bool FastISel::selectOperator(const User *I, unsigned Opcode) {
    1584       24550 :   switch (Opcode) {
    1585         469 :   case Instruction::Add:
    1586         469 :     return selectBinaryOp(I, ISD::ADD);
    1587         245 :   case Instruction::FAdd:
    1588         245 :     return selectBinaryOp(I, ISD::FADD);
    1589          93 :   case Instruction::Sub:
    1590          93 :     return selectBinaryOp(I, ISD::SUB);
    1591          13 :   case Instruction::FSub:
    1592             :     // FNeg is currently represented in LLVM IR as a special case of FSub.
    1593          13 :     if (BinaryOperator::isFNeg(I))
    1594           3 :       return selectFNeg(I);
    1595          10 :     return selectBinaryOp(I, ISD::FSUB);
    1596          64 :   case Instruction::Mul:
    1597          64 :     return selectBinaryOp(I, ISD::MUL);
    1598          17 :   case Instruction::FMul:
    1599          17 :     return selectBinaryOp(I, ISD::FMUL);
    1600          18 :   case Instruction::SDiv:
    1601          18 :     return selectBinaryOp(I, ISD::SDIV);
    1602          23 :   case Instruction::UDiv:
    1603          23 :     return selectBinaryOp(I, ISD::UDIV);
    1604          10 :   case Instruction::FDiv:
    1605          10 :     return selectBinaryOp(I, ISD::FDIV);
    1606          41 :   case Instruction::SRem:
    1607          41 :     return selectBinaryOp(I, ISD::SREM);
    1608          18 :   case Instruction::URem:
    1609          18 :     return selectBinaryOp(I, ISD::UREM);
    1610           1 :   case Instruction::FRem:
    1611           1 :     return selectBinaryOp(I, ISD::FREM);
    1612          36 :   case Instruction::Shl:
    1613          36 :     return selectBinaryOp(I, ISD::SHL);
    1614          41 :   case Instruction::LShr:
    1615          41 :     return selectBinaryOp(I, ISD::SRL);
    1616          28 :   case Instruction::AShr:
    1617          28 :     return selectBinaryOp(I, ISD::SRA);
    1618         152 :   case Instruction::And:
    1619         152 :     return selectBinaryOp(I, ISD::AND);
    1620          98 :   case Instruction::Or:
    1621          98 :     return selectBinaryOp(I, ISD::OR);
    1622         136 :   case Instruction::Xor:
    1623         136 :     return selectBinaryOp(I, ISD::XOR);
    1624             : 
    1625         267 :   case Instruction::GetElementPtr:
    1626         267 :     return selectGetElementPtr(I);
    1627             : 
    1628             :   case Instruction::Br: {
    1629             :     const BranchInst *BI = cast<BranchInst>(I);
    1630             : 
    1631        1229 :     if (BI->isUnconditional()) {
    1632         703 :       const BasicBlock *LLVMSucc = BI->getSuccessor(0);
    1633        1406 :       MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
    1634         703 :       fastEmitBranch(MSucc, BI->getDebugLoc());
    1635             :       return true;
    1636             :     }
    1637             : 
    1638             :     // Conditional branches are not handed yet.
    1639             :     // Halt "fast" selection and bail.
    1640             :     return false;
    1641             :   }
    1642             : 
    1643          97 :   case Instruction::Unreachable:
    1644          97 :     if (TM.Options.TrapUnreachable)
    1645          12 :       return fastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0;
    1646             :     else
    1647             :       return true;
    1648             : 
    1649          16 :   case Instruction::Alloca:
    1650             :     // FunctionLowering has the static-sized case covered.
    1651          16 :     if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
    1652             :       return true;
    1653             : 
    1654             :     // Dynamic-sized alloca is not handled yet.
    1655             :     return false;
    1656             : 
    1657        3784 :   case Instruction::Call:
    1658        3784 :     return selectCall(I);
    1659             : 
    1660        2103 :   case Instruction::BitCast:
    1661        2103 :     return selectBitCast(I);
    1662             : 
    1663          32 :   case Instruction::FPToSI:
    1664          32 :     return selectCast(I, ISD::FP_TO_SINT);
    1665         349 :   case Instruction::ZExt:
    1666         349 :     return selectCast(I, ISD::ZERO_EXTEND);
    1667         249 :   case Instruction::SExt:
    1668         249 :     return selectCast(I, ISD::SIGN_EXTEND);
    1669         132 :   case Instruction::Trunc:
    1670         132 :     return selectCast(I, ISD::TRUNCATE);
    1671          91 :   case Instruction::SIToFP:
    1672          91 :     return selectCast(I, ISD::SINT_TO_FP);
    1673             : 
    1674          99 :   case Instruction::IntToPtr: // Deliberate fall-through.
    1675             :   case Instruction::PtrToInt: {
    1676         198 :     EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
    1677          99 :     EVT DstVT = TLI.getValueType(DL, I->getType());
    1678          99 :     if (DstVT.bitsGT(SrcVT))
    1679           3 :       return selectCast(I, ISD::ZERO_EXTEND);
    1680          96 :     if (DstVT.bitsLT(SrcVT))
    1681           9 :       return selectCast(I, ISD::TRUNCATE);
    1682          87 :     unsigned Reg = getRegForValue(I->getOperand(0));
    1683          87 :     if (!Reg)
    1684             :       return false;
    1685          82 :     updateValueMap(I, Reg);
    1686          82 :     return true;
    1687             :   }
    1688             : 
    1689         450 :   case Instruction::ExtractValue:
    1690         450 :     return selectExtractValue(I);
    1691             : 
    1692           0 :   case Instruction::PHI:
    1693           0 :     llvm_unreachable("FastISel shouldn't visit PHI nodes!");
    1694             : 
    1695             :   default:
    1696             :     // Unhandled instruction. Halt "fast" selection and bail.
    1697             :     return false;
    1698             :   }
    1699             : }
    1700             : 
    1701        8591 : FastISel::FastISel(FunctionLoweringInfo &FuncInfo,
    1702             :                    const TargetLibraryInfo *LibInfo,
    1703        8591 :                    bool SkipTargetIndependentISel)
    1704       17182 :     : FuncInfo(FuncInfo), MF(FuncInfo.MF), MRI(FuncInfo.MF->getRegInfo()),
    1705       17182 :       MFI(FuncInfo.MF->getFrameInfo()), MCP(*FuncInfo.MF->getConstantPool()),
    1706       17182 :       TM(FuncInfo.MF->getTarget()), DL(MF->getDataLayout()),
    1707        8591 :       TII(*MF->getSubtarget().getInstrInfo()),
    1708        8591 :       TLI(*MF->getSubtarget().getTargetLowering()),
    1709        8591 :       TRI(*MF->getSubtarget().getRegisterInfo()), LibInfo(LibInfo),
    1710      103092 :       SkipTargetIndependentISel(SkipTargetIndependentISel) {}
    1711             : 
    1712             : FastISel::~FastISel() = default;
    1713             : 
    1714           0 : bool FastISel::fastLowerArguments() { return false; }
    1715             : 
    1716         594 : bool FastISel::fastLowerCall(CallLoweringInfo & /*CLI*/) { return false; }
    1717             : 
    1718         127 : bool FastISel::fastLowerIntrinsicCall(const IntrinsicInst * /*II*/) {
    1719         127 :   return false;
    1720             : }
    1721             : 
    1722           6 : unsigned FastISel::fastEmit_(MVT, MVT, unsigned) { return 0; }
    1723             : 
    1724           0 : unsigned FastISel::fastEmit_r(MVT, MVT, unsigned, unsigned /*Op0*/,
    1725             :                               bool /*Op0IsKill*/) {
    1726           0 :   return 0;
    1727             : }
    1728             : 
    1729           0 : unsigned FastISel::fastEmit_rr(MVT, MVT, unsigned, unsigned /*Op0*/,
    1730             :                                bool /*Op0IsKill*/, unsigned /*Op1*/,
    1731             :                                bool /*Op1IsKill*/) {
    1732           0 :   return 0;
    1733             : }
    1734             : 
    1735           0 : unsigned FastISel::fastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
    1736           0 :   return 0;
    1737             : }
    1738             : 
    1739           0 : unsigned FastISel::fastEmit_f(MVT, MVT, unsigned,
    1740             :                               const ConstantFP * /*FPImm*/) {
    1741           0 :   return 0;
    1742             : }
    1743             : 
    1744           3 : unsigned FastISel::fastEmit_ri(MVT, MVT, unsigned, unsigned /*Op0*/,
    1745             :                                bool /*Op0IsKill*/, uint64_t /*Imm*/) {
    1746           3 :   return 0;
    1747             : }
    1748             : 
    1749             : /// This method is a wrapper of fastEmit_ri. It first tries to emit an
    1750             : /// instruction with an immediate operand using fastEmit_ri.
    1751             : /// If that fails, it materializes the immediate into a register and try
    1752             : /// fastEmit_rr instead.
    1753         942 : unsigned FastISel::fastEmit_ri_(MVT VT, unsigned Opcode, unsigned Op0,
    1754             :                                 bool Op0IsKill, uint64_t Imm, MVT ImmType) {
    1755             :   // If this is a multiply by a power of two, emit this as a shift left.
    1756         942 :   if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
    1757             :     Opcode = ISD::SHL;
    1758          30 :     Imm = Log2_64(Imm);
    1759         912 :   } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
    1760             :     // div x, 8 -> srl x, 3
    1761             :     Opcode = ISD::SRL;
    1762           3 :     Imm = Log2_64(Imm);
    1763             :   }
    1764             : 
    1765             :   // Horrible hack (to be removed), check to make sure shift amounts are
    1766             :   // in-range.
    1767        1039 :   if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
    1768          97 :       Imm >= VT.getSizeInBits())
    1769             :     return 0;
    1770             : 
    1771             :   // First check if immediate type is legal. If not, we can't use the ri form.
    1772         939 :   unsigned ResultReg = fastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
    1773         939 :   if (ResultReg)
    1774             :     return ResultReg;
    1775          62 :   unsigned MaterialReg = fastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
    1776             :   bool IsImmKill = true;
    1777          62 :   if (!MaterialReg) {
    1778             :     // This is a bit ugly/slow, but failing here means falling out of
    1779             :     // fast-isel, which would be very slow.
    1780             :     IntegerType *ITy =
    1781          42 :         IntegerType::get(FuncInfo.Fn->getContext(), VT.getSizeInBits());
    1782          42 :     MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
    1783          42 :     if (!MaterialReg)
    1784             :       return 0;
    1785             :     // FIXME: If the materialized register here has no uses yet then this
    1786             :     // will be the first use and we should be able to mark it as killed.
    1787             :     // However, the local value area for materialising constant expressions
    1788             :     // grows down, not up, which means that any constant expressions we generate
    1789             :     // later which also use 'Imm' could be after this instruction and therefore
    1790             :     // after this kill.
    1791             :     IsImmKill = false;
    1792             :   }
    1793          62 :   return fastEmit_rr(VT, VT, Opcode, Op0, Op0IsKill, MaterialReg, IsImmKill);
    1794             : }
    1795             : 
    1796       18862 : unsigned FastISel::createResultReg(const TargetRegisterClass *RC) {
    1797       18862 :   return MRI.createVirtualRegister(RC);
    1798             : }
    1799             : 
    1800       14236 : unsigned FastISel::constrainOperandRegClass(const MCInstrDesc &II, unsigned Op,
    1801             :                                             unsigned OpNum) {
    1802       14236 :   if (TargetRegisterInfo::isVirtualRegister(Op)) {
    1803             :     const TargetRegisterClass *RegClass =
    1804        9920 :         TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF);
    1805        9920 :     if (!MRI.constrainRegClass(Op, RegClass)) {
    1806             :       // If it's not legal to COPY between the register classes, something
    1807             :       // has gone very wrong before we got here.
    1808           0 :       unsigned NewOp = createResultReg(RegClass);
    1809           0 :       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
    1810           0 :               TII.get(TargetOpcode::COPY), NewOp).addReg(Op);
    1811           0 :       return NewOp;
    1812             :     }
    1813             :   }
    1814             :   return Op;
    1815             : }
    1816             : 
    1817         285 : unsigned FastISel::fastEmitInst_(unsigned MachineInstOpcode,
    1818             :                                  const TargetRegisterClass *RC) {
    1819         285 :   unsigned ResultReg = createResultReg(RC);
    1820         285 :   const MCInstrDesc &II = TII.get(MachineInstOpcode);
    1821             : 
    1822         285 :   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg);
    1823         285 :   return ResultReg;
    1824             : }
    1825             : 
    1826         591 : unsigned FastISel::fastEmitInst_r(unsigned MachineInstOpcode,
    1827             :                                   const TargetRegisterClass *RC, unsigned Op0,
    1828             :                                   bool Op0IsKill) {
    1829         591 :   const MCInstrDesc &II = TII.get(MachineInstOpcode);
    1830             : 
    1831         591 :   unsigned ResultReg = createResultReg(RC);
    1832        1182 :   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
    1833             : 
    1834         591 :   if (II.getNumDefs() >= 1)
    1835        1160 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
    1836         580 :         .addReg(Op0, getKillRegState(Op0IsKill));
    1837             :   else {
    1838          22 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
    1839          11 :         .addReg(Op0, getKillRegState(Op0IsKill));
    1840          22 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
    1841          22 :             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
    1842             :   }
    1843             : 
    1844         591 :   return ResultReg;
    1845             : }
    1846             : 
    1847        1018 : unsigned FastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
    1848             :                                    const TargetRegisterClass *RC, unsigned Op0,
    1849             :                                    bool Op0IsKill, unsigned Op1,
    1850             :                                    bool Op1IsKill) {
    1851        1018 :   const MCInstrDesc &II = TII.get(MachineInstOpcode);
    1852             : 
    1853        1018 :   unsigned ResultReg = createResultReg(RC);
    1854        2036 :   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
    1855        2036 :   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
    1856             : 
    1857        1018 :   if (II.getNumDefs() >= 1)
    1858        2036 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
    1859        1018 :         .addReg(Op0, getKillRegState(Op0IsKill))
    1860        1018 :         .addReg(Op1, getKillRegState(Op1IsKill));
    1861             :   else {
    1862           0 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
    1863           0 :         .addReg(Op0, getKillRegState(Op0IsKill))
    1864           0 :         .addReg(Op1, getKillRegState(Op1IsKill));
    1865           0 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
    1866           0 :             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
    1867             :   }
    1868        1018 :   return ResultReg;
    1869             : }
    1870             : 
    1871          58 : unsigned FastISel::fastEmitInst_rrr(unsigned MachineInstOpcode,
    1872             :                                     const TargetRegisterClass *RC, unsigned Op0,
    1873             :                                     bool Op0IsKill, unsigned Op1,
    1874             :                                     bool Op1IsKill, unsigned Op2,
    1875             :                                     bool Op2IsKill) {
    1876          58 :   const MCInstrDesc &II = TII.get(MachineInstOpcode);
    1877             : 
    1878          58 :   unsigned ResultReg = createResultReg(RC);
    1879         116 :   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
    1880         116 :   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
    1881         116 :   Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
    1882             : 
    1883          58 :   if (II.getNumDefs() >= 1)
    1884         116 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
    1885          58 :         .addReg(Op0, getKillRegState(Op0IsKill))
    1886          58 :         .addReg(Op1, getKillRegState(Op1IsKill))
    1887          58 :         .addReg(Op2, getKillRegState(Op2IsKill));
    1888             :   else {
    1889           0 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
    1890           0 :         .addReg(Op0, getKillRegState(Op0IsKill))
    1891           0 :         .addReg(Op1, getKillRegState(Op1IsKill))
    1892           0 :         .addReg(Op2, getKillRegState(Op2IsKill));
    1893           0 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
    1894           0 :             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
    1895             :   }
    1896          58 :   return ResultReg;
    1897             : }
    1898             : 
    1899         956 : unsigned FastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
    1900             :                                    const TargetRegisterClass *RC, unsigned Op0,
    1901             :                                    bool Op0IsKill, uint64_t Imm) {
    1902         956 :   const MCInstrDesc &II = TII.get(MachineInstOpcode);
    1903             : 
    1904         956 :   unsigned ResultReg = createResultReg(RC);
    1905        1912 :   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
    1906             : 
    1907         956 :   if (II.getNumDefs() >= 1)
    1908        1912 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
    1909         956 :         .addReg(Op0, getKillRegState(Op0IsKill))
    1910         956 :         .addImm(Imm);
    1911             :   else {
    1912           0 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
    1913           0 :         .addReg(Op0, getKillRegState(Op0IsKill))
    1914           0 :         .addImm(Imm);
    1915           0 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
    1916           0 :             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
    1917             :   }
    1918         956 :   return ResultReg;
    1919             : }
    1920             : 
    1921         361 : unsigned FastISel::fastEmitInst_rii(unsigned MachineInstOpcode,
    1922             :                                     const TargetRegisterClass *RC, unsigned Op0,
    1923             :                                     bool Op0IsKill, uint64_t Imm1,
    1924             :                                     uint64_t Imm2) {
    1925         361 :   const MCInstrDesc &II = TII.get(MachineInstOpcode);
    1926             : 
    1927         361 :   unsigned ResultReg = createResultReg(RC);
    1928         722 :   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
    1929             : 
    1930         361 :   if (II.getNumDefs() >= 1)
    1931         722 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
    1932         361 :         .addReg(Op0, getKillRegState(Op0IsKill))
    1933         361 :         .addImm(Imm1)
    1934         361 :         .addImm(Imm2);
    1935             :   else {
    1936           0 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
    1937           0 :         .addReg(Op0, getKillRegState(Op0IsKill))
    1938           0 :         .addImm(Imm1)
    1939           0 :         .addImm(Imm2);
    1940           0 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
    1941           0 :             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
    1942             :   }
    1943         361 :   return ResultReg;
    1944             : }
    1945             : 
    1946           0 : unsigned FastISel::fastEmitInst_f(unsigned MachineInstOpcode,
    1947             :                                   const TargetRegisterClass *RC,
    1948             :                                   const ConstantFP *FPImm) {
    1949           0 :   const MCInstrDesc &II = TII.get(MachineInstOpcode);
    1950             : 
    1951           0 :   unsigned ResultReg = createResultReg(RC);
    1952             : 
    1953           0 :   if (II.getNumDefs() >= 1)
    1954           0 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
    1955             :         .addFPImm(FPImm);
    1956             :   else {
    1957           0 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
    1958             :         .addFPImm(FPImm);
    1959           0 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
    1960           0 :             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
    1961             :   }
    1962           0 :   return ResultReg;
    1963             : }
    1964             : 
    1965         230 : unsigned FastISel::fastEmitInst_rri(unsigned MachineInstOpcode,
    1966             :                                     const TargetRegisterClass *RC, unsigned Op0,
    1967             :                                     bool Op0IsKill, unsigned Op1,
    1968             :                                     bool Op1IsKill, uint64_t Imm) {
    1969         230 :   const MCInstrDesc &II = TII.get(MachineInstOpcode);
    1970             : 
    1971         230 :   unsigned ResultReg = createResultReg(RC);
    1972         460 :   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
    1973         460 :   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
    1974             : 
    1975         230 :   if (II.getNumDefs() >= 1)
    1976         460 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
    1977         230 :         .addReg(Op0, getKillRegState(Op0IsKill))
    1978         230 :         .addReg(Op1, getKillRegState(Op1IsKill))
    1979         230 :         .addImm(Imm);
    1980             :   else {
    1981           0 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
    1982           0 :         .addReg(Op0, getKillRegState(Op0IsKill))
    1983           0 :         .addReg(Op1, getKillRegState(Op1IsKill))
    1984           0 :         .addImm(Imm);
    1985           0 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
    1986           0 :             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
    1987             :   }
    1988         230 :   return ResultReg;
    1989             : }
    1990             : 
    1991         592 : unsigned FastISel::fastEmitInst_i(unsigned MachineInstOpcode,
    1992             :                                   const TargetRegisterClass *RC, uint64_t Imm) {
    1993         592 :   unsigned ResultReg = createResultReg(RC);
    1994         592 :   const MCInstrDesc &II = TII.get(MachineInstOpcode);
    1995             : 
    1996         592 :   if (II.getNumDefs() >= 1)
    1997        1184 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
    1998         592 :         .addImm(Imm);
    1999             :   else {
    2000           0 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm);
    2001           0 :     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
    2002           0 :             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
    2003             :   }
    2004         592 :   return ResultReg;
    2005             : }
    2006             : 
    2007         169 : unsigned FastISel::fastEmitInst_extractsubreg(MVT RetVT, unsigned Op0,
    2008             :                                               bool Op0IsKill, uint32_t Idx) {
    2009         169 :   unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
    2010             :   assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
    2011             :          "Cannot yet extract from physregs");
    2012         169 :   const TargetRegisterClass *RC = MRI.getRegClass(Op0);
    2013         169 :   MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
    2014         507 :   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
    2015         507 :           ResultReg).addReg(Op0, getKillRegState(Op0IsKill), Idx);
    2016         169 :   return ResultReg;
    2017             : }
    2018             : 
    2019             : /// Emit MachineInstrs to compute the value of Op with all but the least
    2020             : /// significant bit set to zero.
    2021         325 : unsigned FastISel::fastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
    2022         325 :   return fastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
    2023             : }
    2024             : 
    2025             : /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
    2026             : /// Emit code to ensure constants are copied into registers when needed.
    2027             : /// Remember the virtual registers that need to be added to the Machine PHI
    2028             : /// nodes as input.  We cannot just directly add them, because expansion
    2029             : /// might result in multiple MBB's for one BB.  As such, the start of the
    2030             : /// BB might correspond to a different MBB than the end.
    2031       10592 : bool FastISel::handlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
    2032       10592 :   const TerminatorInst *TI = LLVMBB->getTerminator();
    2033             : 
    2034             :   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
    2035       21184 :   FuncInfo.OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
    2036             : 
    2037             :   // Check successor nodes' PHI nodes that expect a constant to be available
    2038             :   // from this block.
    2039       13459 :   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
    2040        2925 :     const BasicBlock *SuccBB = TI->getSuccessor(succ);
    2041        2925 :     if (!isa<PHINode>(SuccBB->begin()))
    2042        5219 :       continue;
    2043         632 :     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
    2044             : 
    2045             :     // If this terminator has multiple identical successors (common for
    2046             :     // switches), only handle each succ once.
    2047         316 :     if (!SuccsHandled.insert(SuccMBB).second)
    2048           1 :       continue;
    2049             : 
    2050         315 :     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
    2051             : 
    2052             :     // At this point we know that there is a 1-1 correspondence between LLVM PHI
    2053             :     // nodes and Machine PHI nodes, but the incoming operands have not been
    2054             :     // emitted yet.
    2055         902 :     for (const PHINode &PN : SuccBB->phis()) {
    2056             :       // Ignore dead phi's.
    2057         330 :       if (PN.use_empty())
    2058           8 :         continue;
    2059             : 
    2060             :       // Only handle legal types. Two interesting things to note here. First,
    2061             :       // by bailing out early, we may leave behind some dead instructions,
    2062             :       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
    2063             :       // own moves. Second, this check is necessary because FastISel doesn't
    2064             :       // use CreateRegs to create registers, so it always creates
    2065             :       // exactly one register for each non-void instruction.
    2066         322 :       EVT VT = TLI.getValueType(DL, PN.getType(), /*AllowUnknown=*/true);
    2067         322 :       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
    2068             :         // Handle integer promotions, though, because they're common and easy.
    2069             :         if (!(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)) {
    2070          57 :           FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
    2071          57 :           return false;
    2072             :         }
    2073             :       }
    2074             : 
    2075         265 :       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
    2076             : 
    2077             :       // Set the DebugLoc for the copy. Prefer the location of the operand
    2078             :       // if there is one; use the location of the PHI otherwise.
    2079             :       DbgLoc = PN.getDebugLoc();
    2080             :       if (const auto *Inst = dyn_cast<Instruction>(PHIOp))
    2081             :         DbgLoc = Inst->getDebugLoc();
    2082             : 
    2083         265 :       unsigned Reg = getRegForValue(PHIOp);
    2084         265 :       if (!Reg) {
    2085           1 :         FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
    2086           1 :         return false;
    2087             :       }
    2088         792 :       FuncInfo.PHINodesToUpdate.push_back(std::make_pair(&*MBBI++, Reg));
    2089         528 :       DbgLoc = DebugLoc();
    2090             :     }
    2091             :   }
    2092             : 
    2093             :   return true;
    2094             : }
    2095             : 
    2096        2131 : bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) {
    2097             :   assert(LI->hasOneUse() &&
    2098             :          "tryToFoldLoad expected a LoadInst with a single use");
    2099             :   // We know that the load has a single use, but don't know what it is.  If it
    2100             :   // isn't one of the folded instructions, then we can't succeed here.  Handle
    2101             :   // this by scanning the single-use users of the load until we get to FoldInst.
    2102             :   unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs.
    2103             : 
    2104             :   const Instruction *TheUser = LI->user_back();
    2105        1681 :   while (TheUser != FoldInst && // Scan up until we find FoldInst.
    2106             :          // Stay in the right block.
    2107        3724 :          TheUser->getParent() == FoldInst->getParent() &&
    2108             :          --MaxUsers) { // Don't scan too far.
    2109             :     // If there are multiple or no uses of this instruction, then bail out.
    2110         595 :     if (!TheUser->hasOneUse())
    2111             :       return false;
    2112             : 
    2113             :     TheUser = TheUser->user_back();
    2114             :   }
    2115             : 
    2116             :   // If we didn't find the fold instruction, then we failed to collapse the
    2117             :   // sequence.
    2118        1711 :   if (TheUser != FoldInst)
    2119             :     return false;
    2120             : 
    2121             :   // Don't try to fold volatile loads.  Target has to deal with alignment
    2122             :   // constraints.
    2123        1618 :   if (LI->isVolatile())
    2124             :     return false;
    2125             : 
    2126             :   // Figure out which vreg this is going into.  If there is no assigned vreg yet
    2127             :   // then there actually was no reference to it.  Perhaps the load is referenced
    2128             :   // by a dead instruction.
    2129        1563 :   unsigned LoadReg = getRegForValue(LI);
    2130        1563 :   if (!LoadReg)
    2131             :     return false;
    2132             : 
    2133             :   // We can't fold if this vreg has no uses or more than one use.  Multiple uses
    2134             :   // may mean that the instruction got lowered to multiple MIs, or the use of
    2135             :   // the loaded value ended up being multiple operands of the result.
    2136        1563 :   if (!MRI.hasOneUse(LoadReg))
    2137             :     return false;
    2138             : 
    2139        1517 :   MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg);
    2140        1517 :   MachineInstr *User = RI->getParent();
    2141             : 
    2142             :   // Set the insertion point properly.  Folding the load can cause generation of
    2143             :   // other random instructions (like sign extends) for addressing modes; make
    2144             :   // sure they get inserted in a logical place before the new instruction.
    2145        1517 :   FuncInfo.InsertPt = User;
    2146        1517 :   FuncInfo.MBB = User->getParent();
    2147             : 
    2148             :   // Ask the target to try folding the load.
    2149        3034 :   return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI);
    2150             : }
    2151             : 
    2152          78 : bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) {
    2153             :   // Must be an add.
    2154             :   if (!isa<AddOperator>(Add))
    2155             :     return false;
    2156             :   // Type size needs to match.
    2157          20 :   if (DL.getTypeSizeInBits(GEP->getType()) !=
    2158          10 :       DL.getTypeSizeInBits(Add->getType()))
    2159             :     return false;
    2160             :   // Must be in the same basic block.
    2161          10 :   if (isa<Instruction>(Add) &&
    2162          15 :       FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB)
    2163             :     return false;
    2164             :   // Must have a constant operand.
    2165           4 :   return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1));
    2166             : }
    2167             : 
    2168             : MachineMemOperand *
    2169        3330 : FastISel::createMachineMemOperandFor(const Instruction *I) const {
    2170             :   const Value *Ptr;
    2171             :   Type *ValTy;
    2172             :   unsigned Alignment;
    2173             :   MachineMemOperand::Flags Flags;
    2174             :   bool IsVolatile;
    2175             : 
    2176             :   if (const auto *LI = dyn_cast<LoadInst>(I)) {
    2177             :     Alignment = LI->getAlignment();
    2178             :     IsVolatile = LI->isVolatile();
    2179             :     Flags = MachineMemOperand::MOLoad;
    2180             :     Ptr = LI->getPointerOperand();
    2181        1590 :     ValTy = LI->getType();
    2182             :   } else if (const auto *SI = dyn_cast<StoreInst>(I)) {
    2183             :     Alignment = SI->getAlignment();
    2184             :     IsVolatile = SI->isVolatile();
    2185             :     Flags = MachineMemOperand::MOStore;
    2186             :     Ptr = SI->getPointerOperand();
    2187        1740 :     ValTy = SI->getValueOperand()->getType();
    2188             :   } else
    2189             :     return nullptr;
    2190             : 
    2191             :   bool IsNonTemporal = I->getMetadata(LLVMContext::MD_nontemporal) != nullptr;
    2192             :   bool IsInvariant = I->getMetadata(LLVMContext::MD_invariant_load) != nullptr;
    2193             :   bool IsDereferenceable =
    2194             :       I->getMetadata(LLVMContext::MD_dereferenceable) != nullptr;
    2195             :   const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range);
    2196             : 
    2197             :   AAMDNodes AAInfo;
    2198        3330 :   I->getAAMetadata(AAInfo);
    2199             : 
    2200        3330 :   if (Alignment == 0) // Ensure that codegen never sees alignment 0.
    2201        1006 :     Alignment = DL.getABITypeAlignment(ValTy);
    2202             : 
    2203        3330 :   unsigned Size = DL.getTypeStoreSize(ValTy);
    2204             : 
    2205        3330 :   if (IsVolatile)
    2206             :     Flags |= MachineMemOperand::MOVolatile;
    2207        3330 :   if (IsNonTemporal)
    2208             :     Flags |= MachineMemOperand::MONonTemporal;
    2209        3330 :   if (IsDereferenceable)
    2210             :     Flags |= MachineMemOperand::MODereferenceable;
    2211        3330 :   if (IsInvariant)
    2212             :     Flags |= MachineMemOperand::MOInvariant;
    2213             : 
    2214        6660 :   return FuncInfo.MF->getMachineMemOperand(MachinePointerInfo(Ptr), Flags, Size,
    2215        3330 :                                            Alignment, AAInfo, Ranges);
    2216             : }
    2217             : 
    2218        1149 : CmpInst::Predicate FastISel::optimizeCmpPredicate(const CmpInst *CI) const {
    2219             :   // If both operands are the same, then try to optimize or fold the cmp.
    2220             :   CmpInst::Predicate Predicate = CI->getPredicate();
    2221        1149 :   if (CI->getOperand(0) != CI->getOperand(1))
    2222             :     return Predicate;
    2223             : 
    2224         101 :   switch (Predicate) {
    2225           0 :   default: llvm_unreachable("Invalid predicate!");
    2226             :   case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
    2227           4 :   case CmpInst::FCMP_OEQ:   Predicate = CmpInst::FCMP_ORD;   break;
    2228             :   case CmpInst::FCMP_OGT:   Predicate = CmpInst::FCMP_FALSE; break;
    2229           4 :   case CmpInst::FCMP_OGE:   Predicate = CmpInst::FCMP_ORD;   break;
    2230             :   case CmpInst::FCMP_OLT:   Predicate = CmpInst::FCMP_FALSE; break;
    2231           4 :   case CmpInst::FCMP_OLE:   Predicate = CmpInst::FCMP_ORD;   break;
    2232             :   case CmpInst::FCMP_ONE:   Predicate = CmpInst::FCMP_FALSE; break;
    2233           4 :   case CmpInst::FCMP_ORD:   Predicate = CmpInst::FCMP_ORD;   break;
    2234           4 :   case CmpInst::FCMP_UNO:   Predicate = CmpInst::FCMP_UNO;   break;
    2235           6 :   case CmpInst::FCMP_UEQ:   Predicate = CmpInst::FCMP_TRUE;  break;
    2236           4 :   case CmpInst::FCMP_UGT:   Predicate = CmpInst::FCMP_UNO;   break;
    2237           4 :   case CmpInst::FCMP_UGE:   Predicate = CmpInst::FCMP_TRUE;  break;
    2238           4 :   case CmpInst::FCMP_ULT:   Predicate = CmpInst::FCMP_UNO;   break;
    2239           4 :   case CmpInst::FCMP_ULE:   Predicate = CmpInst::FCMP_TRUE;  break;
    2240           4 :   case CmpInst::FCMP_UNE:   Predicate = CmpInst::FCMP_UNO;   break;
    2241           0 :   case CmpInst::FCMP_TRUE:  Predicate = CmpInst::FCMP_TRUE;  break;
    2242             : 
    2243           4 :   case CmpInst::ICMP_EQ:    Predicate = CmpInst::FCMP_TRUE;  break;
    2244             :   case CmpInst::ICMP_NE:    Predicate = CmpInst::FCMP_FALSE; break;
    2245             :   case CmpInst::ICMP_UGT:   Predicate = CmpInst::FCMP_FALSE; break;
    2246           4 :   case CmpInst::ICMP_UGE:   Predicate = CmpInst::FCMP_TRUE;  break;
    2247             :   case CmpInst::ICMP_ULT:   Predicate = CmpInst::FCMP_FALSE; break;
    2248           4 :   case CmpInst::ICMP_ULE:   Predicate = CmpInst::FCMP_TRUE;  break;
    2249             :   case CmpInst::ICMP_SGT:   Predicate = CmpInst::FCMP_FALSE; break;
    2250           4 :   case CmpInst::ICMP_SGE:   Predicate = CmpInst::FCMP_TRUE;  break;
    2251             :   case CmpInst::ICMP_SLT:   Predicate = CmpInst::FCMP_FALSE; break;
    2252           4 :   case CmpInst::ICMP_SLE:   Predicate = CmpInst::FCMP_TRUE;  break;
    2253             :   }
    2254             : 
    2255             :   return Predicate;
    2256             : }

Generated by: LCOV version 1.13