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