We actually handle AllocaInst via getRegForValue below just fine.
[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/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"
63 using namespace llvm;
64
65 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
66           "target-independent selector");
67 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
68           "target-specific selector");
69 STATISTIC(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 ///
74 void 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
89 void FastISel::flushLocalValueMap() {
90   LocalValueMap.clear();
91   LastLocalValue = EmitStartPt;
92   recomputeInsertPt();
93 }
94
95 bool 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
121 unsigned 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.
172 unsigned 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
239 unsigned 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.
256 void 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
275 std::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
299 void 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
313 void 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
325 FastISel::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
334 void 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 ///
346 bool 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
447 bool 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
542 bool 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       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
582       return true;
583     }
584
585     const Value *Address = DI->getAddress();
586     if (!Address || isa<UndefValue>(Address)) {
587       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
588       return true;
589     }
590
591     unsigned Reg = 0;
592     unsigned Offset = 0;
593     if (const Argument *Arg = dyn_cast<Argument>(Address)) {
594       // Some arguments' frame index is recorded during argument lowering.
595       Offset = FuncInfo.getArgumentFrameIndex(Arg);
596       if (Offset)
597         Reg = TRI.getFrameRegister(*FuncInfo.MF);
598     }
599     if (!Reg)
600       Reg = getRegForValue(Address);
601
602     if (Reg)
603       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
604               TII.get(TargetOpcode::DBG_VALUE))
605         .addReg(Reg, RegState::Debug).addImm(Offset)
606         .addMetadata(DI->getVariable());
607     return true;
608   }
609   case Intrinsic::dbg_value: {
610     // This form of DBG_VALUE is target-independent.
611     const DbgValueInst *DI = cast<DbgValueInst>(Call);
612     const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
613     const Value *V = DI->getValue();
614     if (!V) {
615       // Currently the optimizer can produce this; insert an undef to
616       // help debugging.  Probably the optimizer should not do this.
617       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
618         .addReg(0U).addImm(DI->getOffset())
619         .addMetadata(DI->getVariable());
620     } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
621       if (CI->getBitWidth() > 64)
622         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
623           .addCImm(CI).addImm(DI->getOffset())
624           .addMetadata(DI->getVariable());
625       else 
626         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
627           .addImm(CI->getZExtValue()).addImm(DI->getOffset())
628           .addMetadata(DI->getVariable());
629     } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
630       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
631         .addFPImm(CF).addImm(DI->getOffset())
632         .addMetadata(DI->getVariable());
633     } else if (unsigned Reg = lookUpRegForValue(V)) {
634       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
635         .addReg(Reg, RegState::Debug).addImm(DI->getOffset())
636         .addMetadata(DI->getVariable());
637     } else {
638       // We can't yet handle anything else here because it would require
639       // generating code, thus altering codegen because of debug info.
640       DEBUG(dbgs() << "Dropping debug info for " << DI);
641     }
642     return true;
643   }
644   case Intrinsic::objectsize: {
645     ConstantInt *CI = cast<ConstantInt>(Call->getArgOperand(1));
646     unsigned long long Res = CI->isZero() ? -1ULL : 0;
647     Constant *ResCI = ConstantInt::get(Call->getType(), Res);
648     unsigned ResultReg = getRegForValue(ResCI);
649     if (ResultReg == 0)
650       return false;
651     UpdateValueMap(Call, ResultReg);
652     return true;
653   }
654   }
655
656   // Usually, it does not make sense to initialize a value,
657   // make an unrelated function call and use the value, because
658   // it tends to be spilled on the stack. So, we move the pointer
659   // to the last local value to the beginning of the block, so that
660   // all the values which have already been materialized,
661   // appear after the call. It also makes sense to skip intrinsics
662   // since they tend to be inlined.
663   if (!isa<IntrinsicInst>(F))
664     flushLocalValueMap();
665
666   // An arbitrary call. Bail.
667   return false;
668 }
669
670 bool FastISel::SelectCast(const User *I, unsigned Opcode) {
671   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
672   EVT DstVT = TLI.getValueType(I->getType());
673
674   if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
675       DstVT == MVT::Other || !DstVT.isSimple())
676     // Unhandled type. Halt "fast" selection and bail.
677     return false;
678
679   // Check if the destination type is legal.
680   if (!TLI.isTypeLegal(DstVT))
681     return false;
682
683   // Check if the source operand is legal.
684   if (!TLI.isTypeLegal(SrcVT))
685     return false;
686
687   unsigned InputReg = getRegForValue(I->getOperand(0));
688   if (!InputReg)
689     // Unhandled operand.  Halt "fast" selection and bail.
690     return false;
691
692   bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
693
694   unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
695                                   DstVT.getSimpleVT(),
696                                   Opcode,
697                                   InputReg, InputRegIsKill);
698   if (!ResultReg)
699     return false;
700
701   UpdateValueMap(I, ResultReg);
702   return true;
703 }
704
705 bool FastISel::SelectBitCast(const User *I) {
706   // If the bitcast doesn't change the type, just use the operand value.
707   if (I->getType() == I->getOperand(0)->getType()) {
708     unsigned Reg = getRegForValue(I->getOperand(0));
709     if (Reg == 0)
710       return false;
711     UpdateValueMap(I, Reg);
712     return true;
713   }
714
715   // Bitcasts of other values become reg-reg copies or BITCAST operators.
716   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
717   EVT DstVT = TLI.getValueType(I->getType());
718
719   if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
720       DstVT == MVT::Other || !DstVT.isSimple() ||
721       !TLI.isTypeLegal(SrcVT) || !TLI.isTypeLegal(DstVT))
722     // Unhandled type. Halt "fast" selection and bail.
723     return false;
724
725   unsigned Op0 = getRegForValue(I->getOperand(0));
726   if (Op0 == 0)
727     // Unhandled operand. Halt "fast" selection and bail.
728     return false;
729
730   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
731
732   // First, try to perform the bitcast by inserting a reg-reg copy.
733   unsigned ResultReg = 0;
734   if (SrcVT.getSimpleVT() == DstVT.getSimpleVT()) {
735     const TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
736     const TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
737     // Don't attempt a cross-class copy. It will likely fail.
738     if (SrcClass == DstClass) {
739       ResultReg = createResultReg(DstClass);
740       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
741               ResultReg).addReg(Op0);
742     }
743   }
744
745   // If the reg-reg copy failed, select a BITCAST opcode.
746   if (!ResultReg)
747     ResultReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
748                            ISD::BITCAST, Op0, Op0IsKill);
749
750   if (!ResultReg)
751     return false;
752
753   UpdateValueMap(I, ResultReg);
754   return true;
755 }
756
757 bool
758 FastISel::SelectInstruction(const Instruction *I) {
759   // Just before the terminator instruction, insert instructions to
760   // feed PHI nodes in successor blocks.
761   if (isa<TerminatorInst>(I))
762     if (!HandlePHINodesInSuccessorBlocks(I->getParent()))
763       return false;
764
765   DL = I->getDebugLoc();
766
767   MachineBasicBlock::iterator SavedInsertPt = FuncInfo.InsertPt;
768
769   // First, try doing target-independent selection.
770   if (SelectOperator(I, I->getOpcode())) {
771     ++NumFastIselSuccessIndependent;
772     DL = DebugLoc();
773     return true;
774   }
775   // Remove dead code.  However, ignore call instructions since we've flushed 
776   // the local value map and recomputed the insert point.
777   if (!isa<CallInst>(I)) {
778     recomputeInsertPt();
779     if (SavedInsertPt != FuncInfo.InsertPt)
780       removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
781   }
782
783   // Next, try calling the target to attempt to handle the instruction.
784   SavedInsertPt = FuncInfo.InsertPt;
785   if (TargetSelectInstruction(I)) {
786     ++NumFastIselSuccessTarget;
787     DL = DebugLoc();
788     return true;
789   }
790   // Check for dead code and remove as necessary.
791   recomputeInsertPt();
792   if (SavedInsertPt != FuncInfo.InsertPt)
793     removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
794
795   DL = DebugLoc();
796   return false;
797 }
798
799 /// FastEmitBranch - Emit an unconditional branch to the given block,
800 /// unless it is the immediate (fall-through) successor, and update
801 /// the CFG.
802 void
803 FastISel::FastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DL) {
804   if (FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
805     // The unconditional fall-through case, which needs no instructions.
806   } else {
807     // The unconditional branch case.
808     TII.InsertBranch(*FuncInfo.MBB, MSucc, NULL,
809                      SmallVector<MachineOperand, 0>(), DL);
810   }
811   FuncInfo.MBB->addSuccessor(MSucc);
812 }
813
814 /// SelectFNeg - Emit an FNeg operation.
815 ///
816 bool
817 FastISel::SelectFNeg(const User *I) {
818   unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
819   if (OpReg == 0) return false;
820
821   bool OpRegIsKill = hasTrivialKill(I);
822
823   // If the target has ISD::FNEG, use it.
824   EVT VT = TLI.getValueType(I->getType());
825   unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(),
826                                   ISD::FNEG, OpReg, OpRegIsKill);
827   if (ResultReg != 0) {
828     UpdateValueMap(I, ResultReg);
829     return true;
830   }
831
832   // Bitcast the value to integer, twiddle the sign bit with xor,
833   // and then bitcast it back to floating-point.
834   if (VT.getSizeInBits() > 64) return false;
835   EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
836   if (!TLI.isTypeLegal(IntVT))
837     return false;
838
839   unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
840                                ISD::BITCAST, OpReg, OpRegIsKill);
841   if (IntReg == 0)
842     return false;
843
844   unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR,
845                                        IntReg, /*Kill=*/true,
846                                        UINT64_C(1) << (VT.getSizeInBits()-1),
847                                        IntVT.getSimpleVT());
848   if (IntResultReg == 0)
849     return false;
850
851   ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(),
852                          ISD::BITCAST, IntResultReg, /*Kill=*/true);
853   if (ResultReg == 0)
854     return false;
855
856   UpdateValueMap(I, ResultReg);
857   return true;
858 }
859
860 bool
861 FastISel::SelectExtractValue(const User *U) {
862   const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
863   if (!EVI)
864     return false;
865
866   // Make sure we only try to handle extracts with a legal result.  But also
867   // allow i1 because it's easy.
868   EVT RealVT = TLI.getValueType(EVI->getType(), /*AllowUnknown=*/true);
869   if (!RealVT.isSimple())
870     return false;
871   MVT VT = RealVT.getSimpleVT();
872   if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
873     return false;
874
875   const Value *Op0 = EVI->getOperand(0);
876   Type *AggTy = Op0->getType();
877
878   // Get the base result register.
879   unsigned ResultReg;
880   DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
881   if (I != FuncInfo.ValueMap.end())
882     ResultReg = I->second;
883   else if (isa<Instruction>(Op0))
884     ResultReg = FuncInfo.InitializeRegForValue(Op0);
885   else
886     return false; // fast-isel can't handle aggregate constants at the moment
887
888   // Get the actual result register, which is an offset from the base register.
889   unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
890
891   SmallVector<EVT, 4> AggValueVTs;
892   ComputeValueVTs(TLI, AggTy, AggValueVTs);
893
894   for (unsigned i = 0; i < VTIndex; i++)
895     ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
896
897   UpdateValueMap(EVI, ResultReg);
898   return true;
899 }
900
901 bool
902 FastISel::SelectOperator(const User *I, unsigned Opcode) {
903   switch (Opcode) {
904   case Instruction::Add:
905     return SelectBinaryOp(I, ISD::ADD);
906   case Instruction::FAdd:
907     return SelectBinaryOp(I, ISD::FADD);
908   case Instruction::Sub:
909     return SelectBinaryOp(I, ISD::SUB);
910   case Instruction::FSub:
911     // FNeg is currently represented in LLVM IR as a special case of FSub.
912     if (BinaryOperator::isFNeg(I))
913       return SelectFNeg(I);
914     return SelectBinaryOp(I, ISD::FSUB);
915   case Instruction::Mul:
916     return SelectBinaryOp(I, ISD::MUL);
917   case Instruction::FMul:
918     return SelectBinaryOp(I, ISD::FMUL);
919   case Instruction::SDiv:
920     return SelectBinaryOp(I, ISD::SDIV);
921   case Instruction::UDiv:
922     return SelectBinaryOp(I, ISD::UDIV);
923   case Instruction::FDiv:
924     return SelectBinaryOp(I, ISD::FDIV);
925   case Instruction::SRem:
926     return SelectBinaryOp(I, ISD::SREM);
927   case Instruction::URem:
928     return SelectBinaryOp(I, ISD::UREM);
929   case Instruction::FRem:
930     return SelectBinaryOp(I, ISD::FREM);
931   case Instruction::Shl:
932     return SelectBinaryOp(I, ISD::SHL);
933   case Instruction::LShr:
934     return SelectBinaryOp(I, ISD::SRL);
935   case Instruction::AShr:
936     return SelectBinaryOp(I, ISD::SRA);
937   case Instruction::And:
938     return SelectBinaryOp(I, ISD::AND);
939   case Instruction::Or:
940     return SelectBinaryOp(I, ISD::OR);
941   case Instruction::Xor:
942     return SelectBinaryOp(I, ISD::XOR);
943
944   case Instruction::GetElementPtr:
945     return SelectGetElementPtr(I);
946
947   case Instruction::Br: {
948     const BranchInst *BI = cast<BranchInst>(I);
949
950     if (BI->isUnconditional()) {
951       const BasicBlock *LLVMSucc = BI->getSuccessor(0);
952       MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
953       FastEmitBranch(MSucc, BI->getDebugLoc());
954       return true;
955     }
956
957     // Conditional branches are not handed yet.
958     // Halt "fast" selection and bail.
959     return false;
960   }
961
962   case Instruction::Unreachable:
963     // Nothing to emit.
964     return true;
965
966   case Instruction::Alloca:
967     // FunctionLowering has the static-sized case covered.
968     if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
969       return true;
970
971     // Dynamic-sized alloca is not handled yet.
972     return false;
973
974   case Instruction::Call:
975     return SelectCall(I);
976
977   case Instruction::BitCast:
978     return SelectBitCast(I);
979
980   case Instruction::FPToSI:
981     return SelectCast(I, ISD::FP_TO_SINT);
982   case Instruction::ZExt:
983     return SelectCast(I, ISD::ZERO_EXTEND);
984   case Instruction::SExt:
985     return SelectCast(I, ISD::SIGN_EXTEND);
986   case Instruction::Trunc:
987     return SelectCast(I, ISD::TRUNCATE);
988   case Instruction::SIToFP:
989     return SelectCast(I, ISD::SINT_TO_FP);
990
991   case Instruction::IntToPtr: // Deliberate fall-through.
992   case Instruction::PtrToInt: {
993     EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
994     EVT DstVT = TLI.getValueType(I->getType());
995     if (DstVT.bitsGT(SrcVT))
996       return SelectCast(I, ISD::ZERO_EXTEND);
997     if (DstVT.bitsLT(SrcVT))
998       return SelectCast(I, ISD::TRUNCATE);
999     unsigned Reg = getRegForValue(I->getOperand(0));
1000     if (Reg == 0) return false;
1001     UpdateValueMap(I, Reg);
1002     return true;
1003   }
1004
1005   case Instruction::ExtractValue:
1006     return SelectExtractValue(I);
1007
1008   case Instruction::PHI:
1009     llvm_unreachable("FastISel shouldn't visit PHI nodes!");
1010
1011   default:
1012     // Unhandled instruction. Halt "fast" selection and bail.
1013     return false;
1014   }
1015 }
1016
1017 FastISel::FastISel(FunctionLoweringInfo &funcInfo)
1018   : FuncInfo(funcInfo),
1019     MRI(FuncInfo.MF->getRegInfo()),
1020     MFI(*FuncInfo.MF->getFrameInfo()),
1021     MCP(*FuncInfo.MF->getConstantPool()),
1022     TM(FuncInfo.MF->getTarget()),
1023     TD(*TM.getTargetData()),
1024     TII(*TM.getInstrInfo()),
1025     TLI(*TM.getTargetLowering()),
1026     TRI(*TM.getRegisterInfo()) {
1027 }
1028
1029 FastISel::~FastISel() {}
1030
1031 unsigned FastISel::FastEmit_(MVT, MVT,
1032                              unsigned) {
1033   return 0;
1034 }
1035
1036 unsigned FastISel::FastEmit_r(MVT, MVT,
1037                               unsigned,
1038                               unsigned /*Op0*/, bool /*Op0IsKill*/) {
1039   return 0;
1040 }
1041
1042 unsigned FastISel::FastEmit_rr(MVT, MVT,
1043                                unsigned,
1044                                unsigned /*Op0*/, bool /*Op0IsKill*/,
1045                                unsigned /*Op1*/, bool /*Op1IsKill*/) {
1046   return 0;
1047 }
1048
1049 unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
1050   return 0;
1051 }
1052
1053 unsigned FastISel::FastEmit_f(MVT, MVT,
1054                               unsigned, const ConstantFP * /*FPImm*/) {
1055   return 0;
1056 }
1057
1058 unsigned FastISel::FastEmit_ri(MVT, MVT,
1059                                unsigned,
1060                                unsigned /*Op0*/, bool /*Op0IsKill*/,
1061                                uint64_t /*Imm*/) {
1062   return 0;
1063 }
1064
1065 unsigned FastISel::FastEmit_rf(MVT, MVT,
1066                                unsigned,
1067                                unsigned /*Op0*/, bool /*Op0IsKill*/,
1068                                const ConstantFP * /*FPImm*/) {
1069   return 0;
1070 }
1071
1072 unsigned FastISel::FastEmit_rri(MVT, MVT,
1073                                 unsigned,
1074                                 unsigned /*Op0*/, bool /*Op0IsKill*/,
1075                                 unsigned /*Op1*/, bool /*Op1IsKill*/,
1076                                 uint64_t /*Imm*/) {
1077   return 0;
1078 }
1079
1080 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
1081 /// to emit an instruction with an immediate operand using FastEmit_ri.
1082 /// If that fails, it materializes the immediate into a register and try
1083 /// FastEmit_rr instead.
1084 unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode,
1085                                 unsigned Op0, bool Op0IsKill,
1086                                 uint64_t Imm, MVT ImmType) {
1087   // If this is a multiply by a power of two, emit this as a shift left.
1088   if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
1089     Opcode = ISD::SHL;
1090     Imm = Log2_64(Imm);
1091   } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
1092     // div x, 8 -> srl x, 3
1093     Opcode = ISD::SRL;
1094     Imm = Log2_64(Imm);
1095   }
1096
1097   // Horrible hack (to be removed), check to make sure shift amounts are
1098   // in-range.
1099   if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
1100       Imm >= VT.getSizeInBits())
1101     return 0;
1102
1103   // First check if immediate type is legal. If not, we can't use the ri form.
1104   unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
1105   if (ResultReg != 0)
1106     return ResultReg;
1107   unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
1108   if (MaterialReg == 0) {
1109     // This is a bit ugly/slow, but failing here means falling out of
1110     // fast-isel, which would be very slow.
1111     IntegerType *ITy = IntegerType::get(FuncInfo.Fn->getContext(),
1112                                               VT.getSizeInBits());
1113     MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
1114   }
1115   return FastEmit_rr(VT, VT, Opcode,
1116                      Op0, Op0IsKill,
1117                      MaterialReg, /*Kill=*/true);
1118 }
1119
1120 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
1121   return MRI.createVirtualRegister(RC);
1122 }
1123
1124 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
1125                                  const TargetRegisterClass* RC) {
1126   unsigned ResultReg = createResultReg(RC);
1127   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1128
1129   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg);
1130   return ResultReg;
1131 }
1132
1133 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
1134                                   const TargetRegisterClass *RC,
1135                                   unsigned Op0, bool Op0IsKill) {
1136   unsigned ResultReg = createResultReg(RC);
1137   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1138
1139   if (II.getNumDefs() >= 1)
1140     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1141       .addReg(Op0, Op0IsKill * RegState::Kill);
1142   else {
1143     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1144       .addReg(Op0, Op0IsKill * RegState::Kill);
1145     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1146             ResultReg).addReg(II.ImplicitDefs[0]);
1147   }
1148
1149   return ResultReg;
1150 }
1151
1152 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
1153                                    const TargetRegisterClass *RC,
1154                                    unsigned Op0, bool Op0IsKill,
1155                                    unsigned Op1, bool Op1IsKill) {
1156   unsigned ResultReg = createResultReg(RC);
1157   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1158
1159   if (II.getNumDefs() >= 1)
1160     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1161       .addReg(Op0, Op0IsKill * RegState::Kill)
1162       .addReg(Op1, Op1IsKill * RegState::Kill);
1163   else {
1164     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1165       .addReg(Op0, Op0IsKill * RegState::Kill)
1166       .addReg(Op1, Op1IsKill * RegState::Kill);
1167     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1168             ResultReg).addReg(II.ImplicitDefs[0]);
1169   }
1170   return ResultReg;
1171 }
1172
1173 unsigned FastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
1174                                    const TargetRegisterClass *RC,
1175                                    unsigned Op0, bool Op0IsKill,
1176                                    unsigned Op1, bool Op1IsKill,
1177                                    unsigned Op2, bool Op2IsKill) {
1178   unsigned ResultReg = createResultReg(RC);
1179   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1180
1181   if (II.getNumDefs() >= 1)
1182     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1183       .addReg(Op0, Op0IsKill * RegState::Kill)
1184       .addReg(Op1, Op1IsKill * RegState::Kill)
1185       .addReg(Op2, Op2IsKill * RegState::Kill);
1186   else {
1187     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1188       .addReg(Op0, Op0IsKill * RegState::Kill)
1189       .addReg(Op1, Op1IsKill * RegState::Kill)
1190       .addReg(Op2, Op2IsKill * RegState::Kill);
1191     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1192             ResultReg).addReg(II.ImplicitDefs[0]);
1193   }
1194   return ResultReg;
1195 }
1196
1197 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
1198                                    const TargetRegisterClass *RC,
1199                                    unsigned Op0, bool Op0IsKill,
1200                                    uint64_t Imm) {
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       .addImm(Imm);
1208   else {
1209     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1210       .addReg(Op0, Op0IsKill * RegState::Kill)
1211       .addImm(Imm);
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_rii(unsigned MachineInstOpcode,
1219                                    const TargetRegisterClass *RC,
1220                                    unsigned Op0, bool Op0IsKill,
1221                                    uint64_t Imm1, uint64_t Imm2) {
1222   unsigned ResultReg = createResultReg(RC);
1223   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1224
1225   if (II.getNumDefs() >= 1)
1226     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1227       .addReg(Op0, Op0IsKill * RegState::Kill)
1228       .addImm(Imm1)
1229       .addImm(Imm2);
1230   else {
1231     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1232       .addReg(Op0, Op0IsKill * RegState::Kill)
1233       .addImm(Imm1)
1234       .addImm(Imm2);
1235     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1236             ResultReg).addReg(II.ImplicitDefs[0]);
1237   }
1238   return ResultReg;
1239 }
1240
1241 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
1242                                    const TargetRegisterClass *RC,
1243                                    unsigned Op0, bool Op0IsKill,
1244                                    const ConstantFP *FPImm) {
1245   unsigned ResultReg = createResultReg(RC);
1246   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1247
1248   if (II.getNumDefs() >= 1)
1249     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1250       .addReg(Op0, Op0IsKill * RegState::Kill)
1251       .addFPImm(FPImm);
1252   else {
1253     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1254       .addReg(Op0, Op0IsKill * RegState::Kill)
1255       .addFPImm(FPImm);
1256     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1257             ResultReg).addReg(II.ImplicitDefs[0]);
1258   }
1259   return ResultReg;
1260 }
1261
1262 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
1263                                     const TargetRegisterClass *RC,
1264                                     unsigned Op0, bool Op0IsKill,
1265                                     unsigned Op1, bool Op1IsKill,
1266                                     uint64_t Imm) {
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       .addReg(Op1, Op1IsKill * RegState::Kill)
1274       .addImm(Imm);
1275   else {
1276     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1277       .addReg(Op0, Op0IsKill * RegState::Kill)
1278       .addReg(Op1, Op1IsKill * RegState::Kill)
1279       .addImm(Imm);
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_i(unsigned MachineInstOpcode,
1287                                   const TargetRegisterClass *RC,
1288                                   uint64_t Imm) {
1289   unsigned ResultReg = createResultReg(RC);
1290   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1291
1292   if (II.getNumDefs() >= 1)
1293     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg).addImm(Imm);
1294   else {
1295     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm);
1296     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1297             ResultReg).addReg(II.ImplicitDefs[0]);
1298   }
1299   return ResultReg;
1300 }
1301
1302 unsigned FastISel::FastEmitInst_ii(unsigned MachineInstOpcode,
1303                                   const TargetRegisterClass *RC,
1304                                   uint64_t Imm1, uint64_t Imm2) {
1305   unsigned ResultReg = createResultReg(RC);
1306   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1307
1308   if (II.getNumDefs() >= 1)
1309     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1310       .addImm(Imm1).addImm(Imm2);
1311   else {
1312     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm1).addImm(Imm2);
1313     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1314             ResultReg).addReg(II.ImplicitDefs[0]);
1315   }
1316   return ResultReg;
1317 }
1318
1319 unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT,
1320                                               unsigned Op0, bool Op0IsKill,
1321                                               uint32_t Idx) {
1322   unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1323   assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
1324          "Cannot yet extract from physregs");
1325   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
1326           DL, TII.get(TargetOpcode::COPY), ResultReg)
1327     .addReg(Op0, getKillRegState(Op0IsKill), Idx);
1328   return ResultReg;
1329 }
1330
1331 /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
1332 /// with all but the least significant bit set to zero.
1333 unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
1334   return FastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
1335 }
1336
1337 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
1338 /// Emit code to ensure constants are copied into registers when needed.
1339 /// Remember the virtual registers that need to be added to the Machine PHI
1340 /// nodes as input.  We cannot just directly add them, because expansion
1341 /// might result in multiple MBB's for one BB.  As such, the start of the
1342 /// BB might correspond to a different MBB than the end.
1343 bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
1344   const TerminatorInst *TI = LLVMBB->getTerminator();
1345
1346   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
1347   unsigned OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
1348
1349   // Check successor nodes' PHI nodes that expect a constant to be available
1350   // from this block.
1351   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1352     const BasicBlock *SuccBB = TI->getSuccessor(succ);
1353     if (!isa<PHINode>(SuccBB->begin())) continue;
1354     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
1355
1356     // If this terminator has multiple identical successors (common for
1357     // switches), only handle each succ once.
1358     if (!SuccsHandled.insert(SuccMBB)) continue;
1359
1360     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
1361
1362     // At this point we know that there is a 1-1 correspondence between LLVM PHI
1363     // nodes and Machine PHI nodes, but the incoming operands have not been
1364     // emitted yet.
1365     for (BasicBlock::const_iterator I = SuccBB->begin();
1366          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1367
1368       // Ignore dead phi's.
1369       if (PN->use_empty()) continue;
1370
1371       // Only handle legal types. Two interesting things to note here. First,
1372       // by bailing out early, we may leave behind some dead instructions,
1373       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
1374       // own moves. Second, this check is necessary because FastISel doesn't
1375       // use CreateRegs to create registers, so it always creates
1376       // exactly one register for each non-void instruction.
1377       EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
1378       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
1379         // Handle integer promotions, though, because they're common and easy.
1380         if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
1381           VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
1382         else {
1383           FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1384           return false;
1385         }
1386       }
1387
1388       const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1389
1390       // Set the DebugLoc for the copy. Prefer the location of the operand
1391       // if there is one; use the location of the PHI otherwise.
1392       DL = PN->getDebugLoc();
1393       if (const Instruction *Inst = dyn_cast<Instruction>(PHIOp))
1394         DL = Inst->getDebugLoc();
1395
1396       unsigned Reg = getRegForValue(PHIOp);
1397       if (Reg == 0) {
1398         FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1399         return false;
1400       }
1401       FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
1402       DL = DebugLoc();
1403     }
1404   }
1405
1406   return true;
1407 }