FastISel.cpp revision c9c137b463b953fbf8942f655d67f6dc1a0f7965
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#define DEBUG_TYPE "isel"
43#include "llvm/Function.h"
44#include "llvm/GlobalVariable.h"
45#include "llvm/Instructions.h"
46#include "llvm/IntrinsicInst.h"
47#include "llvm/Operator.h"
48#include "llvm/CodeGen/Analysis.h"
49#include "llvm/CodeGen/FastISel.h"
50#include "llvm/CodeGen/FunctionLoweringInfo.h"
51#include "llvm/CodeGen/MachineInstrBuilder.h"
52#include "llvm/CodeGen/MachineModuleInfo.h"
53#include "llvm/CodeGen/MachineRegisterInfo.h"
54#include "llvm/Analysis/DebugInfo.h"
55#include "llvm/Analysis/Loads.h"
56#include "llvm/Target/TargetData.h"
57#include "llvm/Target/TargetInstrInfo.h"
58#include "llvm/Target/TargetLowering.h"
59#include "llvm/Target/TargetMachine.h"
60#include "llvm/Support/ErrorHandling.h"
61#include "llvm/Support/Debug.h"
62#include "llvm/ADT/Statistic.h"
63using namespace llvm;
64
65STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
66          "target-independent selector");
67STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
68          "target-specific selector");
69STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
70
71/// startNewBlock - Set the current block to which generated machine
72/// instructions will be appended, and clear the local CSE map.
73///
74void FastISel::startNewBlock() {
75  LocalValueMap.clear();
76
77  EmitStartPt = 0;
78
79  // Advance the emit start point past any EH_LABEL instructions.
80  MachineBasicBlock::iterator
81    I = FuncInfo.MBB->begin(), E = FuncInfo.MBB->end();
82  while (I != E && I->getOpcode() == TargetOpcode::EH_LABEL) {
83    EmitStartPt = I;
84    ++I;
85  }
86  LastLocalValue = EmitStartPt;
87}
88
89void FastISel::flushLocalValueMap() {
90  LocalValueMap.clear();
91  LastLocalValue = EmitStartPt;
92  recomputeInsertPt();
93}
94
95bool FastISel::hasTrivialKill(const Value *V) const {
96  // Don't consider constants or arguments to have trivial kills.
97  const Instruction *I = dyn_cast<Instruction>(V);
98  if (!I)
99    return false;
100
101  // No-op casts are trivially coalesced by fast-isel.
102  if (const CastInst *Cast = dyn_cast<CastInst>(I))
103    if (Cast->isNoopCast(TD.getIntPtrType(Cast->getContext())) &&
104        !hasTrivialKill(Cast->getOperand(0)))
105      return false;
106
107  // GEPs with all zero indices are trivially coalesced by fast-isel.
108  if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
109    if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
110      return false;
111
112  // Only instructions with a single use in the same basic block are considered
113  // to have trivial kills.
114  return I->hasOneUse() &&
115         !(I->getOpcode() == Instruction::BitCast ||
116           I->getOpcode() == Instruction::PtrToInt ||
117           I->getOpcode() == Instruction::IntToPtr) &&
118         cast<Instruction>(*I->use_begin())->getParent() == I->getParent();
119}
120
121unsigned FastISel::getRegForValue(const Value *V) {
122  EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true);
123  // Don't handle non-simple values in FastISel.
124  if (!RealVT.isSimple())
125    return 0;
126
127  // Ignore illegal types. We must do this before looking up the value
128  // in ValueMap because Arguments are given virtual registers regardless
129  // of whether FastISel can handle them.
130  MVT VT = RealVT.getSimpleVT();
131  if (!TLI.isTypeLegal(VT)) {
132    // Handle integer promotions, though, because they're common and easy.
133    if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
134      VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
135    else
136      return 0;
137  }
138
139  // Look up the value to see if we already have a register for it. We
140  // cache values defined by Instructions across blocks, and other values
141  // only locally. This is because Instructions already have the SSA
142  // def-dominates-use requirement enforced.
143  DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
144  if (I != FuncInfo.ValueMap.end())
145    return I->second;
146
147  unsigned Reg = LocalValueMap[V];
148  if (Reg != 0)
149    return Reg;
150
151  // In bottom-up mode, just create the virtual register which will be used
152  // to hold the value. It will be materialized later.
153  if (isa<Instruction>(V) &&
154      (!isa<AllocaInst>(V) ||
155       !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
156    return FuncInfo.InitializeRegForValue(V);
157
158  SavePoint SaveInsertPt = enterLocalValueArea();
159
160  // Materialize the value in a register. Emit any instructions in the
161  // local value area.
162  Reg = materializeRegForValue(V, VT);
163
164  leaveLocalValueArea(SaveInsertPt);
165
166  return Reg;
167}
168
169/// materializeRegForValue - Helper for getRegForValue. This function is
170/// called when the value isn't already available in a register and must
171/// be materialized with new instructions.
172unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
173  unsigned Reg = 0;
174
175  if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
176    if (CI->getValue().getActiveBits() <= 64)
177      Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
178  } else if (isa<AllocaInst>(V)) {
179    Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
180  } else if (isa<ConstantPointerNull>(V)) {
181    // Translate this as an integer zero so that it can be
182    // local-CSE'd with actual integer zeros.
183    Reg =
184      getRegForValue(Constant::getNullValue(TD.getIntPtrType(V->getContext())));
185  } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
186    if (CF->isNullValue()) {
187      Reg = TargetMaterializeFloatZero(CF);
188    } else {
189      // Try to emit the constant directly.
190      Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
191    }
192
193    if (!Reg) {
194      // Try to emit the constant by using an integer constant with a cast.
195      const APFloat &Flt = CF->getValueAPF();
196      EVT IntVT = TLI.getPointerTy();
197
198      uint64_t x[2];
199      uint32_t IntBitWidth = IntVT.getSizeInBits();
200      bool isExact;
201      (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
202                                APFloat::rmTowardZero, &isExact);
203      if (isExact) {
204        APInt IntVal(IntBitWidth, x);
205
206        unsigned IntegerReg =
207          getRegForValue(ConstantInt::get(V->getContext(), IntVal));
208        if (IntegerReg != 0)
209          Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP,
210                           IntegerReg, /*Kill=*/false);
211      }
212    }
213  } else if (const Operator *Op = dyn_cast<Operator>(V)) {
214    if (!SelectOperator(Op, Op->getOpcode()))
215      if (!isa<Instruction>(Op) ||
216          !TargetSelectInstruction(cast<Instruction>(Op)))
217        return 0;
218    Reg = lookUpRegForValue(Op);
219  } else if (isa<UndefValue>(V)) {
220    Reg = createResultReg(TLI.getRegClassFor(VT));
221    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
222            TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
223  }
224
225  // If target-independent code couldn't handle the value, give target-specific
226  // code a try.
227  if (!Reg && isa<Constant>(V))
228    Reg = TargetMaterializeConstant(cast<Constant>(V));
229
230  // Don't cache constant materializations in the general ValueMap.
231  // To do so would require tracking what uses they dominate.
232  if (Reg != 0) {
233    LocalValueMap[V] = Reg;
234    LastLocalValue = MRI.getVRegDef(Reg);
235  }
236  return Reg;
237}
238
239unsigned FastISel::lookUpRegForValue(const Value *V) {
240  // Look up the value to see if we already have a register for it. We
241  // cache values defined by Instructions across blocks, and other values
242  // only locally. This is because Instructions already have the SSA
243  // def-dominates-use requirement enforced.
244  DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
245  if (I != FuncInfo.ValueMap.end())
246    return I->second;
247  return LocalValueMap[V];
248}
249
250/// UpdateValueMap - Update the value map to include the new mapping for this
251/// instruction, or insert an extra copy to get the result in a previous
252/// determined register.
253/// NOTE: This is only necessary because we might select a block that uses
254/// a value before we select the block that defines the value.  It might be
255/// possible to fix this by selecting blocks in reverse postorder.
256void FastISel::UpdateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
257  if (!isa<Instruction>(I)) {
258    LocalValueMap[I] = Reg;
259    return;
260  }
261
262  unsigned &AssignedReg = FuncInfo.ValueMap[I];
263  if (AssignedReg == 0)
264    // Use the new register.
265    AssignedReg = Reg;
266  else if (Reg != AssignedReg) {
267    // Arrange for uses of AssignedReg to be replaced by uses of Reg.
268    for (unsigned i = 0; i < NumRegs; i++)
269      FuncInfo.RegFixups[AssignedReg+i] = Reg+i;
270
271    AssignedReg = Reg;
272  }
273}
274
275std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
276  unsigned IdxN = getRegForValue(Idx);
277  if (IdxN == 0)
278    // Unhandled operand. Halt "fast" selection and bail.
279    return std::pair<unsigned, bool>(0, false);
280
281  bool IdxNIsKill = hasTrivialKill(Idx);
282
283  // If the index is smaller or larger than intptr_t, truncate or extend it.
284  MVT PtrVT = TLI.getPointerTy();
285  EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
286  if (IdxVT.bitsLT(PtrVT)) {
287    IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND,
288                      IdxN, IdxNIsKill);
289    IdxNIsKill = true;
290  }
291  else if (IdxVT.bitsGT(PtrVT)) {
292    IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE,
293                      IdxN, IdxNIsKill);
294    IdxNIsKill = true;
295  }
296  return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
297}
298
299void FastISel::recomputeInsertPt() {
300  if (getLastLocalValue()) {
301    FuncInfo.InsertPt = getLastLocalValue();
302    FuncInfo.MBB = FuncInfo.InsertPt->getParent();
303    ++FuncInfo.InsertPt;
304  } else
305    FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
306
307  // Now skip past any EH_LABELs, which must remain at the beginning.
308  while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
309         FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
310    ++FuncInfo.InsertPt;
311}
312
313void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
314                              MachineBasicBlock::iterator E) {
315  assert (I && E && std::distance(I, E) > 0 && "Invalid iterator!");
316  while (I != E) {
317    MachineInstr *Dead = &*I;
318    ++I;
319    Dead->eraseFromParent();
320    ++NumFastIselDead;
321  }
322  recomputeInsertPt();
323}
324
325FastISel::SavePoint FastISel::enterLocalValueArea() {
326  MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
327  DebugLoc OldDL = DL;
328  recomputeInsertPt();
329  DL = DebugLoc();
330  SavePoint SP = { OldInsertPt, OldDL };
331  return SP;
332}
333
334void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
335  if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
336    LastLocalValue = llvm::prior(FuncInfo.InsertPt);
337
338  // Restore the previous insert position.
339  FuncInfo.InsertPt = OldInsertPt.InsertPt;
340  DL = OldInsertPt.DL;
341}
342
343/// SelectBinaryOp - Select and emit code for a binary operator instruction,
344/// which has an opcode which directly corresponds to the given ISD opcode.
345///
346bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) {
347  EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
348  if (VT == MVT::Other || !VT.isSimple())
349    // Unhandled type. Halt "fast" selection and bail.
350    return false;
351
352  // We only handle legal types. For example, on x86-32 the instruction
353  // selector contains all of the 64-bit instructions from x86-64,
354  // under the assumption that i64 won't be used if the target doesn't
355  // support it.
356  if (!TLI.isTypeLegal(VT)) {
357    // MVT::i1 is special. Allow AND, OR, or XOR because they
358    // don't require additional zeroing, which makes them easy.
359    if (VT == MVT::i1 &&
360        (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
361         ISDOpcode == ISD::XOR))
362      VT = TLI.getTypeToTransformTo(I->getContext(), VT);
363    else
364      return false;
365  }
366
367  // Check if the first operand is a constant, and handle it as "ri".  At -O0,
368  // we don't have anything that canonicalizes operand order.
369  if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
370    if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
371      unsigned Op1 = getRegForValue(I->getOperand(1));
372      if (Op1 == 0) return false;
373
374      bool Op1IsKill = hasTrivialKill(I->getOperand(1));
375
376      unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1,
377                                        Op1IsKill, CI->getZExtValue(),
378                                        VT.getSimpleVT());
379      if (ResultReg == 0) return false;
380
381      // We successfully emitted code for the given LLVM Instruction.
382      UpdateValueMap(I, ResultReg);
383      return true;
384    }
385
386
387  unsigned Op0 = getRegForValue(I->getOperand(0));
388  if (Op0 == 0)   // Unhandled operand. Halt "fast" selection and bail.
389    return false;
390
391  bool Op0IsKill = hasTrivialKill(I->getOperand(0));
392
393  // Check if the second operand is a constant and handle it appropriately.
394  if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
395    uint64_t Imm = CI->getZExtValue();
396
397    // Transform "sdiv exact X, 8" -> "sra X, 3".
398    if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
399        cast<BinaryOperator>(I)->isExact() &&
400        isPowerOf2_64(Imm)) {
401      Imm = Log2_64(Imm);
402      ISDOpcode = ISD::SRA;
403    }
404
405    unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
406                                      Op0IsKill, Imm, VT.getSimpleVT());
407    if (ResultReg == 0) return false;
408
409    // We successfully emitted code for the given LLVM Instruction.
410    UpdateValueMap(I, ResultReg);
411    return true;
412  }
413
414  // Check if the second operand is a constant float.
415  if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
416    unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
417                                     ISDOpcode, Op0, Op0IsKill, CF);
418    if (ResultReg != 0) {
419      // We successfully emitted code for the given LLVM Instruction.
420      UpdateValueMap(I, ResultReg);
421      return true;
422    }
423  }
424
425  unsigned Op1 = getRegForValue(I->getOperand(1));
426  if (Op1 == 0)
427    // Unhandled operand. Halt "fast" selection and bail.
428    return false;
429
430  bool Op1IsKill = hasTrivialKill(I->getOperand(1));
431
432  // Now we have both operands in registers. Emit the instruction.
433  unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
434                                   ISDOpcode,
435                                   Op0, Op0IsKill,
436                                   Op1, Op1IsKill);
437  if (ResultReg == 0)
438    // Target-specific code wasn't able to find a machine opcode for
439    // the given ISD opcode and type. Halt "fast" selection and bail.
440    return false;
441
442  // We successfully emitted code for the given LLVM Instruction.
443  UpdateValueMap(I, ResultReg);
444  return true;
445}
446
447bool FastISel::SelectGetElementPtr(const User *I) {
448  unsigned N = getRegForValue(I->getOperand(0));
449  if (N == 0)
450    // Unhandled operand. Halt "fast" selection and bail.
451    return false;
452
453  bool NIsKill = hasTrivialKill(I->getOperand(0));
454
455  // Keep a running tab of the total offset to coalesce multiple N = N + Offset
456  // into a single N = N + TotalOffset.
457  uint64_t TotalOffs = 0;
458  // FIXME: What's a good SWAG number for MaxOffs?
459  uint64_t MaxOffs = 2048;
460  Type *Ty = I->getOperand(0)->getType();
461  MVT VT = TLI.getPointerTy();
462  for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1,
463       E = I->op_end(); OI != E; ++OI) {
464    const Value *Idx = *OI;
465    if (StructType *StTy = dyn_cast<StructType>(Ty)) {
466      unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
467      if (Field) {
468        // N = N + Offset
469        TotalOffs += TD.getStructLayout(StTy)->getElementOffset(Field);
470        if (TotalOffs >= MaxOffs) {
471          N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
472          if (N == 0)
473            // Unhandled operand. Halt "fast" selection and bail.
474            return false;
475          NIsKill = true;
476          TotalOffs = 0;
477        }
478      }
479      Ty = StTy->getElementType(Field);
480    } else {
481      Ty = cast<SequentialType>(Ty)->getElementType();
482
483      // If this is a constant subscript, handle it quickly.
484      if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
485        if (CI->isZero()) continue;
486        // N = N + Offset
487        TotalOffs +=
488          TD.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
489        if (TotalOffs >= MaxOffs) {
490          N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
491          if (N == 0)
492            // Unhandled operand. Halt "fast" selection and bail.
493            return false;
494          NIsKill = true;
495          TotalOffs = 0;
496        }
497        continue;
498      }
499      if (TotalOffs) {
500        N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
501        if (N == 0)
502          // Unhandled operand. Halt "fast" selection and bail.
503          return false;
504        NIsKill = true;
505        TotalOffs = 0;
506      }
507
508      // N = N + Idx * ElementSize;
509      uint64_t ElementSize = TD.getTypeAllocSize(Ty);
510      std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
511      unsigned IdxN = Pair.first;
512      bool IdxNIsKill = Pair.second;
513      if (IdxN == 0)
514        // Unhandled operand. Halt "fast" selection and bail.
515        return false;
516
517      if (ElementSize != 1) {
518        IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
519        if (IdxN == 0)
520          // Unhandled operand. Halt "fast" selection and bail.
521          return false;
522        IdxNIsKill = true;
523      }
524      N = FastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
525      if (N == 0)
526        // Unhandled operand. Halt "fast" selection and bail.
527        return false;
528    }
529  }
530  if (TotalOffs) {
531    N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
532    if (N == 0)
533      // Unhandled operand. Halt "fast" selection and bail.
534      return false;
535  }
536
537  // We successfully emitted code for the given LLVM Instruction.
538  UpdateValueMap(I, N);
539  return true;
540}
541
542bool FastISel::SelectCall(const User *I) {
543  const CallInst *Call = cast<CallInst>(I);
544
545  // Handle simple inline asms.
546  if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
547    // Don't attempt to handle constraints.
548    if (!IA->getConstraintString().empty())
549      return false;
550
551    unsigned ExtraInfo = 0;
552    if (IA->hasSideEffects())
553      ExtraInfo |= InlineAsm::Extra_HasSideEffects;
554    if (IA->isAlignStack())
555      ExtraInfo |= InlineAsm::Extra_IsAlignStack;
556
557    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
558            TII.get(TargetOpcode::INLINEASM))
559      .addExternalSymbol(IA->getAsmString().c_str())
560      .addImm(ExtraInfo);
561    return true;
562  }
563
564  MachineModuleInfo &MMI = FuncInfo.MF->getMMI();
565  ComputeUsesVAFloatArgument(*Call, &MMI);
566
567  const Function *F = Call->getCalledFunction();
568  if (!F) return false;
569
570  // Handle selected intrinsic function calls.
571  switch (F->getIntrinsicID()) {
572  default: break;
573    // At -O0 we don't care about the lifetime intrinsics.
574  case Intrinsic::lifetime_start:
575  case Intrinsic::lifetime_end:
576    return true;
577  case Intrinsic::dbg_declare: {
578    const DbgDeclareInst *DI = cast<DbgDeclareInst>(Call);
579    if (!DIVariable(DI->getVariable()).Verify() ||
580        !FuncInfo.MF->getMMI().hasDebugInfo())
581      return true;
582
583    const Value *Address = DI->getAddress();
584    if (!Address || isa<UndefValue>(Address) || isa<AllocaInst>(Address))
585      return true;
586
587    unsigned Reg = 0;
588    unsigned Offset = 0;
589    if (const Argument *Arg = dyn_cast<Argument>(Address)) {
590      // Some arguments' frame index is recorded during argument lowering.
591      Offset = FuncInfo.getArgumentFrameIndex(Arg);
592      if (Offset)
593	Reg = TRI.getFrameRegister(*FuncInfo.MF);
594    }
595    if (!Reg)
596      Reg = getRegForValue(Address);
597
598    if (Reg)
599      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
600              TII.get(TargetOpcode::DBG_VALUE))
601        .addReg(Reg, RegState::Debug).addImm(Offset)
602        .addMetadata(DI->getVariable());
603    return true;
604  }
605  case Intrinsic::dbg_value: {
606    // This form of DBG_VALUE is target-independent.
607    const DbgValueInst *DI = cast<DbgValueInst>(Call);
608    const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
609    const Value *V = DI->getValue();
610    if (!V) {
611      // Currently the optimizer can produce this; insert an undef to
612      // help debugging.  Probably the optimizer should not do this.
613      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
614        .addReg(0U).addImm(DI->getOffset())
615        .addMetadata(DI->getVariable());
616    } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
617      if (CI->getBitWidth() > 64)
618        BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
619          .addCImm(CI).addImm(DI->getOffset())
620          .addMetadata(DI->getVariable());
621      else
622        BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
623          .addImm(CI->getZExtValue()).addImm(DI->getOffset())
624          .addMetadata(DI->getVariable());
625    } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
626      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
627        .addFPImm(CF).addImm(DI->getOffset())
628        .addMetadata(DI->getVariable());
629    } else if (unsigned Reg = lookUpRegForValue(V)) {
630      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
631        .addReg(Reg, RegState::Debug).addImm(DI->getOffset())
632        .addMetadata(DI->getVariable());
633    } else {
634      // We can't yet handle anything else here because it would require
635      // generating code, thus altering codegen because of debug info.
636      DEBUG(dbgs() << "Dropping debug info for " << DI);
637    }
638    return true;
639  }
640  case Intrinsic::objectsize: {
641    ConstantInt *CI = cast<ConstantInt>(Call->getArgOperand(1));
642    unsigned long long Res = CI->isZero() ? -1ULL : 0;
643    Constant *ResCI = ConstantInt::get(Call->getType(), Res);
644    unsigned ResultReg = getRegForValue(ResCI);
645    if (ResultReg == 0)
646      return false;
647    UpdateValueMap(Call, ResultReg);
648    return true;
649  }
650  }
651
652  // Usually, it does not make sense to initialize a value,
653  // make an unrelated function call and use the value, because
654  // it tends to be spilled on the stack. So, we move the pointer
655  // to the last local value to the beginning of the block, so that
656  // all the values which have already been materialized,
657  // appear after the call. It also makes sense to skip intrinsics
658  // since they tend to be inlined.
659  if (!isa<IntrinsicInst>(F))
660    flushLocalValueMap();
661
662  // An arbitrary call. Bail.
663  return false;
664}
665
666bool FastISel::SelectCast(const User *I, unsigned Opcode) {
667  EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
668  EVT DstVT = TLI.getValueType(I->getType());
669
670  if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
671      DstVT == MVT::Other || !DstVT.isSimple())
672    // Unhandled type. Halt "fast" selection and bail.
673    return false;
674
675  // Check if the destination type is legal.
676  if (!TLI.isTypeLegal(DstVT))
677    return false;
678
679  // Check if the source operand is legal.
680  if (!TLI.isTypeLegal(SrcVT))
681    return false;
682
683  unsigned InputReg = getRegForValue(I->getOperand(0));
684  if (!InputReg)
685    // Unhandled operand.  Halt "fast" selection and bail.
686    return false;
687
688  bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
689
690  unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
691                                  DstVT.getSimpleVT(),
692                                  Opcode,
693                                  InputReg, InputRegIsKill);
694  if (!ResultReg)
695    return false;
696
697  UpdateValueMap(I, ResultReg);
698  return true;
699}
700
701bool FastISel::SelectBitCast(const User *I) {
702  // If the bitcast doesn't change the type, just use the operand value.
703  if (I->getType() == I->getOperand(0)->getType()) {
704    unsigned Reg = getRegForValue(I->getOperand(0));
705    if (Reg == 0)
706      return false;
707    UpdateValueMap(I, Reg);
708    return true;
709  }
710
711  // Bitcasts of other values become reg-reg copies or BITCAST operators.
712  EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
713  EVT DstVT = TLI.getValueType(I->getType());
714
715  if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
716      DstVT == MVT::Other || !DstVT.isSimple() ||
717      !TLI.isTypeLegal(SrcVT) || !TLI.isTypeLegal(DstVT))
718    // Unhandled type. Halt "fast" selection and bail.
719    return false;
720
721  unsigned Op0 = getRegForValue(I->getOperand(0));
722  if (Op0 == 0)
723    // Unhandled operand. Halt "fast" selection and bail.
724    return false;
725
726  bool Op0IsKill = hasTrivialKill(I->getOperand(0));
727
728  // First, try to perform the bitcast by inserting a reg-reg copy.
729  unsigned ResultReg = 0;
730  if (SrcVT.getSimpleVT() == DstVT.getSimpleVT()) {
731    const TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
732    const TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
733    // Don't attempt a cross-class copy. It will likely fail.
734    if (SrcClass == DstClass) {
735      ResultReg = createResultReg(DstClass);
736      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
737              ResultReg).addReg(Op0);
738    }
739  }
740
741  // If the reg-reg copy failed, select a BITCAST opcode.
742  if (!ResultReg)
743    ResultReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
744                           ISD::BITCAST, Op0, Op0IsKill);
745
746  if (!ResultReg)
747    return false;
748
749  UpdateValueMap(I, ResultReg);
750  return true;
751}
752
753bool
754FastISel::SelectInstruction(const Instruction *I) {
755  // Just before the terminator instruction, insert instructions to
756  // feed PHI nodes in successor blocks.
757  if (isa<TerminatorInst>(I))
758    if (!HandlePHINodesInSuccessorBlocks(I->getParent()))
759      return false;
760
761  DL = I->getDebugLoc();
762
763  MachineBasicBlock::iterator SavedInsertPt = FuncInfo.InsertPt;
764
765  // First, try doing target-independent selection.
766  if (SelectOperator(I, I->getOpcode())) {
767    ++NumFastIselSuccessIndependent;
768    DL = DebugLoc();
769    return true;
770  }
771  // Remove dead code.  However, ignore call instructions since we've flushed
772  // the local value map and recomputed the insert point.
773  if (!isa<CallInst>(I)) {
774    recomputeInsertPt();
775    if (SavedInsertPt != FuncInfo.InsertPt)
776      removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
777  }
778
779  // Next, try calling the target to attempt to handle the instruction.
780  SavedInsertPt = FuncInfo.InsertPt;
781  if (TargetSelectInstruction(I)) {
782    ++NumFastIselSuccessTarget;
783    DL = DebugLoc();
784    return true;
785  }
786  // Check for dead code and remove as necessary.
787  recomputeInsertPt();
788  if (SavedInsertPt != FuncInfo.InsertPt)
789    removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
790
791  DL = DebugLoc();
792  return false;
793}
794
795/// FastEmitBranch - Emit an unconditional branch to the given block,
796/// unless it is the immediate (fall-through) successor, and update
797/// the CFG.
798void
799FastISel::FastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DL) {
800  if (FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
801    // The unconditional fall-through case, which needs no instructions.
802  } else {
803    // The unconditional branch case.
804    TII.InsertBranch(*FuncInfo.MBB, MSucc, NULL,
805                     SmallVector<MachineOperand, 0>(), DL);
806  }
807  FuncInfo.MBB->addSuccessor(MSucc);
808}
809
810/// SelectFNeg - Emit an FNeg operation.
811///
812bool
813FastISel::SelectFNeg(const User *I) {
814  unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
815  if (OpReg == 0) return false;
816
817  bool OpRegIsKill = hasTrivialKill(I);
818
819  // If the target has ISD::FNEG, use it.
820  EVT VT = TLI.getValueType(I->getType());
821  unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(),
822                                  ISD::FNEG, OpReg, OpRegIsKill);
823  if (ResultReg != 0) {
824    UpdateValueMap(I, ResultReg);
825    return true;
826  }
827
828  // Bitcast the value to integer, twiddle the sign bit with xor,
829  // and then bitcast it back to floating-point.
830  if (VT.getSizeInBits() > 64) return false;
831  EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
832  if (!TLI.isTypeLegal(IntVT))
833    return false;
834
835  unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
836                               ISD::BITCAST, OpReg, OpRegIsKill);
837  if (IntReg == 0)
838    return false;
839
840  unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR,
841                                       IntReg, /*Kill=*/true,
842                                       UINT64_C(1) << (VT.getSizeInBits()-1),
843                                       IntVT.getSimpleVT());
844  if (IntResultReg == 0)
845    return false;
846
847  ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(),
848                         ISD::BITCAST, IntResultReg, /*Kill=*/true);
849  if (ResultReg == 0)
850    return false;
851
852  UpdateValueMap(I, ResultReg);
853  return true;
854}
855
856bool
857FastISel::SelectExtractValue(const User *U) {
858  const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
859  if (!EVI)
860    return false;
861
862  // Make sure we only try to handle extracts with a legal result.  But also
863  // allow i1 because it's easy.
864  EVT RealVT = TLI.getValueType(EVI->getType(), /*AllowUnknown=*/true);
865  if (!RealVT.isSimple())
866    return false;
867  MVT VT = RealVT.getSimpleVT();
868  if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
869    return false;
870
871  const Value *Op0 = EVI->getOperand(0);
872  Type *AggTy = Op0->getType();
873
874  // Get the base result register.
875  unsigned ResultReg;
876  DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
877  if (I != FuncInfo.ValueMap.end())
878    ResultReg = I->second;
879  else if (isa<Instruction>(Op0))
880    ResultReg = FuncInfo.InitializeRegForValue(Op0);
881  else
882    return false; // fast-isel can't handle aggregate constants at the moment
883
884  // Get the actual result register, which is an offset from the base register.
885  unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
886
887  SmallVector<EVT, 4> AggValueVTs;
888  ComputeValueVTs(TLI, AggTy, AggValueVTs);
889
890  for (unsigned i = 0; i < VTIndex; i++)
891    ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
892
893  UpdateValueMap(EVI, ResultReg);
894  return true;
895}
896
897bool
898FastISel::SelectOperator(const User *I, unsigned Opcode) {
899  switch (Opcode) {
900  case Instruction::Add:
901    return SelectBinaryOp(I, ISD::ADD);
902  case Instruction::FAdd:
903    return SelectBinaryOp(I, ISD::FADD);
904  case Instruction::Sub:
905    return SelectBinaryOp(I, ISD::SUB);
906  case Instruction::FSub:
907    // FNeg is currently represented in LLVM IR as a special case of FSub.
908    if (BinaryOperator::isFNeg(I))
909      return SelectFNeg(I);
910    return SelectBinaryOp(I, ISD::FSUB);
911  case Instruction::Mul:
912    return SelectBinaryOp(I, ISD::MUL);
913  case Instruction::FMul:
914    return SelectBinaryOp(I, ISD::FMUL);
915  case Instruction::SDiv:
916    return SelectBinaryOp(I, ISD::SDIV);
917  case Instruction::UDiv:
918    return SelectBinaryOp(I, ISD::UDIV);
919  case Instruction::FDiv:
920    return SelectBinaryOp(I, ISD::FDIV);
921  case Instruction::SRem:
922    return SelectBinaryOp(I, ISD::SREM);
923  case Instruction::URem:
924    return SelectBinaryOp(I, ISD::UREM);
925  case Instruction::FRem:
926    return SelectBinaryOp(I, ISD::FREM);
927  case Instruction::Shl:
928    return SelectBinaryOp(I, ISD::SHL);
929  case Instruction::LShr:
930    return SelectBinaryOp(I, ISD::SRL);
931  case Instruction::AShr:
932    return SelectBinaryOp(I, ISD::SRA);
933  case Instruction::And:
934    return SelectBinaryOp(I, ISD::AND);
935  case Instruction::Or:
936    return SelectBinaryOp(I, ISD::OR);
937  case Instruction::Xor:
938    return SelectBinaryOp(I, ISD::XOR);
939
940  case Instruction::GetElementPtr:
941    return SelectGetElementPtr(I);
942
943  case Instruction::Br: {
944    const BranchInst *BI = cast<BranchInst>(I);
945
946    if (BI->isUnconditional()) {
947      const BasicBlock *LLVMSucc = BI->getSuccessor(0);
948      MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
949      FastEmitBranch(MSucc, BI->getDebugLoc());
950      return true;
951    }
952
953    // Conditional branches are not handed yet.
954    // Halt "fast" selection and bail.
955    return false;
956  }
957
958  case Instruction::Unreachable:
959    // Nothing to emit.
960    return true;
961
962  case Instruction::Alloca:
963    // FunctionLowering has the static-sized case covered.
964    if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
965      return true;
966
967    // Dynamic-sized alloca is not handled yet.
968    return false;
969
970  case Instruction::Call:
971    return SelectCall(I);
972
973  case Instruction::BitCast:
974    return SelectBitCast(I);
975
976  case Instruction::FPToSI:
977    return SelectCast(I, ISD::FP_TO_SINT);
978  case Instruction::ZExt:
979    return SelectCast(I, ISD::ZERO_EXTEND);
980  case Instruction::SExt:
981    return SelectCast(I, ISD::SIGN_EXTEND);
982  case Instruction::Trunc:
983    return SelectCast(I, ISD::TRUNCATE);
984  case Instruction::SIToFP:
985    return SelectCast(I, ISD::SINT_TO_FP);
986
987  case Instruction::IntToPtr: // Deliberate fall-through.
988  case Instruction::PtrToInt: {
989    EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
990    EVT DstVT = TLI.getValueType(I->getType());
991    if (DstVT.bitsGT(SrcVT))
992      return SelectCast(I, ISD::ZERO_EXTEND);
993    if (DstVT.bitsLT(SrcVT))
994      return SelectCast(I, ISD::TRUNCATE);
995    unsigned Reg = getRegForValue(I->getOperand(0));
996    if (Reg == 0) return false;
997    UpdateValueMap(I, Reg);
998    return true;
999  }
1000
1001  case Instruction::ExtractValue:
1002    return SelectExtractValue(I);
1003
1004  case Instruction::PHI:
1005    llvm_unreachable("FastISel shouldn't visit PHI nodes!");
1006
1007  default:
1008    // Unhandled instruction. Halt "fast" selection and bail.
1009    return false;
1010  }
1011}
1012
1013FastISel::FastISel(FunctionLoweringInfo &funcInfo)
1014  : FuncInfo(funcInfo),
1015    MRI(FuncInfo.MF->getRegInfo()),
1016    MFI(*FuncInfo.MF->getFrameInfo()),
1017    MCP(*FuncInfo.MF->getConstantPool()),
1018    TM(FuncInfo.MF->getTarget()),
1019    TD(*TM.getTargetData()),
1020    TII(*TM.getInstrInfo()),
1021    TLI(*TM.getTargetLowering()),
1022    TRI(*TM.getRegisterInfo()) {
1023}
1024
1025FastISel::~FastISel() {}
1026
1027unsigned FastISel::FastEmit_(MVT, MVT,
1028                             unsigned) {
1029  return 0;
1030}
1031
1032unsigned FastISel::FastEmit_r(MVT, MVT,
1033                              unsigned,
1034                              unsigned /*Op0*/, bool /*Op0IsKill*/) {
1035  return 0;
1036}
1037
1038unsigned FastISel::FastEmit_rr(MVT, MVT,
1039                               unsigned,
1040                               unsigned /*Op0*/, bool /*Op0IsKill*/,
1041                               unsigned /*Op1*/, bool /*Op1IsKill*/) {
1042  return 0;
1043}
1044
1045unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
1046  return 0;
1047}
1048
1049unsigned FastISel::FastEmit_f(MVT, MVT,
1050                              unsigned, const ConstantFP * /*FPImm*/) {
1051  return 0;
1052}
1053
1054unsigned FastISel::FastEmit_ri(MVT, MVT,
1055                               unsigned,
1056                               unsigned /*Op0*/, bool /*Op0IsKill*/,
1057                               uint64_t /*Imm*/) {
1058  return 0;
1059}
1060
1061unsigned FastISel::FastEmit_rf(MVT, MVT,
1062                               unsigned,
1063                               unsigned /*Op0*/, bool /*Op0IsKill*/,
1064                               const ConstantFP * /*FPImm*/) {
1065  return 0;
1066}
1067
1068unsigned FastISel::FastEmit_rri(MVT, MVT,
1069                                unsigned,
1070                                unsigned /*Op0*/, bool /*Op0IsKill*/,
1071                                unsigned /*Op1*/, bool /*Op1IsKill*/,
1072                                uint64_t /*Imm*/) {
1073  return 0;
1074}
1075
1076/// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
1077/// to emit an instruction with an immediate operand using FastEmit_ri.
1078/// If that fails, it materializes the immediate into a register and try
1079/// FastEmit_rr instead.
1080unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode,
1081                                unsigned Op0, bool Op0IsKill,
1082                                uint64_t Imm, MVT ImmType) {
1083  // If this is a multiply by a power of two, emit this as a shift left.
1084  if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
1085    Opcode = ISD::SHL;
1086    Imm = Log2_64(Imm);
1087  } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
1088    // div x, 8 -> srl x, 3
1089    Opcode = ISD::SRL;
1090    Imm = Log2_64(Imm);
1091  }
1092
1093  // Horrible hack (to be removed), check to make sure shift amounts are
1094  // in-range.
1095  if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
1096      Imm >= VT.getSizeInBits())
1097    return 0;
1098
1099  // First check if immediate type is legal. If not, we can't use the ri form.
1100  unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
1101  if (ResultReg != 0)
1102    return ResultReg;
1103  unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
1104  if (MaterialReg == 0) {
1105    // This is a bit ugly/slow, but failing here means falling out of
1106    // fast-isel, which would be very slow.
1107    IntegerType *ITy = IntegerType::get(FuncInfo.Fn->getContext(),
1108                                              VT.getSizeInBits());
1109    MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
1110  }
1111  return FastEmit_rr(VT, VT, Opcode,
1112                     Op0, Op0IsKill,
1113                     MaterialReg, /*Kill=*/true);
1114}
1115
1116unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
1117  return MRI.createVirtualRegister(RC);
1118}
1119
1120unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
1121                                 const TargetRegisterClass* RC) {
1122  unsigned ResultReg = createResultReg(RC);
1123  const MCInstrDesc &II = TII.get(MachineInstOpcode);
1124
1125  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg);
1126  return ResultReg;
1127}
1128
1129unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
1130                                  const TargetRegisterClass *RC,
1131                                  unsigned Op0, bool Op0IsKill) {
1132  unsigned ResultReg = createResultReg(RC);
1133  const MCInstrDesc &II = TII.get(MachineInstOpcode);
1134
1135  if (II.getNumDefs() >= 1)
1136    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1137      .addReg(Op0, Op0IsKill * RegState::Kill);
1138  else {
1139    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1140      .addReg(Op0, Op0IsKill * RegState::Kill);
1141    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1142            ResultReg).addReg(II.ImplicitDefs[0]);
1143  }
1144
1145  return ResultReg;
1146}
1147
1148unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
1149                                   const TargetRegisterClass *RC,
1150                                   unsigned Op0, bool Op0IsKill,
1151                                   unsigned Op1, bool Op1IsKill) {
1152  unsigned ResultReg = createResultReg(RC);
1153  const MCInstrDesc &II = TII.get(MachineInstOpcode);
1154
1155  if (II.getNumDefs() >= 1)
1156    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1157      .addReg(Op0, Op0IsKill * RegState::Kill)
1158      .addReg(Op1, Op1IsKill * RegState::Kill);
1159  else {
1160    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1161      .addReg(Op0, Op0IsKill * RegState::Kill)
1162      .addReg(Op1, Op1IsKill * RegState::Kill);
1163    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1164            ResultReg).addReg(II.ImplicitDefs[0]);
1165  }
1166  return ResultReg;
1167}
1168
1169unsigned FastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
1170                                   const TargetRegisterClass *RC,
1171                                   unsigned Op0, bool Op0IsKill,
1172                                   unsigned Op1, bool Op1IsKill,
1173                                   unsigned Op2, bool Op2IsKill) {
1174  unsigned ResultReg = createResultReg(RC);
1175  const MCInstrDesc &II = TII.get(MachineInstOpcode);
1176
1177  if (II.getNumDefs() >= 1)
1178    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1179      .addReg(Op0, Op0IsKill * RegState::Kill)
1180      .addReg(Op1, Op1IsKill * RegState::Kill)
1181      .addReg(Op2, Op2IsKill * RegState::Kill);
1182  else {
1183    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1184      .addReg(Op0, Op0IsKill * RegState::Kill)
1185      .addReg(Op1, Op1IsKill * RegState::Kill)
1186      .addReg(Op2, Op2IsKill * RegState::Kill);
1187    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1188            ResultReg).addReg(II.ImplicitDefs[0]);
1189  }
1190  return ResultReg;
1191}
1192
1193unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
1194                                   const TargetRegisterClass *RC,
1195                                   unsigned Op0, bool Op0IsKill,
1196                                   uint64_t Imm) {
1197  unsigned ResultReg = createResultReg(RC);
1198  const MCInstrDesc &II = TII.get(MachineInstOpcode);
1199
1200  if (II.getNumDefs() >= 1)
1201    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1202      .addReg(Op0, Op0IsKill * RegState::Kill)
1203      .addImm(Imm);
1204  else {
1205    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1206      .addReg(Op0, Op0IsKill * RegState::Kill)
1207      .addImm(Imm);
1208    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1209            ResultReg).addReg(II.ImplicitDefs[0]);
1210  }
1211  return ResultReg;
1212}
1213
1214unsigned FastISel::FastEmitInst_rii(unsigned MachineInstOpcode,
1215                                   const TargetRegisterClass *RC,
1216                                   unsigned Op0, bool Op0IsKill,
1217                                   uint64_t Imm1, uint64_t Imm2) {
1218  unsigned ResultReg = createResultReg(RC);
1219  const MCInstrDesc &II = TII.get(MachineInstOpcode);
1220
1221  if (II.getNumDefs() >= 1)
1222    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1223      .addReg(Op0, Op0IsKill * RegState::Kill)
1224      .addImm(Imm1)
1225      .addImm(Imm2);
1226  else {
1227    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1228      .addReg(Op0, Op0IsKill * RegState::Kill)
1229      .addImm(Imm1)
1230      .addImm(Imm2);
1231    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1232            ResultReg).addReg(II.ImplicitDefs[0]);
1233  }
1234  return ResultReg;
1235}
1236
1237unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
1238                                   const TargetRegisterClass *RC,
1239                                   unsigned Op0, bool Op0IsKill,
1240                                   const ConstantFP *FPImm) {
1241  unsigned ResultReg = createResultReg(RC);
1242  const MCInstrDesc &II = TII.get(MachineInstOpcode);
1243
1244  if (II.getNumDefs() >= 1)
1245    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1246      .addReg(Op0, Op0IsKill * RegState::Kill)
1247      .addFPImm(FPImm);
1248  else {
1249    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1250      .addReg(Op0, Op0IsKill * RegState::Kill)
1251      .addFPImm(FPImm);
1252    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1253            ResultReg).addReg(II.ImplicitDefs[0]);
1254  }
1255  return ResultReg;
1256}
1257
1258unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
1259                                    const TargetRegisterClass *RC,
1260                                    unsigned Op0, bool Op0IsKill,
1261                                    unsigned Op1, bool Op1IsKill,
1262                                    uint64_t Imm) {
1263  unsigned ResultReg = createResultReg(RC);
1264  const MCInstrDesc &II = TII.get(MachineInstOpcode);
1265
1266  if (II.getNumDefs() >= 1)
1267    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1268      .addReg(Op0, Op0IsKill * RegState::Kill)
1269      .addReg(Op1, Op1IsKill * RegState::Kill)
1270      .addImm(Imm);
1271  else {
1272    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1273      .addReg(Op0, Op0IsKill * RegState::Kill)
1274      .addReg(Op1, Op1IsKill * RegState::Kill)
1275      .addImm(Imm);
1276    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1277            ResultReg).addReg(II.ImplicitDefs[0]);
1278  }
1279  return ResultReg;
1280}
1281
1282unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
1283                                  const TargetRegisterClass *RC,
1284                                  uint64_t Imm) {
1285  unsigned ResultReg = createResultReg(RC);
1286  const MCInstrDesc &II = TII.get(MachineInstOpcode);
1287
1288  if (II.getNumDefs() >= 1)
1289    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg).addImm(Imm);
1290  else {
1291    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm);
1292    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1293            ResultReg).addReg(II.ImplicitDefs[0]);
1294  }
1295  return ResultReg;
1296}
1297
1298unsigned FastISel::FastEmitInst_ii(unsigned MachineInstOpcode,
1299                                  const TargetRegisterClass *RC,
1300                                  uint64_t Imm1, uint64_t Imm2) {
1301  unsigned ResultReg = createResultReg(RC);
1302  const MCInstrDesc &II = TII.get(MachineInstOpcode);
1303
1304  if (II.getNumDefs() >= 1)
1305    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1306      .addImm(Imm1).addImm(Imm2);
1307  else {
1308    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm1).addImm(Imm2);
1309    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1310            ResultReg).addReg(II.ImplicitDefs[0]);
1311  }
1312  return ResultReg;
1313}
1314
1315unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT,
1316                                              unsigned Op0, bool Op0IsKill,
1317                                              uint32_t Idx) {
1318  unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1319  assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
1320         "Cannot yet extract from physregs");
1321  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
1322          DL, TII.get(TargetOpcode::COPY), ResultReg)
1323    .addReg(Op0, getKillRegState(Op0IsKill), Idx);
1324  return ResultReg;
1325}
1326
1327/// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
1328/// with all but the least significant bit set to zero.
1329unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
1330  return FastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
1331}
1332
1333/// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
1334/// Emit code to ensure constants are copied into registers when needed.
1335/// Remember the virtual registers that need to be added to the Machine PHI
1336/// nodes as input.  We cannot just directly add them, because expansion
1337/// might result in multiple MBB's for one BB.  As such, the start of the
1338/// BB might correspond to a different MBB than the end.
1339bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
1340  const TerminatorInst *TI = LLVMBB->getTerminator();
1341
1342  SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
1343  unsigned OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
1344
1345  // Check successor nodes' PHI nodes that expect a constant to be available
1346  // from this block.
1347  for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1348    const BasicBlock *SuccBB = TI->getSuccessor(succ);
1349    if (!isa<PHINode>(SuccBB->begin())) continue;
1350    MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
1351
1352    // If this terminator has multiple identical successors (common for
1353    // switches), only handle each succ once.
1354    if (!SuccsHandled.insert(SuccMBB)) continue;
1355
1356    MachineBasicBlock::iterator MBBI = SuccMBB->begin();
1357
1358    // At this point we know that there is a 1-1 correspondence between LLVM PHI
1359    // nodes and Machine PHI nodes, but the incoming operands have not been
1360    // emitted yet.
1361    for (BasicBlock::const_iterator I = SuccBB->begin();
1362         const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1363
1364      // Ignore dead phi's.
1365      if (PN->use_empty()) continue;
1366
1367      // Only handle legal types. Two interesting things to note here. First,
1368      // by bailing out early, we may leave behind some dead instructions,
1369      // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
1370      // own moves. Second, this check is necessary because FastISel doesn't
1371      // use CreateRegs to create registers, so it always creates
1372      // exactly one register for each non-void instruction.
1373      EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
1374      if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
1375        // Handle integer promotions, though, because they're common and easy.
1376        if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
1377          VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
1378        else {
1379          FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1380          return false;
1381        }
1382      }
1383
1384      const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1385
1386      // Set the DebugLoc for the copy. Prefer the location of the operand
1387      // if there is one; use the location of the PHI otherwise.
1388      DL = PN->getDebugLoc();
1389      if (const Instruction *Inst = dyn_cast<Instruction>(PHIOp))
1390        DL = Inst->getDebugLoc();
1391
1392      unsigned Reg = getRegForValue(PHIOp);
1393      if (Reg == 0) {
1394        FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1395        return false;
1396      }
1397      FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
1398      DL = DebugLoc();
1399    }
1400  }
1401
1402  return true;
1403}
1404