Add a "loses information" return value to APFloat::convert
[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 (e.g. calls) are not
15 // supported. It is also not intended to be able to do much optimization,
16 // except in a few cases where doing optimizations reduces overall compile
17 // time (e.g. folding constants into immediate fields, because it's cheap
18 // and it reduces the number of instructions later phases have to examine).
19 //
20 // "Fast" instruction selection is able to fail gracefully and transfer
21 // control to the SelectionDAG selector for operations that it doesn't
22 // support. In many cases, this allows us to avoid duplicating a lot of
23 // the complicated lowering logic that SelectionDAG currently has.
24 //
25 // The intended use for "fast" instruction selection is "-O0" mode
26 // compilation, where the quality of the generated code is irrelevant when
27 // weighed against the speed at which the code can be generated. Also,
28 // at -O0, the LLVM optimizers are not running, and this makes the
29 // compile time of codegen a much higher portion of the overall compile
30 // time. Despite its limitations, "fast" instruction selection is able to
31 // handle enough code on its own to provide noticeable overall speedups
32 // in -O0 compiles.
33 //
34 // Basic operations are supported in a target-independent way, by reading
35 // the same instruction descriptions that the SelectionDAG selector reads,
36 // and identifying simple arithmetic operations that can be directly selected
37 // from simple operators. More complicated operations currently require
38 // target-specific code.
39 //
40 //===----------------------------------------------------------------------===//
41
42 #include "llvm/Function.h"
43 #include "llvm/GlobalVariable.h"
44 #include "llvm/Instructions.h"
45 #include "llvm/IntrinsicInst.h"
46 #include "llvm/CodeGen/FastISel.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineModuleInfo.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/Target/TargetData.h"
51 #include "llvm/Target/TargetInstrInfo.h"
52 #include "llvm/Target/TargetLowering.h"
53 #include "llvm/Target/TargetMachine.h"
54 using namespace llvm;
55
56 unsigned FastISel::getRegForValue(Value *V) {
57   // Look up the value to see if we already have a register for it. We
58   // cache values defined by Instructions across blocks, and other values
59   // only locally. This is because Instructions already have the SSA
60   // def-dominatess-use requirement enforced.
61   if (ValueMap.count(V))
62     return ValueMap[V];
63   unsigned Reg = LocalValueMap[V];
64   if (Reg != 0)
65     return Reg;
66
67   MVT::SimpleValueType VT = TLI.getValueType(V->getType()).getSimpleVT();
68
69   // Ignore illegal types.
70   if (!TLI.isTypeLegal(VT)) {
71     // Promote MVT::i1 to a legal type though, because it's common and easy.
72     if (VT == MVT::i1)
73       VT = TLI.getTypeToTransformTo(VT).getSimpleVT();
74     else
75       return 0;
76   }
77
78   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
79     if (CI->getValue().getActiveBits() <= 64)
80       Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
81   } else if (isa<AllocaInst>(V)) {
82     Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
83   } else if (isa<ConstantPointerNull>(V)) {
84     // Translate this as an integer zero so that it can be
85     // local-CSE'd with actual integer zeros.
86     Reg = getRegForValue(Constant::getNullValue(TD.getIntPtrType()));
87   } else if (ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
88     Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
89
90     if (!Reg) {
91       const APFloat &Flt = CF->getValueAPF();
92       MVT IntVT = TLI.getPointerTy();
93
94       uint64_t x[2];
95       uint32_t IntBitWidth = IntVT.getSizeInBits();
96       bool isExact;
97       (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
98                                 APFloat::rmTowardZero, &isExact);
99       if (isExact) {
100         APInt IntVal(IntBitWidth, 2, x);
101
102         unsigned IntegerReg = getRegForValue(ConstantInt::get(IntVal));
103         if (IntegerReg != 0)
104           Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, IntegerReg);
105       }
106     }
107   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
108     if (!SelectOperator(CE, CE->getOpcode())) return 0;
109     Reg = LocalValueMap[CE];
110   } else if (isa<UndefValue>(V)) {
111     Reg = createResultReg(TLI.getRegClassFor(VT));
112     BuildMI(MBB, TII.get(TargetInstrInfo::IMPLICIT_DEF), Reg);
113   }
114   
115   // If target-independent code couldn't handle the value, give target-specific
116   // code a try.
117   if (!Reg && isa<Constant>(V))
118     Reg = TargetMaterializeConstant(cast<Constant>(V));
119   
120   // Don't cache constant materializations in the general ValueMap.
121   // To do so would require tracking what uses they dominate.
122   if (Reg != 0)
123     LocalValueMap[V] = Reg;
124   return Reg;
125 }
126
127 unsigned FastISel::lookUpRegForValue(Value *V) {
128   // Look up the value to see if we already have a register for it. We
129   // cache values defined by Instructions across blocks, and other values
130   // only locally. This is because Instructions already have the SSA
131   // def-dominatess-use requirement enforced.
132   if (ValueMap.count(V))
133     return ValueMap[V];
134   return LocalValueMap[V];
135 }
136
137 /// UpdateValueMap - Update the value map to include the new mapping for this
138 /// instruction, or insert an extra copy to get the result in a previous
139 /// determined register.
140 /// NOTE: This is only necessary because we might select a block that uses
141 /// a value before we select the block that defines the value.  It might be
142 /// possible to fix this by selecting blocks in reverse postorder.
143 void FastISel::UpdateValueMap(Value* I, unsigned Reg) {
144   if (!isa<Instruction>(I)) {
145     LocalValueMap[I] = Reg;
146     return;
147   }
148   if (!ValueMap.count(I))
149     ValueMap[I] = Reg;
150   else
151     TII.copyRegToReg(*MBB, MBB->end(), ValueMap[I],
152                      Reg, MRI.getRegClass(Reg), MRI.getRegClass(Reg));
153 }
154
155 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
156 /// which has an opcode which directly corresponds to the given ISD opcode.
157 ///
158 bool FastISel::SelectBinaryOp(User *I, ISD::NodeType ISDOpcode) {
159   MVT VT = MVT::getMVT(I->getType(), /*HandleUnknown=*/true);
160   if (VT == MVT::Other || !VT.isSimple())
161     // Unhandled type. Halt "fast" selection and bail.
162     return false;
163
164   // We only handle legal types. For example, on x86-32 the instruction
165   // selector contains all of the 64-bit instructions from x86-64,
166   // under the assumption that i64 won't be used if the target doesn't
167   // support it.
168   if (!TLI.isTypeLegal(VT)) {
169     // MVT::i1 is special. Allow AND, OR, or XOR because they
170     // don't require additional zeroing, which makes them easy.
171     if (VT == MVT::i1 &&
172         (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
173          ISDOpcode == ISD::XOR))
174       VT = TLI.getTypeToTransformTo(VT);
175     else
176       return false;
177   }
178
179   unsigned Op0 = getRegForValue(I->getOperand(0));
180   if (Op0 == 0)
181     // Unhandled operand. Halt "fast" selection and bail.
182     return false;
183
184   // Check if the second operand is a constant and handle it appropriately.
185   if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
186     unsigned ResultReg = FastEmit_ri(VT.getSimpleVT(), VT.getSimpleVT(),
187                                      ISDOpcode, Op0, CI->getZExtValue());
188     if (ResultReg != 0) {
189       // We successfully emitted code for the given LLVM Instruction.
190       UpdateValueMap(I, ResultReg);
191       return true;
192     }
193   }
194
195   // Check if the second operand is a constant float.
196   if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
197     unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
198                                      ISDOpcode, Op0, CF);
199     if (ResultReg != 0) {
200       // We successfully emitted code for the given LLVM Instruction.
201       UpdateValueMap(I, ResultReg);
202       return true;
203     }
204   }
205
206   unsigned Op1 = getRegForValue(I->getOperand(1));
207   if (Op1 == 0)
208     // Unhandled operand. Halt "fast" selection and bail.
209     return false;
210
211   // Now we have both operands in registers. Emit the instruction.
212   unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
213                                    ISDOpcode, Op0, Op1);
214   if (ResultReg == 0)
215     // Target-specific code wasn't able to find a machine opcode for
216     // the given ISD opcode and type. Halt "fast" selection and bail.
217     return false;
218
219   // We successfully emitted code for the given LLVM Instruction.
220   UpdateValueMap(I, ResultReg);
221   return true;
222 }
223
224 bool FastISel::SelectGetElementPtr(User *I) {
225   unsigned N = getRegForValue(I->getOperand(0));
226   if (N == 0)
227     // Unhandled operand. Halt "fast" selection and bail.
228     return false;
229
230   const Type *Ty = I->getOperand(0)->getType();
231   MVT::SimpleValueType VT = TLI.getPointerTy().getSimpleVT();
232   for (GetElementPtrInst::op_iterator OI = I->op_begin()+1, E = I->op_end();
233        OI != E; ++OI) {
234     Value *Idx = *OI;
235     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
236       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
237       if (Field) {
238         // N = N + Offset
239         uint64_t Offs = TD.getStructLayout(StTy)->getElementOffset(Field);
240         // FIXME: This can be optimized by combining the add with a
241         // subsequent one.
242         N = FastEmit_ri_(VT, ISD::ADD, N, Offs, VT);
243         if (N == 0)
244           // Unhandled operand. Halt "fast" selection and bail.
245           return false;
246       }
247       Ty = StTy->getElementType(Field);
248     } else {
249       Ty = cast<SequentialType>(Ty)->getElementType();
250
251       // If this is a constant subscript, handle it quickly.
252       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
253         if (CI->getZExtValue() == 0) continue;
254         uint64_t Offs = 
255           TD.getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
256         N = FastEmit_ri_(VT, ISD::ADD, N, Offs, VT);
257         if (N == 0)
258           // Unhandled operand. Halt "fast" selection and bail.
259           return false;
260         continue;
261       }
262       
263       // N = N + Idx * ElementSize;
264       uint64_t ElementSize = TD.getABITypeSize(Ty);
265       unsigned IdxN = getRegForValue(Idx);
266       if (IdxN == 0)
267         // Unhandled operand. Halt "fast" selection and bail.
268         return false;
269
270       // If the index is smaller or larger than intptr_t, truncate or extend
271       // it.
272       MVT IdxVT = MVT::getMVT(Idx->getType(), /*HandleUnknown=*/false);
273       if (IdxVT.bitsLT(VT))
274         IdxN = FastEmit_r(IdxVT.getSimpleVT(), VT, ISD::SIGN_EXTEND, IdxN);
275       else if (IdxVT.bitsGT(VT))
276         IdxN = FastEmit_r(IdxVT.getSimpleVT(), VT, ISD::TRUNCATE, IdxN);
277       if (IdxN == 0)
278         // Unhandled operand. Halt "fast" selection and bail.
279         return false;
280
281       if (ElementSize != 1) {
282         IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, ElementSize, VT);
283         if (IdxN == 0)
284           // Unhandled operand. Halt "fast" selection and bail.
285           return false;
286       }
287       N = FastEmit_rr(VT, VT, ISD::ADD, N, IdxN);
288       if (N == 0)
289         // Unhandled operand. Halt "fast" selection and bail.
290         return false;
291     }
292   }
293
294   // We successfully emitted code for the given LLVM Instruction.
295   UpdateValueMap(I, N);
296   return true;
297 }
298
299 bool FastISel::SelectCall(User *I) {
300   Function *F = cast<CallInst>(I)->getCalledFunction();
301   if (!F) return false;
302
303   unsigned IID = F->getIntrinsicID();
304   switch (IID) {
305   default: break;
306   case Intrinsic::dbg_stoppoint: {
307     DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
308     if (MMI && SPI->getContext() && MMI->Verify(SPI->getContext())) {
309       DebugInfoDesc *DD = MMI->getDescFor(SPI->getContext());
310       assert(DD && "Not a debug information descriptor");
311       const CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
312       unsigned SrcFile = MMI->RecordSource(CompileUnit);
313       unsigned Line = SPI->getLine();
314       unsigned Col = SPI->getColumn();
315       unsigned ID = MMI->RecordSourceLine(Line, Col, SrcFile);
316       const TargetInstrDesc &II = TII.get(TargetInstrInfo::DBG_LABEL);
317       BuildMI(MBB, II).addImm(ID);
318     }
319     return true;
320   }
321   case Intrinsic::dbg_region_start: {
322     DbgRegionStartInst *RSI = cast<DbgRegionStartInst>(I);
323     if (MMI && RSI->getContext() && MMI->Verify(RSI->getContext())) {
324       unsigned ID = MMI->RecordRegionStart(RSI->getContext());
325       const TargetInstrDesc &II = TII.get(TargetInstrInfo::DBG_LABEL);
326       BuildMI(MBB, II).addImm(ID);
327     }
328     return true;
329   }
330   case Intrinsic::dbg_region_end: {
331     DbgRegionEndInst *REI = cast<DbgRegionEndInst>(I);
332     if (MMI && REI->getContext() && MMI->Verify(REI->getContext())) {
333       unsigned ID = MMI->RecordRegionEnd(REI->getContext());
334       const TargetInstrDesc &II = TII.get(TargetInstrInfo::DBG_LABEL);
335       BuildMI(MBB, II).addImm(ID);
336     }
337     return true;
338   }
339   case Intrinsic::dbg_func_start: {
340     if (!MMI) return true;
341     DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
342     Value *SP = FSI->getSubprogram();
343     if (SP && MMI->Verify(SP)) {
344       // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
345       // what (most?) gdb expects.
346       DebugInfoDesc *DD = MMI->getDescFor(SP);
347       assert(DD && "Not a debug information descriptor");
348       SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
349       const CompileUnitDesc *CompileUnit = Subprogram->getFile();
350       unsigned SrcFile = MMI->RecordSource(CompileUnit);
351       // Record the source line but does create a label. It will be emitted
352       // at asm emission time.
353       MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
354     }
355     return true;
356   }
357   case Intrinsic::dbg_declare: {
358     DbgDeclareInst *DI = cast<DbgDeclareInst>(I);
359     Value *Variable = DI->getVariable();
360     if (MMI && Variable && MMI->Verify(Variable)) {
361       // Determine the address of the declared object.
362       Value *Address = DI->getAddress();
363       if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
364         Address = BCI->getOperand(0);
365       AllocaInst *AI = dyn_cast<AllocaInst>(Address);
366       // Don't handle byval struct arguments, for example.
367       if (!AI) break;
368       DenseMap<const AllocaInst*, int>::iterator SI =
369         StaticAllocaMap.find(AI);
370       assert(SI != StaticAllocaMap.end() && "Invalid dbg.declare!");
371       int FI = SI->second;
372
373       // Determine the debug globalvariable.
374       GlobalValue *GV = cast<GlobalVariable>(Variable);
375
376       // Build the DECLARE instruction.
377       const TargetInstrDesc &II = TII.get(TargetInstrInfo::DECLARE);
378       BuildMI(MBB, II).addFrameIndex(FI).addGlobalAddress(GV);
379     }
380     return true;
381   }
382   }
383   return false;
384 }
385
386 bool FastISel::SelectCast(User *I, ISD::NodeType Opcode) {
387   MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
388   MVT DstVT = TLI.getValueType(I->getType());
389     
390   if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
391       DstVT == MVT::Other || !DstVT.isSimple() ||
392       !TLI.isTypeLegal(DstVT))
393     // Unhandled type. Halt "fast" selection and bail.
394     return false;
395     
396   // Check if the source operand is legal. Or as a special case,
397   // it may be i1 if we're doing zero-extension because that's
398   // trivially easy and somewhat common.
399   if (!TLI.isTypeLegal(SrcVT)) {
400     if (SrcVT == MVT::i1 && Opcode == ISD::ZERO_EXTEND)
401       SrcVT = TLI.getTypeToTransformTo(SrcVT);
402     else
403       // Unhandled type. Halt "fast" selection and bail.
404       return false;
405   }
406     
407   unsigned InputReg = getRegForValue(I->getOperand(0));
408   if (!InputReg)
409     // Unhandled operand.  Halt "fast" selection and bail.
410     return false;
411     
412   unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
413                                   DstVT.getSimpleVT(),
414                                   Opcode,
415                                   InputReg);
416   if (!ResultReg)
417     return false;
418     
419   UpdateValueMap(I, ResultReg);
420   return true;
421 }
422
423 bool FastISel::SelectBitCast(User *I) {
424   // If the bitcast doesn't change the type, just use the operand value.
425   if (I->getType() == I->getOperand(0)->getType()) {
426     unsigned Reg = getRegForValue(I->getOperand(0));
427     if (Reg == 0)
428       return false;
429     UpdateValueMap(I, Reg);
430     return true;
431   }
432
433   // Bitcasts of other values become reg-reg copies or BIT_CONVERT operators.
434   MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
435   MVT DstVT = TLI.getValueType(I->getType());
436   
437   if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
438       DstVT == MVT::Other || !DstVT.isSimple() ||
439       !TLI.isTypeLegal(SrcVT) || !TLI.isTypeLegal(DstVT))
440     // Unhandled type. Halt "fast" selection and bail.
441     return false;
442   
443   unsigned Op0 = getRegForValue(I->getOperand(0));
444   if (Op0 == 0)
445     // Unhandled operand. Halt "fast" selection and bail.
446     return false;
447   
448   // First, try to perform the bitcast by inserting a reg-reg copy.
449   unsigned ResultReg = 0;
450   if (SrcVT.getSimpleVT() == DstVT.getSimpleVT()) {
451     TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
452     TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
453     ResultReg = createResultReg(DstClass);
454     
455     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
456                                          Op0, DstClass, SrcClass);
457     if (!InsertedCopy)
458       ResultReg = 0;
459   }
460   
461   // If the reg-reg copy failed, select a BIT_CONVERT opcode.
462   if (!ResultReg)
463     ResultReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
464                            ISD::BIT_CONVERT, Op0);
465   
466   if (!ResultReg)
467     return false;
468   
469   UpdateValueMap(I, ResultReg);
470   return true;
471 }
472
473 bool
474 FastISel::SelectInstruction(Instruction *I) {
475   return SelectOperator(I, I->getOpcode());
476 }
477
478 /// FastEmitBranch - Emit an unconditional branch to the given block,
479 /// unless it is the immediate (fall-through) successor, and update
480 /// the CFG.
481 void
482 FastISel::FastEmitBranch(MachineBasicBlock *MSucc) {
483   MachineFunction::iterator NextMBB =
484      next(MachineFunction::iterator(MBB));
485
486   if (MBB->isLayoutSuccessor(MSucc)) {
487     // The unconditional fall-through case, which needs no instructions.
488   } else {
489     // The unconditional branch case.
490     TII.InsertBranch(*MBB, MSucc, NULL, SmallVector<MachineOperand, 0>());
491   }
492   MBB->addSuccessor(MSucc);
493 }
494
495 bool
496 FastISel::SelectOperator(User *I, unsigned Opcode) {
497   switch (Opcode) {
498   case Instruction::Add: {
499     ISD::NodeType Opc = I->getType()->isFPOrFPVector() ? ISD::FADD : ISD::ADD;
500     return SelectBinaryOp(I, Opc);
501   }
502   case Instruction::Sub: {
503     ISD::NodeType Opc = I->getType()->isFPOrFPVector() ? ISD::FSUB : ISD::SUB;
504     return SelectBinaryOp(I, Opc);
505   }
506   case Instruction::Mul: {
507     ISD::NodeType Opc = I->getType()->isFPOrFPVector() ? ISD::FMUL : ISD::MUL;
508     return SelectBinaryOp(I, Opc);
509   }
510   case Instruction::SDiv:
511     return SelectBinaryOp(I, ISD::SDIV);
512   case Instruction::UDiv:
513     return SelectBinaryOp(I, ISD::UDIV);
514   case Instruction::FDiv:
515     return SelectBinaryOp(I, ISD::FDIV);
516   case Instruction::SRem:
517     return SelectBinaryOp(I, ISD::SREM);
518   case Instruction::URem:
519     return SelectBinaryOp(I, ISD::UREM);
520   case Instruction::FRem:
521     return SelectBinaryOp(I, ISD::FREM);
522   case Instruction::Shl:
523     return SelectBinaryOp(I, ISD::SHL);
524   case Instruction::LShr:
525     return SelectBinaryOp(I, ISD::SRL);
526   case Instruction::AShr:
527     return SelectBinaryOp(I, ISD::SRA);
528   case Instruction::And:
529     return SelectBinaryOp(I, ISD::AND);
530   case Instruction::Or:
531     return SelectBinaryOp(I, ISD::OR);
532   case Instruction::Xor:
533     return SelectBinaryOp(I, ISD::XOR);
534
535   case Instruction::GetElementPtr:
536     return SelectGetElementPtr(I);
537
538   case Instruction::Br: {
539     BranchInst *BI = cast<BranchInst>(I);
540
541     if (BI->isUnconditional()) {
542       BasicBlock *LLVMSucc = BI->getSuccessor(0);
543       MachineBasicBlock *MSucc = MBBMap[LLVMSucc];
544       FastEmitBranch(MSucc);
545       return true;
546     }
547
548     // Conditional branches are not handed yet.
549     // Halt "fast" selection and bail.
550     return false;
551   }
552
553   case Instruction::Unreachable:
554     // Nothing to emit.
555     return true;
556
557   case Instruction::PHI:
558     // PHI nodes are already emitted.
559     return true;
560
561   case Instruction::Alloca:
562     // FunctionLowering has the static-sized case covered.
563     if (StaticAllocaMap.count(cast<AllocaInst>(I)))
564       return true;
565
566     // Dynamic-sized alloca is not handled yet.
567     return false;
568     
569   case Instruction::Call:
570     return SelectCall(I);
571   
572   case Instruction::BitCast:
573     return SelectBitCast(I);
574
575   case Instruction::FPToSI:
576     return SelectCast(I, ISD::FP_TO_SINT);
577   case Instruction::ZExt:
578     return SelectCast(I, ISD::ZERO_EXTEND);
579   case Instruction::SExt:
580     return SelectCast(I, ISD::SIGN_EXTEND);
581   case Instruction::Trunc:
582     return SelectCast(I, ISD::TRUNCATE);
583   case Instruction::SIToFP:
584     return SelectCast(I, ISD::SINT_TO_FP);
585
586   case Instruction::IntToPtr: // Deliberate fall-through.
587   case Instruction::PtrToInt: {
588     MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
589     MVT DstVT = TLI.getValueType(I->getType());
590     if (DstVT.bitsGT(SrcVT))
591       return SelectCast(I, ISD::ZERO_EXTEND);
592     if (DstVT.bitsLT(SrcVT))
593       return SelectCast(I, ISD::TRUNCATE);
594     unsigned Reg = getRegForValue(I->getOperand(0));
595     if (Reg == 0) return false;
596     UpdateValueMap(I, Reg);
597     return true;
598   }
599
600   default:
601     // Unhandled instruction. Halt "fast" selection and bail.
602     return false;
603   }
604 }
605
606 FastISel::FastISel(MachineFunction &mf,
607                    MachineModuleInfo *mmi,
608                    DenseMap<const Value *, unsigned> &vm,
609                    DenseMap<const BasicBlock *, MachineBasicBlock *> &bm,
610                    DenseMap<const AllocaInst *, int> &am)
611   : MBB(0),
612     ValueMap(vm),
613     MBBMap(bm),
614     StaticAllocaMap(am),
615     MF(mf),
616     MMI(mmi),
617     MRI(MF.getRegInfo()),
618     MFI(*MF.getFrameInfo()),
619     MCP(*MF.getConstantPool()),
620     TM(MF.getTarget()),
621     TD(*TM.getTargetData()),
622     TII(*TM.getInstrInfo()),
623     TLI(*TM.getTargetLowering()) {
624 }
625
626 FastISel::~FastISel() {}
627
628 unsigned FastISel::FastEmit_(MVT::SimpleValueType, MVT::SimpleValueType,
629                              ISD::NodeType) {
630   return 0;
631 }
632
633 unsigned FastISel::FastEmit_r(MVT::SimpleValueType, MVT::SimpleValueType,
634                               ISD::NodeType, unsigned /*Op0*/) {
635   return 0;
636 }
637
638 unsigned FastISel::FastEmit_rr(MVT::SimpleValueType, MVT::SimpleValueType, 
639                                ISD::NodeType, unsigned /*Op0*/,
640                                unsigned /*Op0*/) {
641   return 0;
642 }
643
644 unsigned FastISel::FastEmit_i(MVT::SimpleValueType, MVT::SimpleValueType,
645                               ISD::NodeType, uint64_t /*Imm*/) {
646   return 0;
647 }
648
649 unsigned FastISel::FastEmit_f(MVT::SimpleValueType, MVT::SimpleValueType,
650                               ISD::NodeType, ConstantFP * /*FPImm*/) {
651   return 0;
652 }
653
654 unsigned FastISel::FastEmit_ri(MVT::SimpleValueType, MVT::SimpleValueType,
655                                ISD::NodeType, unsigned /*Op0*/,
656                                uint64_t /*Imm*/) {
657   return 0;
658 }
659
660 unsigned FastISel::FastEmit_rf(MVT::SimpleValueType, MVT::SimpleValueType,
661                                ISD::NodeType, unsigned /*Op0*/,
662                                ConstantFP * /*FPImm*/) {
663   return 0;
664 }
665
666 unsigned FastISel::FastEmit_rri(MVT::SimpleValueType, MVT::SimpleValueType,
667                                 ISD::NodeType,
668                                 unsigned /*Op0*/, unsigned /*Op1*/,
669                                 uint64_t /*Imm*/) {
670   return 0;
671 }
672
673 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
674 /// to emit an instruction with an immediate operand using FastEmit_ri.
675 /// If that fails, it materializes the immediate into a register and try
676 /// FastEmit_rr instead.
677 unsigned FastISel::FastEmit_ri_(MVT::SimpleValueType VT, ISD::NodeType Opcode,
678                                 unsigned Op0, uint64_t Imm,
679                                 MVT::SimpleValueType ImmType) {
680   // First check if immediate type is legal. If not, we can't use the ri form.
681   unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Imm);
682   if (ResultReg != 0)
683     return ResultReg;
684   unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
685   if (MaterialReg == 0)
686     return 0;
687   return FastEmit_rr(VT, VT, Opcode, Op0, MaterialReg);
688 }
689
690 /// FastEmit_rf_ - This method is a wrapper of FastEmit_ri. It first tries
691 /// to emit an instruction with a floating-point immediate operand using
692 /// FastEmit_rf. If that fails, it materializes the immediate into a register
693 /// and try FastEmit_rr instead.
694 unsigned FastISel::FastEmit_rf_(MVT::SimpleValueType VT, ISD::NodeType Opcode,
695                                 unsigned Op0, ConstantFP *FPImm,
696                                 MVT::SimpleValueType ImmType) {
697   // First check if immediate type is legal. If not, we can't use the rf form.
698   unsigned ResultReg = FastEmit_rf(VT, VT, Opcode, Op0, FPImm);
699   if (ResultReg != 0)
700     return ResultReg;
701
702   // Materialize the constant in a register.
703   unsigned MaterialReg = FastEmit_f(ImmType, ImmType, ISD::ConstantFP, FPImm);
704   if (MaterialReg == 0) {
705     // If the target doesn't have a way to directly enter a floating-point
706     // value into a register, use an alternate approach.
707     // TODO: The current approach only supports floating-point constants
708     // that can be constructed by conversion from integer values. This should
709     // be replaced by code that creates a load from a constant-pool entry,
710     // which will require some target-specific work.
711     const APFloat &Flt = FPImm->getValueAPF();
712     MVT IntVT = TLI.getPointerTy();
713
714     uint64_t x[2];
715     uint32_t IntBitWidth = IntVT.getSizeInBits();
716     bool isExact;
717     (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
718                              APFloat::rmTowardZero, &isExact);
719     if (!isExact)
720       return 0;
721     APInt IntVal(IntBitWidth, 2, x);
722
723     unsigned IntegerReg = FastEmit_i(IntVT.getSimpleVT(), IntVT.getSimpleVT(),
724                                      ISD::Constant, IntVal.getZExtValue());
725     if (IntegerReg == 0)
726       return 0;
727     MaterialReg = FastEmit_r(IntVT.getSimpleVT(), VT,
728                              ISD::SINT_TO_FP, IntegerReg);
729     if (MaterialReg == 0)
730       return 0;
731   }
732   return FastEmit_rr(VT, VT, Opcode, Op0, MaterialReg);
733 }
734
735 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
736   return MRI.createVirtualRegister(RC);
737 }
738
739 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
740                                  const TargetRegisterClass* RC) {
741   unsigned ResultReg = createResultReg(RC);
742   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
743
744   BuildMI(MBB, II, ResultReg);
745   return ResultReg;
746 }
747
748 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
749                                   const TargetRegisterClass *RC,
750                                   unsigned Op0) {
751   unsigned ResultReg = createResultReg(RC);
752   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
753
754   if (II.getNumDefs() >= 1)
755     BuildMI(MBB, II, ResultReg).addReg(Op0);
756   else {
757     BuildMI(MBB, II).addReg(Op0);
758     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
759                                          II.ImplicitDefs[0], RC, RC);
760     if (!InsertedCopy)
761       ResultReg = 0;
762   }
763
764   return ResultReg;
765 }
766
767 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
768                                    const TargetRegisterClass *RC,
769                                    unsigned Op0, unsigned Op1) {
770   unsigned ResultReg = createResultReg(RC);
771   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
772
773   if (II.getNumDefs() >= 1)
774     BuildMI(MBB, II, ResultReg).addReg(Op0).addReg(Op1);
775   else {
776     BuildMI(MBB, II).addReg(Op0).addReg(Op1);
777     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
778                                          II.ImplicitDefs[0], RC, RC);
779     if (!InsertedCopy)
780       ResultReg = 0;
781   }
782   return ResultReg;
783 }
784
785 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
786                                    const TargetRegisterClass *RC,
787                                    unsigned Op0, uint64_t Imm) {
788   unsigned ResultReg = createResultReg(RC);
789   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
790
791   if (II.getNumDefs() >= 1)
792     BuildMI(MBB, II, ResultReg).addReg(Op0).addImm(Imm);
793   else {
794     BuildMI(MBB, II).addReg(Op0).addImm(Imm);
795     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
796                                          II.ImplicitDefs[0], RC, RC);
797     if (!InsertedCopy)
798       ResultReg = 0;
799   }
800   return ResultReg;
801 }
802
803 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
804                                    const TargetRegisterClass *RC,
805                                    unsigned Op0, ConstantFP *FPImm) {
806   unsigned ResultReg = createResultReg(RC);
807   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
808
809   if (II.getNumDefs() >= 1)
810     BuildMI(MBB, II, ResultReg).addReg(Op0).addFPImm(FPImm);
811   else {
812     BuildMI(MBB, II).addReg(Op0).addFPImm(FPImm);
813     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
814                                          II.ImplicitDefs[0], RC, RC);
815     if (!InsertedCopy)
816       ResultReg = 0;
817   }
818   return ResultReg;
819 }
820
821 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
822                                     const TargetRegisterClass *RC,
823                                     unsigned Op0, unsigned Op1, uint64_t Imm) {
824   unsigned ResultReg = createResultReg(RC);
825   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
826
827   if (II.getNumDefs() >= 1)
828     BuildMI(MBB, II, ResultReg).addReg(Op0).addReg(Op1).addImm(Imm);
829   else {
830     BuildMI(MBB, II).addReg(Op0).addReg(Op1).addImm(Imm);
831     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
832                                          II.ImplicitDefs[0], RC, RC);
833     if (!InsertedCopy)
834       ResultReg = 0;
835   }
836   return ResultReg;
837 }
838
839 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
840                                   const TargetRegisterClass *RC,
841                                   uint64_t Imm) {
842   unsigned ResultReg = createResultReg(RC);
843   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
844   
845   if (II.getNumDefs() >= 1)
846     BuildMI(MBB, II, ResultReg).addImm(Imm);
847   else {
848     BuildMI(MBB, II).addImm(Imm);
849     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
850                                          II.ImplicitDefs[0], RC, RC);
851     if (!InsertedCopy)
852       ResultReg = 0;
853   }
854   return ResultReg;
855 }
856
857 unsigned FastISel::FastEmitInst_extractsubreg(unsigned Op0, uint32_t Idx) {
858   const TargetRegisterClass* RC = MRI.getRegClass(Op0);
859   const TargetRegisterClass* SRC = *(RC->subregclasses_begin()+Idx-1);
860   
861   unsigned ResultReg = createResultReg(SRC);
862   const TargetInstrDesc &II = TII.get(TargetInstrInfo::EXTRACT_SUBREG);
863   
864   if (II.getNumDefs() >= 1)
865     BuildMI(MBB, II, ResultReg).addReg(Op0).addImm(Idx);
866   else {
867     BuildMI(MBB, II).addReg(Op0).addImm(Idx);
868     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
869                                          II.ImplicitDefs[0], RC, RC);
870     if (!InsertedCopy)
871       ResultReg = 0;
872   }
873   return ResultReg;
874 }