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