LLVM API Documentation

FastISel.cpp
Go to the documentation of this file.
00001 //===-- FastISel.cpp - Implementation of the FastISel class ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the implementation of the FastISel class.
00011 //
00012 // "Fast" instruction selection is designed to emit very poor code quickly.
00013 // Also, it is not designed to be able to do much lowering, so most illegal
00014 // types (e.g. i64 on 32-bit targets) and operations are not supported.  It is
00015 // also not intended to be able to do much optimization, except in a few cases
00016 // where doing optimizations reduces overall compile time.  For example, folding
00017 // constants into immediate fields is often done, because it's cheap and it
00018 // reduces the number of instructions later phases have to examine.
00019 //
00020 // "Fast" instruction selection is able to fail gracefully and transfer
00021 // control to the SelectionDAG selector for operations that it doesn't
00022 // support.  In many cases, this allows us to avoid duplicating a lot of
00023 // the complicated lowering logic that SelectionDAG currently has.
00024 //
00025 // The intended use for "fast" instruction selection is "-O0" mode
00026 // compilation, where the quality of the generated code is irrelevant when
00027 // weighed against the speed at which the code can be generated.  Also,
00028 // at -O0, the LLVM optimizers are not running, and this makes the
00029 // compile time of codegen a much higher portion of the overall compile
00030 // time.  Despite its limitations, "fast" instruction selection is able to
00031 // handle enough code on its own to provide noticeable overall speedups
00032 // in -O0 compiles.
00033 //
00034 // Basic operations are supported in a target-independent way, by reading
00035 // the same instruction descriptions that the SelectionDAG selector reads,
00036 // and identifying simple arithmetic operations that can be directly selected
00037 // from simple operators.  More complicated operations currently require
00038 // target-specific code.
00039 //
00040 //===----------------------------------------------------------------------===//
00041 
00042 #define DEBUG_TYPE "isel"
00043 #include "llvm/CodeGen/FastISel.h"
00044 #include "llvm/ADT/Optional.h"
00045 #include "llvm/ADT/Statistic.h"
00046 #include "llvm/Analysis/Loads.h"
00047 #include "llvm/CodeGen/Analysis.h"
00048 #include "llvm/CodeGen/FunctionLoweringInfo.h"
00049 #include "llvm/CodeGen/MachineInstrBuilder.h"
00050 #include "llvm/CodeGen/MachineModuleInfo.h"
00051 #include "llvm/CodeGen/MachineRegisterInfo.h"
00052 #include "llvm/IR/DataLayout.h"
00053 #include "llvm/IR/DebugInfo.h"
00054 #include "llvm/IR/Function.h"
00055 #include "llvm/IR/GlobalVariable.h"
00056 #include "llvm/IR/Instructions.h"
00057 #include "llvm/IR/IntrinsicInst.h"
00058 #include "llvm/IR/Operator.h"
00059 #include "llvm/Support/Debug.h"
00060 #include "llvm/Support/ErrorHandling.h"
00061 #include "llvm/Target/TargetInstrInfo.h"
00062 #include "llvm/Target/TargetLibraryInfo.h"
00063 #include "llvm/Target/TargetLowering.h"
00064 #include "llvm/Target/TargetMachine.h"
00065 using namespace llvm;
00066 
00067 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
00068           "target-independent selector");
00069 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
00070           "target-specific selector");
00071 STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
00072 
00073 /// startNewBlock - Set the current block to which generated machine
00074 /// instructions will be appended, and clear the local CSE map.
00075 ///
00076 void FastISel::startNewBlock() {
00077   LocalValueMap.clear();
00078 
00079   // Instructions are appended to FuncInfo.MBB. If the basic block already
00080   // contains labels or copies, use the last instruction as the last local
00081   // value.
00082   EmitStartPt = nullptr;
00083   if (!FuncInfo.MBB->empty())
00084     EmitStartPt = &FuncInfo.MBB->back();
00085   LastLocalValue = EmitStartPt;
00086 }
00087 
00088 bool FastISel::LowerArguments() {
00089   if (!FuncInfo.CanLowerReturn)
00090     // Fallback to SDISel argument lowering code to deal with sret pointer
00091     // parameter.
00092     return false;
00093 
00094   if (!FastLowerArguments())
00095     return false;
00096 
00097   // Enter arguments into ValueMap for uses in non-entry BBs.
00098   for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
00099          E = FuncInfo.Fn->arg_end(); I != E; ++I) {
00100     DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(I);
00101     assert(VI != LocalValueMap.end() && "Missed an argument?");
00102     FuncInfo.ValueMap[I] = VI->second;
00103   }
00104   return true;
00105 }
00106 
00107 void FastISel::flushLocalValueMap() {
00108   LocalValueMap.clear();
00109   LastLocalValue = EmitStartPt;
00110   recomputeInsertPt();
00111 }
00112 
00113 bool FastISel::hasTrivialKill(const Value *V) const {
00114   // Don't consider constants or arguments to have trivial kills.
00115   const Instruction *I = dyn_cast<Instruction>(V);
00116   if (!I)
00117     return false;
00118 
00119   // No-op casts are trivially coalesced by fast-isel.
00120   if (const CastInst *Cast = dyn_cast<CastInst>(I))
00121     if (Cast->isNoopCast(DL.getIntPtrType(Cast->getContext())) &&
00122         !hasTrivialKill(Cast->getOperand(0)))
00123       return false;
00124 
00125   // GEPs with all zero indices are trivially coalesced by fast-isel.
00126   if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
00127     if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
00128       return false;
00129 
00130   // Only instructions with a single use in the same basic block are considered
00131   // to have trivial kills.
00132   return I->hasOneUse() &&
00133          !(I->getOpcode() == Instruction::BitCast ||
00134            I->getOpcode() == Instruction::PtrToInt ||
00135            I->getOpcode() == Instruction::IntToPtr) &&
00136          cast<Instruction>(*I->user_begin())->getParent() == I->getParent();
00137 }
00138 
00139 unsigned FastISel::getRegForValue(const Value *V) {
00140   EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true);
00141   // Don't handle non-simple values in FastISel.
00142   if (!RealVT.isSimple())
00143     return 0;
00144 
00145   // Ignore illegal types. We must do this before looking up the value
00146   // in ValueMap because Arguments are given virtual registers regardless
00147   // of whether FastISel can handle them.
00148   MVT VT = RealVT.getSimpleVT();
00149   if (!TLI.isTypeLegal(VT)) {
00150     // Handle integer promotions, though, because they're common and easy.
00151     if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
00152       VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
00153     else
00154       return 0;
00155   }
00156 
00157   // Look up the value to see if we already have a register for it.
00158   unsigned Reg = lookUpRegForValue(V);
00159   if (Reg != 0)
00160     return Reg;
00161 
00162   // In bottom-up mode, just create the virtual register which will be used
00163   // to hold the value. It will be materialized later.
00164   if (isa<Instruction>(V) &&
00165       (!isa<AllocaInst>(V) ||
00166        !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
00167     return FuncInfo.InitializeRegForValue(V);
00168 
00169   SavePoint SaveInsertPt = enterLocalValueArea();
00170 
00171   // Materialize the value in a register. Emit any instructions in the
00172   // local value area.
00173   Reg = materializeRegForValue(V, VT);
00174 
00175   leaveLocalValueArea(SaveInsertPt);
00176 
00177   return Reg;
00178 }
00179 
00180 /// materializeRegForValue - Helper for getRegForValue. This function is
00181 /// called when the value isn't already available in a register and must
00182 /// be materialized with new instructions.
00183 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
00184   unsigned Reg = 0;
00185 
00186   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00187     if (CI->getValue().getActiveBits() <= 64)
00188       Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
00189   } else if (isa<AllocaInst>(V)) {
00190     Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
00191   } else if (isa<ConstantPointerNull>(V)) {
00192     // Translate this as an integer zero so that it can be
00193     // local-CSE'd with actual integer zeros.
00194     Reg =
00195       getRegForValue(Constant::getNullValue(DL.getIntPtrType(V->getContext())));
00196   } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
00197     if (CF->isNullValue()) {
00198       Reg = TargetMaterializeFloatZero(CF);
00199     } else {
00200       // Try to emit the constant directly.
00201       Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
00202     }
00203 
00204     if (!Reg) {
00205       // Try to emit the constant by using an integer constant with a cast.
00206       const APFloat &Flt = CF->getValueAPF();
00207       EVT IntVT = TLI.getPointerTy();
00208 
00209       uint64_t x[2];
00210       uint32_t IntBitWidth = IntVT.getSizeInBits();
00211       bool isExact;
00212       (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
00213                                   APFloat::rmTowardZero, &isExact);
00214       if (isExact) {
00215         APInt IntVal(IntBitWidth, x);
00216 
00217         unsigned IntegerReg =
00218           getRegForValue(ConstantInt::get(V->getContext(), IntVal));
00219         if (IntegerReg != 0)
00220           Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP,
00221                            IntegerReg, /*Kill=*/false);
00222       }
00223     }
00224   } else if (const Operator *Op = dyn_cast<Operator>(V)) {
00225     if (!SelectOperator(Op, Op->getOpcode()))
00226       if (!isa<Instruction>(Op) ||
00227           !TargetSelectInstruction(cast<Instruction>(Op)))
00228         return 0;
00229     Reg = lookUpRegForValue(Op);
00230   } else if (isa<UndefValue>(V)) {
00231     Reg = createResultReg(TLI.getRegClassFor(VT));
00232     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
00233             TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
00234   }
00235 
00236   // If target-independent code couldn't handle the value, give target-specific
00237   // code a try.
00238   if (!Reg && isa<Constant>(V))
00239     Reg = TargetMaterializeConstant(cast<Constant>(V));
00240 
00241   // Don't cache constant materializations in the general ValueMap.
00242   // To do so would require tracking what uses they dominate.
00243   if (Reg != 0) {
00244     LocalValueMap[V] = Reg;
00245     LastLocalValue = MRI.getVRegDef(Reg);
00246   }
00247   return Reg;
00248 }
00249 
00250 unsigned FastISel::lookUpRegForValue(const Value *V) {
00251   // Look up the value to see if we already have a register for it. We
00252   // cache values defined by Instructions across blocks, and other values
00253   // only locally. This is because Instructions already have the SSA
00254   // def-dominates-use requirement enforced.
00255   DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
00256   if (I != FuncInfo.ValueMap.end())
00257     return I->second;
00258   return LocalValueMap[V];
00259 }
00260 
00261 /// UpdateValueMap - Update the value map to include the new mapping for this
00262 /// instruction, or insert an extra copy to get the result in a previous
00263 /// determined register.
00264 /// NOTE: This is only necessary because we might select a block that uses
00265 /// a value before we select the block that defines the value.  It might be
00266 /// possible to fix this by selecting blocks in reverse postorder.
00267 void FastISel::UpdateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
00268   if (!isa<Instruction>(I)) {
00269     LocalValueMap[I] = Reg;
00270     return;
00271   }
00272 
00273   unsigned &AssignedReg = FuncInfo.ValueMap[I];
00274   if (AssignedReg == 0)
00275     // Use the new register.
00276     AssignedReg = Reg;
00277   else if (Reg != AssignedReg) {
00278     // Arrange for uses of AssignedReg to be replaced by uses of Reg.
00279     for (unsigned i = 0; i < NumRegs; i++)
00280       FuncInfo.RegFixups[AssignedReg+i] = Reg+i;
00281 
00282     AssignedReg = Reg;
00283   }
00284 }
00285 
00286 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
00287   unsigned IdxN = getRegForValue(Idx);
00288   if (IdxN == 0)
00289     // Unhandled operand. Halt "fast" selection and bail.
00290     return std::pair<unsigned, bool>(0, false);
00291 
00292   bool IdxNIsKill = hasTrivialKill(Idx);
00293 
00294   // If the index is smaller or larger than intptr_t, truncate or extend it.
00295   MVT PtrVT = TLI.getPointerTy();
00296   EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
00297   if (IdxVT.bitsLT(PtrVT)) {
00298     IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND,
00299                       IdxN, IdxNIsKill);
00300     IdxNIsKill = true;
00301   }
00302   else if (IdxVT.bitsGT(PtrVT)) {
00303     IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE,
00304                       IdxN, IdxNIsKill);
00305     IdxNIsKill = true;
00306   }
00307   return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
00308 }
00309 
00310 void FastISel::recomputeInsertPt() {
00311   if (getLastLocalValue()) {
00312     FuncInfo.InsertPt = getLastLocalValue();
00313     FuncInfo.MBB = FuncInfo.InsertPt->getParent();
00314     ++FuncInfo.InsertPt;
00315   } else
00316     FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
00317 
00318   // Now skip past any EH_LABELs, which must remain at the beginning.
00319   while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
00320          FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
00321     ++FuncInfo.InsertPt;
00322 }
00323 
00324 void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
00325                               MachineBasicBlock::iterator E) {
00326   assert (I && E && std::distance(I, E) > 0 && "Invalid iterator!");
00327   while (I != E) {
00328     MachineInstr *Dead = &*I;
00329     ++I;
00330     Dead->eraseFromParent();
00331     ++NumFastIselDead;
00332   }
00333   recomputeInsertPt();
00334 }
00335 
00336 FastISel::SavePoint FastISel::enterLocalValueArea() {
00337   MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
00338   DebugLoc OldDL = DbgLoc;
00339   recomputeInsertPt();
00340   DbgLoc = DebugLoc();
00341   SavePoint SP = { OldInsertPt, OldDL };
00342   return SP;
00343 }
00344 
00345 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
00346   if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
00347     LastLocalValue = std::prev(FuncInfo.InsertPt);
00348 
00349   // Restore the previous insert position.
00350   FuncInfo.InsertPt = OldInsertPt.InsertPt;
00351   DbgLoc = OldInsertPt.DL;
00352 }
00353 
00354 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
00355 /// which has an opcode which directly corresponds to the given ISD opcode.
00356 ///
00357 bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) {
00358   EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
00359   if (VT == MVT::Other || !VT.isSimple())
00360     // Unhandled type. Halt "fast" selection and bail.
00361     return false;
00362 
00363   // We only handle legal types. For example, on x86-32 the instruction
00364   // selector contains all of the 64-bit instructions from x86-64,
00365   // under the assumption that i64 won't be used if the target doesn't
00366   // support it.
00367   if (!TLI.isTypeLegal(VT)) {
00368     // MVT::i1 is special. Allow AND, OR, or XOR because they
00369     // don't require additional zeroing, which makes them easy.
00370     if (VT == MVT::i1 &&
00371         (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
00372          ISDOpcode == ISD::XOR))
00373       VT = TLI.getTypeToTransformTo(I->getContext(), VT);
00374     else
00375       return false;
00376   }
00377 
00378   // Check if the first operand is a constant, and handle it as "ri".  At -O0,
00379   // we don't have anything that canonicalizes operand order.
00380   if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
00381     if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
00382       unsigned Op1 = getRegForValue(I->getOperand(1));
00383       if (Op1 == 0) return false;
00384 
00385       bool Op1IsKill = hasTrivialKill(I->getOperand(1));
00386 
00387       unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1,
00388                                         Op1IsKill, CI->getZExtValue(),
00389                                         VT.getSimpleVT());
00390       if (ResultReg == 0) return false;
00391 
00392       // We successfully emitted code for the given LLVM Instruction.
00393       UpdateValueMap(I, ResultReg);
00394       return true;
00395     }
00396 
00397 
00398   unsigned Op0 = getRegForValue(I->getOperand(0));
00399   if (Op0 == 0)   // Unhandled operand. Halt "fast" selection and bail.
00400     return false;
00401 
00402   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
00403 
00404   // Check if the second operand is a constant and handle it appropriately.
00405   if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
00406     uint64_t Imm = CI->getZExtValue();
00407 
00408     // Transform "sdiv exact X, 8" -> "sra X, 3".
00409     if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
00410         cast<BinaryOperator>(I)->isExact() &&
00411         isPowerOf2_64(Imm)) {
00412       Imm = Log2_64(Imm);
00413       ISDOpcode = ISD::SRA;
00414     }
00415 
00416     // Transform "urem x, pow2" -> "and x, pow2-1".
00417     if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
00418         isPowerOf2_64(Imm)) {
00419       --Imm;
00420       ISDOpcode = ISD::AND;
00421     }
00422 
00423     unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
00424                                       Op0IsKill, Imm, VT.getSimpleVT());
00425     if (ResultReg == 0) return false;
00426 
00427     // We successfully emitted code for the given LLVM Instruction.
00428     UpdateValueMap(I, ResultReg);
00429     return true;
00430   }
00431 
00432   // Check if the second operand is a constant float.
00433   if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
00434     unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
00435                                      ISDOpcode, Op0, Op0IsKill, CF);
00436     if (ResultReg != 0) {
00437       // We successfully emitted code for the given LLVM Instruction.
00438       UpdateValueMap(I, ResultReg);
00439       return true;
00440     }
00441   }
00442 
00443   unsigned Op1 = getRegForValue(I->getOperand(1));
00444   if (Op1 == 0)
00445     // Unhandled operand. Halt "fast" selection and bail.
00446     return false;
00447 
00448   bool Op1IsKill = hasTrivialKill(I->getOperand(1));
00449 
00450   // Now we have both operands in registers. Emit the instruction.
00451   unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
00452                                    ISDOpcode,
00453                                    Op0, Op0IsKill,
00454                                    Op1, Op1IsKill);
00455   if (ResultReg == 0)
00456     // Target-specific code wasn't able to find a machine opcode for
00457     // the given ISD opcode and type. Halt "fast" selection and bail.
00458     return false;
00459 
00460   // We successfully emitted code for the given LLVM Instruction.
00461   UpdateValueMap(I, ResultReg);
00462   return true;
00463 }
00464 
00465 bool FastISel::SelectGetElementPtr(const User *I) {
00466   unsigned N = getRegForValue(I->getOperand(0));
00467   if (N == 0)
00468     // Unhandled operand. Halt "fast" selection and bail.
00469     return false;
00470 
00471   bool NIsKill = hasTrivialKill(I->getOperand(0));
00472 
00473   // Keep a running tab of the total offset to coalesce multiple N = N + Offset
00474   // into a single N = N + TotalOffset.
00475   uint64_t TotalOffs = 0;
00476   // FIXME: What's a good SWAG number for MaxOffs?
00477   uint64_t MaxOffs = 2048;
00478   Type *Ty = I->getOperand(0)->getType();
00479   MVT VT = TLI.getPointerTy();
00480   for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1,
00481        E = I->op_end(); OI != E; ++OI) {
00482     const Value *Idx = *OI;
00483     if (StructType *StTy = dyn_cast<StructType>(Ty)) {
00484       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
00485       if (Field) {
00486         // N = N + Offset
00487         TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
00488         if (TotalOffs >= MaxOffs) {
00489           N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
00490           if (N == 0)
00491             // Unhandled operand. Halt "fast" selection and bail.
00492             return false;
00493           NIsKill = true;
00494           TotalOffs = 0;
00495         }
00496       }
00497       Ty = StTy->getElementType(Field);
00498     } else {
00499       Ty = cast<SequentialType>(Ty)->getElementType();
00500 
00501       // If this is a constant subscript, handle it quickly.
00502       if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
00503         if (CI->isZero()) continue;
00504         // N = N + Offset
00505         TotalOffs +=
00506           DL.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
00507         if (TotalOffs >= MaxOffs) {
00508           N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
00509           if (N == 0)
00510             // Unhandled operand. Halt "fast" selection and bail.
00511             return false;
00512           NIsKill = true;
00513           TotalOffs = 0;
00514         }
00515         continue;
00516       }
00517       if (TotalOffs) {
00518         N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
00519         if (N == 0)
00520           // Unhandled operand. Halt "fast" selection and bail.
00521           return false;
00522         NIsKill = true;
00523         TotalOffs = 0;
00524       }
00525 
00526       // N = N + Idx * ElementSize;
00527       uint64_t ElementSize = DL.getTypeAllocSize(Ty);
00528       std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
00529       unsigned IdxN = Pair.first;
00530       bool IdxNIsKill = Pair.second;
00531       if (IdxN == 0)
00532         // Unhandled operand. Halt "fast" selection and bail.
00533         return false;
00534 
00535       if (ElementSize != 1) {
00536         IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
00537         if (IdxN == 0)
00538           // Unhandled operand. Halt "fast" selection and bail.
00539           return false;
00540         IdxNIsKill = true;
00541       }
00542       N = FastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
00543       if (N == 0)
00544         // Unhandled operand. Halt "fast" selection and bail.
00545         return false;
00546     }
00547   }
00548   if (TotalOffs) {
00549     N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
00550     if (N == 0)
00551       // Unhandled operand. Halt "fast" selection and bail.
00552       return false;
00553   }
00554 
00555   // We successfully emitted code for the given LLVM Instruction.
00556   UpdateValueMap(I, N);
00557   return true;
00558 }
00559 
00560 bool FastISel::SelectCall(const User *I) {
00561   const CallInst *Call = cast<CallInst>(I);
00562 
00563   // Handle simple inline asms.
00564   if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
00565     // Don't attempt to handle constraints.
00566     if (!IA->getConstraintString().empty())
00567       return false;
00568 
00569     unsigned ExtraInfo = 0;
00570     if (IA->hasSideEffects())
00571       ExtraInfo |= InlineAsm::Extra_HasSideEffects;
00572     if (IA->isAlignStack())
00573       ExtraInfo |= InlineAsm::Extra_IsAlignStack;
00574 
00575     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
00576             TII.get(TargetOpcode::INLINEASM))
00577       .addExternalSymbol(IA->getAsmString().c_str())
00578       .addImm(ExtraInfo);
00579     return true;
00580   }
00581 
00582   MachineModuleInfo &MMI = FuncInfo.MF->getMMI();
00583   ComputeUsesVAFloatArgument(*Call, &MMI);
00584 
00585   const Function *F = Call->getCalledFunction();
00586   if (!F) return false;
00587 
00588   // Handle selected intrinsic function calls.
00589   switch (F->getIntrinsicID()) {
00590   default: break;
00591     // At -O0 we don't care about the lifetime intrinsics.
00592   case Intrinsic::lifetime_start:
00593   case Intrinsic::lifetime_end:
00594     // The donothing intrinsic does, well, nothing.
00595   case Intrinsic::donothing:
00596     return true;
00597 
00598   case Intrinsic::dbg_declare: {
00599     const DbgDeclareInst *DI = cast<DbgDeclareInst>(Call);
00600     DIVariable DIVar(DI->getVariable());
00601     assert((!DIVar || DIVar.isVariable()) &&
00602       "Variable in DbgDeclareInst should be either null or a DIVariable.");
00603     if (!DIVar ||
00604         !FuncInfo.MF->getMMI().hasDebugInfo()) {
00605       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
00606       return true;
00607     }
00608 
00609     const Value *Address = DI->getAddress();
00610     if (!Address || isa<UndefValue>(Address)) {
00611       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
00612       return true;
00613     }
00614 
00615     unsigned Offset = 0;
00616     Optional<MachineOperand> Op;
00617     if (const Argument *Arg = dyn_cast<Argument>(Address))
00618       // Some arguments' frame index is recorded during argument lowering.
00619       Offset = FuncInfo.getArgumentFrameIndex(Arg);
00620     if (Offset)
00621         Op = MachineOperand::CreateFI(Offset);
00622     if (!Op)
00623       if (unsigned Reg = lookUpRegForValue(Address))
00624         Op = MachineOperand::CreateReg(Reg, false);
00625 
00626     // If we have a VLA that has a "use" in a metadata node that's then used
00627     // here but it has no other uses, then we have a problem. E.g.,
00628     //
00629     //   int foo (const int *x) {
00630     //     char a[*x];
00631     //     return 0;
00632     //   }
00633     //
00634     // If we assign 'a' a vreg and fast isel later on has to use the selection
00635     // DAG isel, it will want to copy the value to the vreg. However, there are
00636     // no uses, which goes counter to what selection DAG isel expects.
00637     if (!Op && !Address->use_empty() && isa<Instruction>(Address) &&
00638         (!isa<AllocaInst>(Address) ||
00639          !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
00640       Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address),
00641                                      false);
00642 
00643     if (Op) {
00644       if (Op->isReg()) {
00645         Op->setIsDebug(true);
00646         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
00647                 TII.get(TargetOpcode::DBG_VALUE), false, Op->getReg(), 0,
00648                 DI->getVariable());
00649       } else
00650         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
00651                 TII.get(TargetOpcode::DBG_VALUE))
00652             .addOperand(*Op)
00653             .addImm(0)
00654             .addMetadata(DI->getVariable());
00655     } else {
00656       // We can't yet handle anything else here because it would require
00657       // generating code, thus altering codegen because of debug info.
00658       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
00659     }
00660     return true;
00661   }
00662   case Intrinsic::dbg_value: {
00663     // This form of DBG_VALUE is target-independent.
00664     const DbgValueInst *DI = cast<DbgValueInst>(Call);
00665     const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
00666     const Value *V = DI->getValue();
00667     if (!V) {
00668       // Currently the optimizer can produce this; insert an undef to
00669       // help debugging.  Probably the optimizer should not do this.
00670       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
00671         .addReg(0U).addImm(DI->getOffset())
00672         .addMetadata(DI->getVariable());
00673     } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00674       if (CI->getBitWidth() > 64)
00675         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
00676           .addCImm(CI).addImm(DI->getOffset())
00677           .addMetadata(DI->getVariable());
00678       else
00679         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
00680           .addImm(CI->getZExtValue()).addImm(DI->getOffset())
00681           .addMetadata(DI->getVariable());
00682     } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
00683       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
00684         .addFPImm(CF).addImm(DI->getOffset())
00685         .addMetadata(DI->getVariable());
00686     } else if (unsigned Reg = lookUpRegForValue(V)) {
00687       // FIXME: This does not handle register-indirect values at offset 0.
00688       bool IsIndirect = DI->getOffset() != 0;
00689       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, IsIndirect,
00690               Reg, DI->getOffset(), DI->getVariable());
00691     } else {
00692       // We can't yet handle anything else here because it would require
00693       // generating code, thus altering codegen because of debug info.
00694       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
00695     }
00696     return true;
00697   }
00698   case Intrinsic::objectsize: {
00699     ConstantInt *CI = cast<ConstantInt>(Call->getArgOperand(1));
00700     unsigned long long Res = CI->isZero() ? -1ULL : 0;
00701     Constant *ResCI = ConstantInt::get(Call->getType(), Res);
00702     unsigned ResultReg = getRegForValue(ResCI);
00703     if (ResultReg == 0)
00704       return false;
00705     UpdateValueMap(Call, ResultReg);
00706     return true;
00707   }
00708   case Intrinsic::expect: {
00709     unsigned ResultReg = getRegForValue(Call->getArgOperand(0));
00710     if (ResultReg == 0)
00711       return false;
00712     UpdateValueMap(Call, ResultReg);
00713     return true;
00714   }
00715   }
00716 
00717   // Usually, it does not make sense to initialize a value,
00718   // make an unrelated function call and use the value, because
00719   // it tends to be spilled on the stack. So, we move the pointer
00720   // to the last local value to the beginning of the block, so that
00721   // all the values which have already been materialized,
00722   // appear after the call. It also makes sense to skip intrinsics
00723   // since they tend to be inlined.
00724   if (!isa<IntrinsicInst>(Call))
00725     flushLocalValueMap();
00726 
00727   // An arbitrary call. Bail.
00728   return false;
00729 }
00730 
00731 bool FastISel::SelectCast(const User *I, unsigned Opcode) {
00732   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
00733   EVT DstVT = TLI.getValueType(I->getType());
00734 
00735   if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
00736       DstVT == MVT::Other || !DstVT.isSimple())
00737     // Unhandled type. Halt "fast" selection and bail.
00738     return false;
00739 
00740   // Check if the destination type is legal.
00741   if (!TLI.isTypeLegal(DstVT))
00742     return false;
00743 
00744   // Check if the source operand is legal.
00745   if (!TLI.isTypeLegal(SrcVT))
00746     return false;
00747 
00748   unsigned InputReg = getRegForValue(I->getOperand(0));
00749   if (!InputReg)
00750     // Unhandled operand.  Halt "fast" selection and bail.
00751     return false;
00752 
00753   bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
00754 
00755   unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
00756                                   DstVT.getSimpleVT(),
00757                                   Opcode,
00758                                   InputReg, InputRegIsKill);
00759   if (!ResultReg)
00760     return false;
00761 
00762   UpdateValueMap(I, ResultReg);
00763   return true;
00764 }
00765 
00766 bool FastISel::SelectBitCast(const User *I) {
00767   // If the bitcast doesn't change the type, just use the operand value.
00768   if (I->getType() == I->getOperand(0)->getType()) {
00769     unsigned Reg = getRegForValue(I->getOperand(0));
00770     if (Reg == 0)
00771       return false;
00772     UpdateValueMap(I, Reg);
00773     return true;
00774   }
00775 
00776   // Bitcasts of other values become reg-reg copies or BITCAST operators.
00777   EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType());
00778   EVT DstEVT = TLI.getValueType(I->getType());
00779   if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
00780       !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
00781     // Unhandled type. Halt "fast" selection and bail.
00782     return false;
00783 
00784   MVT SrcVT = SrcEVT.getSimpleVT();
00785   MVT DstVT = DstEVT.getSimpleVT();
00786   unsigned Op0 = getRegForValue(I->getOperand(0));
00787   if (Op0 == 0)
00788     // Unhandled operand. Halt "fast" selection and bail.
00789     return false;
00790 
00791   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
00792 
00793   // First, try to perform the bitcast by inserting a reg-reg copy.
00794   unsigned ResultReg = 0;
00795   if (SrcVT == DstVT) {
00796     const TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
00797     const TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
00798     // Don't attempt a cross-class copy. It will likely fail.
00799     if (SrcClass == DstClass) {
00800       ResultReg = createResultReg(DstClass);
00801       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
00802               TII.get(TargetOpcode::COPY), ResultReg).addReg(Op0);
00803     }
00804   }
00805 
00806   // If the reg-reg copy failed, select a BITCAST opcode.
00807   if (!ResultReg)
00808     ResultReg = FastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
00809 
00810   if (!ResultReg)
00811     return false;
00812 
00813   UpdateValueMap(I, ResultReg);
00814   return true;
00815 }
00816 
00817 bool
00818 FastISel::SelectInstruction(const Instruction *I) {
00819   // Just before the terminator instruction, insert instructions to
00820   // feed PHI nodes in successor blocks.
00821   if (isa<TerminatorInst>(I))
00822     if (!HandlePHINodesInSuccessorBlocks(I->getParent()))
00823       return false;
00824 
00825   DbgLoc = I->getDebugLoc();
00826 
00827   MachineBasicBlock::iterator SavedInsertPt = FuncInfo.InsertPt;
00828 
00829   if (const CallInst *Call = dyn_cast<CallInst>(I)) {
00830     const Function *F = Call->getCalledFunction();
00831     LibFunc::Func Func;
00832 
00833     // As a special case, don't handle calls to builtin library functions that
00834     // may be translated directly to target instructions.
00835     if (F && !F->hasLocalLinkage() && F->hasName() &&
00836         LibInfo->getLibFunc(F->getName(), Func) &&
00837         LibInfo->hasOptimizedCodeGen(Func))
00838       return false;
00839 
00840     // Don't handle Intrinsic::trap if a trap funciton is specified.
00841     if (F && F->getIntrinsicID() == Intrinsic::trap &&
00842         !TM.Options.getTrapFunctionName().empty())
00843       return false;
00844   }
00845 
00846   // First, try doing target-independent selection.
00847   if (SelectOperator(I, I->getOpcode())) {
00848     ++NumFastIselSuccessIndependent;
00849     DbgLoc = DebugLoc();
00850     return true;
00851   }
00852   // Remove dead code.  However, ignore call instructions since we've flushed
00853   // the local value map and recomputed the insert point.
00854   if (!isa<CallInst>(I)) {
00855     recomputeInsertPt();
00856     if (SavedInsertPt != FuncInfo.InsertPt)
00857       removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
00858   }
00859 
00860   // Next, try calling the target to attempt to handle the instruction.
00861   SavedInsertPt = FuncInfo.InsertPt;
00862   if (TargetSelectInstruction(I)) {
00863     ++NumFastIselSuccessTarget;
00864     DbgLoc = DebugLoc();
00865     return true;
00866   }
00867   // Check for dead code and remove as necessary.
00868   recomputeInsertPt();
00869   if (SavedInsertPt != FuncInfo.InsertPt)
00870     removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
00871 
00872   DbgLoc = DebugLoc();
00873   return false;
00874 }
00875 
00876 /// FastEmitBranch - Emit an unconditional branch to the given block,
00877 /// unless it is the immediate (fall-through) successor, and update
00878 /// the CFG.
00879 void
00880 FastISel::FastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DbgLoc) {
00881 
00882   if (FuncInfo.MBB->getBasicBlock()->size() > 1 &&
00883       FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
00884     // For more accurate line information if this is the only instruction
00885     // in the block then emit it, otherwise we have the unconditional
00886     // fall-through case, which needs no instructions.
00887   } else {
00888     // The unconditional branch case.
00889     TII.InsertBranch(*FuncInfo.MBB, MSucc, nullptr,
00890                      SmallVector<MachineOperand, 0>(), DbgLoc);
00891   }
00892   FuncInfo.MBB->addSuccessor(MSucc);
00893 }
00894 
00895 /// SelectFNeg - Emit an FNeg operation.
00896 ///
00897 bool
00898 FastISel::SelectFNeg(const User *I) {
00899   unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
00900   if (OpReg == 0) return false;
00901 
00902   bool OpRegIsKill = hasTrivialKill(I);
00903 
00904   // If the target has ISD::FNEG, use it.
00905   EVT VT = TLI.getValueType(I->getType());
00906   unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(),
00907                                   ISD::FNEG, OpReg, OpRegIsKill);
00908   if (ResultReg != 0) {
00909     UpdateValueMap(I, ResultReg);
00910     return true;
00911   }
00912 
00913   // Bitcast the value to integer, twiddle the sign bit with xor,
00914   // and then bitcast it back to floating-point.
00915   if (VT.getSizeInBits() > 64) return false;
00916   EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
00917   if (!TLI.isTypeLegal(IntVT))
00918     return false;
00919 
00920   unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
00921                                ISD::BITCAST, OpReg, OpRegIsKill);
00922   if (IntReg == 0)
00923     return false;
00924 
00925   unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR,
00926                                        IntReg, /*Kill=*/true,
00927                                        UINT64_C(1) << (VT.getSizeInBits()-1),
00928                                        IntVT.getSimpleVT());
00929   if (IntResultReg == 0)
00930     return false;
00931 
00932   ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(),
00933                          ISD::BITCAST, IntResultReg, /*Kill=*/true);
00934   if (ResultReg == 0)
00935     return false;
00936 
00937   UpdateValueMap(I, ResultReg);
00938   return true;
00939 }
00940 
00941 bool
00942 FastISel::SelectExtractValue(const User *U) {
00943   const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
00944   if (!EVI)
00945     return false;
00946 
00947   // Make sure we only try to handle extracts with a legal result.  But also
00948   // allow i1 because it's easy.
00949   EVT RealVT = TLI.getValueType(EVI->getType(), /*AllowUnknown=*/true);
00950   if (!RealVT.isSimple())
00951     return false;
00952   MVT VT = RealVT.getSimpleVT();
00953   if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
00954     return false;
00955 
00956   const Value *Op0 = EVI->getOperand(0);
00957   Type *AggTy = Op0->getType();
00958 
00959   // Get the base result register.
00960   unsigned ResultReg;
00961   DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
00962   if (I != FuncInfo.ValueMap.end())
00963     ResultReg = I->second;
00964   else if (isa<Instruction>(Op0))
00965     ResultReg = FuncInfo.InitializeRegForValue(Op0);
00966   else
00967     return false; // fast-isel can't handle aggregate constants at the moment
00968 
00969   // Get the actual result register, which is an offset from the base register.
00970   unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
00971 
00972   SmallVector<EVT, 4> AggValueVTs;
00973   ComputeValueVTs(TLI, AggTy, AggValueVTs);
00974 
00975   for (unsigned i = 0; i < VTIndex; i++)
00976     ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
00977 
00978   UpdateValueMap(EVI, ResultReg);
00979   return true;
00980 }
00981 
00982 bool
00983 FastISel::SelectOperator(const User *I, unsigned Opcode) {
00984   switch (Opcode) {
00985   case Instruction::Add:
00986     return SelectBinaryOp(I, ISD::ADD);
00987   case Instruction::FAdd:
00988     return SelectBinaryOp(I, ISD::FADD);
00989   case Instruction::Sub:
00990     return SelectBinaryOp(I, ISD::SUB);
00991   case Instruction::FSub:
00992     // FNeg is currently represented in LLVM IR as a special case of FSub.
00993     if (BinaryOperator::isFNeg(I))
00994       return SelectFNeg(I);
00995     return SelectBinaryOp(I, ISD::FSUB);
00996   case Instruction::Mul:
00997     return SelectBinaryOp(I, ISD::MUL);
00998   case Instruction::FMul:
00999     return SelectBinaryOp(I, ISD::FMUL);
01000   case Instruction::SDiv:
01001     return SelectBinaryOp(I, ISD::SDIV);
01002   case Instruction::UDiv:
01003     return SelectBinaryOp(I, ISD::UDIV);
01004   case Instruction::FDiv:
01005     return SelectBinaryOp(I, ISD::FDIV);
01006   case Instruction::SRem:
01007     return SelectBinaryOp(I, ISD::SREM);
01008   case Instruction::URem:
01009     return SelectBinaryOp(I, ISD::UREM);
01010   case Instruction::FRem:
01011     return SelectBinaryOp(I, ISD::FREM);
01012   case Instruction::Shl:
01013     return SelectBinaryOp(I, ISD::SHL);
01014   case Instruction::LShr:
01015     return SelectBinaryOp(I, ISD::SRL);
01016   case Instruction::AShr:
01017     return SelectBinaryOp(I, ISD::SRA);
01018   case Instruction::And:
01019     return SelectBinaryOp(I, ISD::AND);
01020   case Instruction::Or:
01021     return SelectBinaryOp(I, ISD::OR);
01022   case Instruction::Xor:
01023     return SelectBinaryOp(I, ISD::XOR);
01024 
01025   case Instruction::GetElementPtr:
01026     return SelectGetElementPtr(I);
01027 
01028   case Instruction::Br: {
01029     const BranchInst *BI = cast<BranchInst>(I);
01030 
01031     if (BI->isUnconditional()) {
01032       const BasicBlock *LLVMSucc = BI->getSuccessor(0);
01033       MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
01034       FastEmitBranch(MSucc, BI->getDebugLoc());
01035       return true;
01036     }
01037 
01038     // Conditional branches are not handed yet.
01039     // Halt "fast" selection and bail.
01040     return false;
01041   }
01042 
01043   case Instruction::Unreachable:
01044     if (TM.Options.TrapUnreachable)
01045       return FastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0;
01046     else
01047       return true;
01048 
01049   case Instruction::Alloca:
01050     // FunctionLowering has the static-sized case covered.
01051     if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
01052       return true;
01053 
01054     // Dynamic-sized alloca is not handled yet.
01055     return false;
01056 
01057   case Instruction::Call:
01058     return SelectCall(I);
01059 
01060   case Instruction::BitCast:
01061     return SelectBitCast(I);
01062 
01063   case Instruction::FPToSI:
01064     return SelectCast(I, ISD::FP_TO_SINT);
01065   case Instruction::ZExt:
01066     return SelectCast(I, ISD::ZERO_EXTEND);
01067   case Instruction::SExt:
01068     return SelectCast(I, ISD::SIGN_EXTEND);
01069   case Instruction::Trunc:
01070     return SelectCast(I, ISD::TRUNCATE);
01071   case Instruction::SIToFP:
01072     return SelectCast(I, ISD::SINT_TO_FP);
01073 
01074   case Instruction::IntToPtr: // Deliberate fall-through.
01075   case Instruction::PtrToInt: {
01076     EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
01077     EVT DstVT = TLI.getValueType(I->getType());
01078     if (DstVT.bitsGT(SrcVT))
01079       return SelectCast(I, ISD::ZERO_EXTEND);
01080     if (DstVT.bitsLT(SrcVT))
01081       return SelectCast(I, ISD::TRUNCATE);
01082     unsigned Reg = getRegForValue(I->getOperand(0));
01083     if (Reg == 0) return false;
01084     UpdateValueMap(I, Reg);
01085     return true;
01086   }
01087 
01088   case Instruction::ExtractValue:
01089     return SelectExtractValue(I);
01090 
01091   case Instruction::PHI:
01092     llvm_unreachable("FastISel shouldn't visit PHI nodes!");
01093 
01094   default:
01095     // Unhandled instruction. Halt "fast" selection and bail.
01096     return false;
01097   }
01098 }
01099 
01100 FastISel::FastISel(FunctionLoweringInfo &funcInfo,
01101                    const TargetLibraryInfo *libInfo)
01102   : FuncInfo(funcInfo),
01103     MRI(FuncInfo.MF->getRegInfo()),
01104     MFI(*FuncInfo.MF->getFrameInfo()),
01105     MCP(*FuncInfo.MF->getConstantPool()),
01106     TM(FuncInfo.MF->getTarget()),
01107     DL(*TM.getDataLayout()),
01108     TII(*TM.getInstrInfo()),
01109     TLI(*TM.getTargetLowering()),
01110     TRI(*TM.getRegisterInfo()),
01111     LibInfo(libInfo) {
01112 }
01113 
01114 FastISel::~FastISel() {}
01115 
01116 bool FastISel::FastLowerArguments() {
01117   return false;
01118 }
01119 
01120 unsigned FastISel::FastEmit_(MVT, MVT,
01121                              unsigned) {
01122   return 0;
01123 }
01124 
01125 unsigned FastISel::FastEmit_r(MVT, MVT,
01126                               unsigned,
01127                               unsigned /*Op0*/, bool /*Op0IsKill*/) {
01128   return 0;
01129 }
01130 
01131 unsigned FastISel::FastEmit_rr(MVT, MVT,
01132                                unsigned,
01133                                unsigned /*Op0*/, bool /*Op0IsKill*/,
01134                                unsigned /*Op1*/, bool /*Op1IsKill*/) {
01135   return 0;
01136 }
01137 
01138 unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
01139   return 0;
01140 }
01141 
01142 unsigned FastISel::FastEmit_f(MVT, MVT,
01143                               unsigned, const ConstantFP * /*FPImm*/) {
01144   return 0;
01145 }
01146 
01147 unsigned FastISel::FastEmit_ri(MVT, MVT,
01148                                unsigned,
01149                                unsigned /*Op0*/, bool /*Op0IsKill*/,
01150                                uint64_t /*Imm*/) {
01151   return 0;
01152 }
01153 
01154 unsigned FastISel::FastEmit_rf(MVT, MVT,
01155                                unsigned,
01156                                unsigned /*Op0*/, bool /*Op0IsKill*/,
01157                                const ConstantFP * /*FPImm*/) {
01158   return 0;
01159 }
01160 
01161 unsigned FastISel::FastEmit_rri(MVT, MVT,
01162                                 unsigned,
01163                                 unsigned /*Op0*/, bool /*Op0IsKill*/,
01164                                 unsigned /*Op1*/, bool /*Op1IsKill*/,
01165                                 uint64_t /*Imm*/) {
01166   return 0;
01167 }
01168 
01169 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
01170 /// to emit an instruction with an immediate operand using FastEmit_ri.
01171 /// If that fails, it materializes the immediate into a register and try
01172 /// FastEmit_rr instead.
01173 unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode,
01174                                 unsigned Op0, bool Op0IsKill,
01175                                 uint64_t Imm, MVT ImmType) {
01176   // If this is a multiply by a power of two, emit this as a shift left.
01177   if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
01178     Opcode = ISD::SHL;
01179     Imm = Log2_64(Imm);
01180   } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
01181     // div x, 8 -> srl x, 3
01182     Opcode = ISD::SRL;
01183     Imm = Log2_64(Imm);
01184   }
01185 
01186   // Horrible hack (to be removed), check to make sure shift amounts are
01187   // in-range.
01188   if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
01189       Imm >= VT.getSizeInBits())
01190     return 0;
01191 
01192   // First check if immediate type is legal. If not, we can't use the ri form.
01193   unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
01194   if (ResultReg != 0)
01195     return ResultReg;
01196   unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
01197   if (MaterialReg == 0) {
01198     // This is a bit ugly/slow, but failing here means falling out of
01199     // fast-isel, which would be very slow.
01200     IntegerType *ITy = IntegerType::get(FuncInfo.Fn->getContext(),
01201                                               VT.getSizeInBits());
01202     MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
01203     assert (MaterialReg != 0 && "Unable to materialize imm.");
01204     if (MaterialReg == 0) return 0;
01205   }
01206   return FastEmit_rr(VT, VT, Opcode,
01207                      Op0, Op0IsKill,
01208                      MaterialReg, /*Kill=*/true);
01209 }
01210 
01211 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
01212   return MRI.createVirtualRegister(RC);
01213 }
01214 
01215 unsigned FastISel::constrainOperandRegClass(const MCInstrDesc &II,
01216                                             unsigned Op, unsigned OpNum) {
01217   if (TargetRegisterInfo::isVirtualRegister(Op)) {
01218     const TargetRegisterClass *RegClass =
01219         TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF);
01220     if (!MRI.constrainRegClass(Op, RegClass)) {
01221       // If it's not legal to COPY between the register classes, something
01222       // has gone very wrong before we got here.
01223       unsigned NewOp = createResultReg(RegClass);
01224       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01225               TII.get(TargetOpcode::COPY), NewOp).addReg(Op);
01226       return NewOp;
01227     }
01228   }
01229   return Op;
01230 }
01231 
01232 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
01233                                  const TargetRegisterClass* RC) {
01234   unsigned ResultReg = createResultReg(RC);
01235   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01236 
01237   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg);
01238   return ResultReg;
01239 }
01240 
01241 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
01242                                   const TargetRegisterClass *RC,
01243                                   unsigned Op0, bool Op0IsKill) {
01244   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01245 
01246   unsigned ResultReg = createResultReg(RC);
01247   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01248 
01249   if (II.getNumDefs() >= 1)
01250     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01251       .addReg(Op0, Op0IsKill * RegState::Kill);
01252   else {
01253     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01254       .addReg(Op0, Op0IsKill * RegState::Kill);
01255     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01256             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01257   }
01258 
01259   return ResultReg;
01260 }
01261 
01262 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
01263                                    const TargetRegisterClass *RC,
01264                                    unsigned Op0, bool Op0IsKill,
01265                                    unsigned Op1, bool Op1IsKill) {
01266   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01267 
01268   unsigned ResultReg = createResultReg(RC);
01269   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01270   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
01271 
01272   if (II.getNumDefs() >= 1)
01273     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01274       .addReg(Op0, Op0IsKill * RegState::Kill)
01275       .addReg(Op1, Op1IsKill * RegState::Kill);
01276   else {
01277     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01278       .addReg(Op0, Op0IsKill * RegState::Kill)
01279       .addReg(Op1, Op1IsKill * RegState::Kill);
01280     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01281             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01282   }
01283   return ResultReg;
01284 }
01285 
01286 unsigned FastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
01287                                    const TargetRegisterClass *RC,
01288                                    unsigned Op0, bool Op0IsKill,
01289                                    unsigned Op1, bool Op1IsKill,
01290                                    unsigned Op2, bool Op2IsKill) {
01291   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01292 
01293   unsigned ResultReg = createResultReg(RC);
01294   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01295   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
01296   Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
01297 
01298   if (II.getNumDefs() >= 1)
01299     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01300       .addReg(Op0, Op0IsKill * RegState::Kill)
01301       .addReg(Op1, Op1IsKill * RegState::Kill)
01302       .addReg(Op2, Op2IsKill * RegState::Kill);
01303   else {
01304     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01305       .addReg(Op0, Op0IsKill * RegState::Kill)
01306       .addReg(Op1, Op1IsKill * RegState::Kill)
01307       .addReg(Op2, Op2IsKill * RegState::Kill);
01308     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01309             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01310   }
01311   return ResultReg;
01312 }
01313 
01314 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
01315                                    const TargetRegisterClass *RC,
01316                                    unsigned Op0, bool Op0IsKill,
01317                                    uint64_t Imm) {
01318   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01319 
01320   unsigned ResultReg = createResultReg(RC);
01321   RC = TII.getRegClass(II, II.getNumDefs(), &TRI, *FuncInfo.MF);
01322   MRI.constrainRegClass(Op0, RC);
01323 
01324   if (II.getNumDefs() >= 1)
01325     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01326       .addReg(Op0, Op0IsKill * RegState::Kill)
01327       .addImm(Imm);
01328   else {
01329     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01330       .addReg(Op0, Op0IsKill * RegState::Kill)
01331       .addImm(Imm);
01332     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01333             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01334   }
01335   return ResultReg;
01336 }
01337 
01338 unsigned FastISel::FastEmitInst_rii(unsigned MachineInstOpcode,
01339                                    const TargetRegisterClass *RC,
01340                                    unsigned Op0, bool Op0IsKill,
01341                                    uint64_t Imm1, uint64_t Imm2) {
01342   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01343 
01344   unsigned ResultReg = createResultReg(RC);
01345   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01346 
01347   if (II.getNumDefs() >= 1)
01348     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01349       .addReg(Op0, Op0IsKill * RegState::Kill)
01350       .addImm(Imm1)
01351       .addImm(Imm2);
01352   else {
01353     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01354       .addReg(Op0, Op0IsKill * RegState::Kill)
01355       .addImm(Imm1)
01356       .addImm(Imm2);
01357     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01358             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01359   }
01360   return ResultReg;
01361 }
01362 
01363 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
01364                                    const TargetRegisterClass *RC,
01365                                    unsigned Op0, bool Op0IsKill,
01366                                    const ConstantFP *FPImm) {
01367   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01368 
01369   unsigned ResultReg = createResultReg(RC);
01370   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01371 
01372   if (II.getNumDefs() >= 1)
01373     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01374       .addReg(Op0, Op0IsKill * RegState::Kill)
01375       .addFPImm(FPImm);
01376   else {
01377     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01378       .addReg(Op0, Op0IsKill * RegState::Kill)
01379       .addFPImm(FPImm);
01380     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01381             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01382   }
01383   return ResultReg;
01384 }
01385 
01386 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
01387                                     const TargetRegisterClass *RC,
01388                                     unsigned Op0, bool Op0IsKill,
01389                                     unsigned Op1, bool Op1IsKill,
01390                                     uint64_t Imm) {
01391   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01392 
01393   unsigned ResultReg = createResultReg(RC);
01394   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01395   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
01396 
01397   if (II.getNumDefs() >= 1)
01398     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01399       .addReg(Op0, Op0IsKill * RegState::Kill)
01400       .addReg(Op1, Op1IsKill * RegState::Kill)
01401       .addImm(Imm);
01402   else {
01403     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01404       .addReg(Op0, Op0IsKill * RegState::Kill)
01405       .addReg(Op1, Op1IsKill * RegState::Kill)
01406       .addImm(Imm);
01407     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01408             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01409   }
01410   return ResultReg;
01411 }
01412 
01413 unsigned FastISel::FastEmitInst_rrii(unsigned MachineInstOpcode,
01414                                      const TargetRegisterClass *RC,
01415                                      unsigned Op0, bool Op0IsKill,
01416                                      unsigned Op1, bool Op1IsKill,
01417                                      uint64_t Imm1, uint64_t Imm2) {
01418   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01419 
01420   unsigned ResultReg = createResultReg(RC);
01421   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01422   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
01423 
01424   if (II.getNumDefs() >= 1)
01425     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01426       .addReg(Op0, Op0IsKill * RegState::Kill)
01427       .addReg(Op1, Op1IsKill * RegState::Kill)
01428       .addImm(Imm1).addImm(Imm2);
01429   else {
01430     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01431       .addReg(Op0, Op0IsKill * RegState::Kill)
01432       .addReg(Op1, Op1IsKill * RegState::Kill)
01433       .addImm(Imm1).addImm(Imm2);
01434     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01435             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01436   }
01437   return ResultReg;
01438 }
01439 
01440 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
01441                                   const TargetRegisterClass *RC,
01442                                   uint64_t Imm) {
01443   unsigned ResultReg = createResultReg(RC);
01444   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01445 
01446   if (II.getNumDefs() >= 1)
01447     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg).addImm(Imm);
01448   else {
01449     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm);
01450     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01451             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01452   }
01453   return ResultReg;
01454 }
01455 
01456 unsigned FastISel::FastEmitInst_ii(unsigned MachineInstOpcode,
01457                                   const TargetRegisterClass *RC,
01458                                   uint64_t Imm1, uint64_t Imm2) {
01459   unsigned ResultReg = createResultReg(RC);
01460   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01461 
01462   if (II.getNumDefs() >= 1)
01463     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01464       .addImm(Imm1).addImm(Imm2);
01465   else {
01466     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm1).addImm(Imm2);
01467     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01468             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01469   }
01470   return ResultReg;
01471 }
01472 
01473 unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT,
01474                                               unsigned Op0, bool Op0IsKill,
01475                                               uint32_t Idx) {
01476   unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
01477   assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
01478          "Cannot yet extract from physregs");
01479   const TargetRegisterClass *RC = MRI.getRegClass(Op0);
01480   MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
01481   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
01482           DbgLoc, TII.get(TargetOpcode::COPY), ResultReg)
01483     .addReg(Op0, getKillRegState(Op0IsKill), Idx);
01484   return ResultReg;
01485 }
01486 
01487 /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
01488 /// with all but the least significant bit set to zero.
01489 unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
01490   return FastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
01491 }
01492 
01493 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
01494 /// Emit code to ensure constants are copied into registers when needed.
01495 /// Remember the virtual registers that need to be added to the Machine PHI
01496 /// nodes as input.  We cannot just directly add them, because expansion
01497 /// might result in multiple MBB's for one BB.  As such, the start of the
01498 /// BB might correspond to a different MBB than the end.
01499 bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
01500   const TerminatorInst *TI = LLVMBB->getTerminator();
01501 
01502   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
01503   unsigned OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
01504 
01505   // Check successor nodes' PHI nodes that expect a constant to be available
01506   // from this block.
01507   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
01508     const BasicBlock *SuccBB = TI->getSuccessor(succ);
01509     if (!isa<PHINode>(SuccBB->begin())) continue;
01510     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
01511 
01512     // If this terminator has multiple identical successors (common for
01513     // switches), only handle each succ once.
01514     if (!SuccsHandled.insert(SuccMBB)) continue;
01515 
01516     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
01517 
01518     // At this point we know that there is a 1-1 correspondence between LLVM PHI
01519     // nodes and Machine PHI nodes, but the incoming operands have not been
01520     // emitted yet.
01521     for (BasicBlock::const_iterator I = SuccBB->begin();
01522          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
01523 
01524       // Ignore dead phi's.
01525       if (PN->use_empty()) continue;
01526 
01527       // Only handle legal types. Two interesting things to note here. First,
01528       // by bailing out early, we may leave behind some dead instructions,
01529       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
01530       // own moves. Second, this check is necessary because FastISel doesn't
01531       // use CreateRegs to create registers, so it always creates
01532       // exactly one register for each non-void instruction.
01533       EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
01534       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
01535         // Handle integer promotions, though, because they're common and easy.
01536         if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
01537           VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
01538         else {
01539           FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
01540           return false;
01541         }
01542       }
01543 
01544       const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
01545 
01546       // Set the DebugLoc for the copy. Prefer the location of the operand
01547       // if there is one; use the location of the PHI otherwise.
01548       DbgLoc = PN->getDebugLoc();
01549       if (const Instruction *Inst = dyn_cast<Instruction>(PHIOp))
01550         DbgLoc = Inst->getDebugLoc();
01551 
01552       unsigned Reg = getRegForValue(PHIOp);
01553       if (Reg == 0) {
01554         FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
01555         return false;
01556       }
01557       FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
01558       DbgLoc = DebugLoc();
01559     }
01560   }
01561 
01562   return true;
01563 }
01564 
01565 bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) {
01566   assert(LI->hasOneUse() &&
01567       "tryToFoldLoad expected a LoadInst with a single use");
01568   // We know that the load has a single use, but don't know what it is.  If it
01569   // isn't one of the folded instructions, then we can't succeed here.  Handle
01570   // this by scanning the single-use users of the load until we get to FoldInst.
01571   unsigned MaxUsers = 6;  // Don't scan down huge single-use chains of instrs.
01572 
01573   const Instruction *TheUser = LI->user_back();
01574   while (TheUser != FoldInst &&   // Scan up until we find FoldInst.
01575          // Stay in the right block.
01576          TheUser->getParent() == FoldInst->getParent() &&
01577          --MaxUsers) {  // Don't scan too far.
01578     // If there are multiple or no uses of this instruction, then bail out.
01579     if (!TheUser->hasOneUse())
01580       return false;
01581 
01582     TheUser = TheUser->user_back();
01583   }
01584 
01585   // If we didn't find the fold instruction, then we failed to collapse the
01586   // sequence.
01587   if (TheUser != FoldInst)
01588     return false;
01589 
01590   // Don't try to fold volatile loads.  Target has to deal with alignment
01591   // constraints.
01592   if (LI->isVolatile())
01593     return false;
01594 
01595   // Figure out which vreg this is going into.  If there is no assigned vreg yet
01596   // then there actually was no reference to it.  Perhaps the load is referenced
01597   // by a dead instruction.
01598   unsigned LoadReg = getRegForValue(LI);
01599   if (LoadReg == 0)
01600     return false;
01601 
01602   // We can't fold if this vreg has no uses or more than one use.  Multiple uses
01603   // may mean that the instruction got lowered to multiple MIs, or the use of
01604   // the loaded value ended up being multiple operands of the result.
01605   if (!MRI.hasOneUse(LoadReg))
01606     return false;
01607 
01608   MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg);
01609   MachineInstr *User = RI->getParent();
01610 
01611   // Set the insertion point properly.  Folding the load can cause generation of
01612   // other random instructions (like sign extends) for addressing modes; make
01613   // sure they get inserted in a logical place before the new instruction.
01614   FuncInfo.InsertPt = User;
01615   FuncInfo.MBB = User->getParent();
01616 
01617   // Ask the target to try folding the load.
01618   return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI);
01619 }
01620 
01621 bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) {
01622   // Must be an add.
01623   if (!isa<AddOperator>(Add))
01624     return false;
01625   // Type size needs to match.
01626   if (DL.getTypeSizeInBits(GEP->getType()) !=
01627       DL.getTypeSizeInBits(Add->getType()))
01628     return false;
01629   // Must be in the same basic block.
01630   if (isa<Instruction>(Add) &&
01631       FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB)
01632     return false;
01633   // Must have a constant operand.
01634   return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1));
01635 }
01636