]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/CodeGen/SelectionDAG/FastISel.cpp
Update LLVM to r103004.
[FreeBSD/FreeBSD.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 #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/Analysis/DebugInfo.h"
51 #include "llvm/Target/TargetData.h"
52 #include "llvm/Target/TargetInstrInfo.h"
53 #include "llvm/Target/TargetLowering.h"
54 #include "llvm/Target/TargetMachine.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "FunctionLoweringInfo.h"
57 using namespace llvm;
58
59 unsigned FastISel::getRegForValue(const Value *V) {
60   EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true);
61   // Don't handle non-simple values in FastISel.
62   if (!RealVT.isSimple())
63     return 0;
64
65   // Ignore illegal types. We must do this before looking up the value
66   // in ValueMap because Arguments are given virtual registers regardless
67   // of whether FastISel can handle them.
68   MVT VT = RealVT.getSimpleVT();
69   if (!TLI.isTypeLegal(VT)) {
70     // Promote MVT::i1 to a legal type though, because it's common and easy.
71     if (VT == MVT::i1)
72       VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
73     else
74       return 0;
75   }
76
77   // Look up the value to see if we already have a register for it. We
78   // cache values defined by Instructions across blocks, and other values
79   // only locally. This is because Instructions already have the SSA
80   // def-dominates-use requirement enforced.
81   if (ValueMap.count(V))
82     return ValueMap[V];
83   unsigned Reg = LocalValueMap[V];
84   if (Reg != 0)
85     return Reg;
86
87   return materializeRegForValue(V, VT);
88 }
89
90 /// materializeRegForValue - Helper for getRegForVale. This function is
91 /// called when the value isn't already available in a register and must
92 /// be materialized with new instructions.
93 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
94   unsigned Reg = 0;
95
96   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
97     if (CI->getValue().getActiveBits() <= 64)
98       Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
99   } else if (isa<AllocaInst>(V)) {
100     Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
101   } else if (isa<ConstantPointerNull>(V)) {
102     // Translate this as an integer zero so that it can be
103     // local-CSE'd with actual integer zeros.
104     Reg =
105       getRegForValue(Constant::getNullValue(TD.getIntPtrType(V->getContext())));
106   } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
107     // Try to emit the constant directly.
108     Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
109
110     if (!Reg) {
111       // Try to emit the constant by using an integer constant with a cast.
112       const APFloat &Flt = CF->getValueAPF();
113       EVT IntVT = TLI.getPointerTy();
114
115       uint64_t x[2];
116       uint32_t IntBitWidth = IntVT.getSizeInBits();
117       bool isExact;
118       (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
119                                 APFloat::rmTowardZero, &isExact);
120       if (isExact) {
121         APInt IntVal(IntBitWidth, 2, x);
122
123         unsigned IntegerReg =
124           getRegForValue(ConstantInt::get(V->getContext(), IntVal));
125         if (IntegerReg != 0)
126           Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, IntegerReg);
127       }
128     }
129   } else if (const Operator *Op = dyn_cast<Operator>(V)) {
130     if (!SelectOperator(Op, Op->getOpcode())) return 0;
131     Reg = LocalValueMap[Op];
132   } else if (isa<UndefValue>(V)) {
133     Reg = createResultReg(TLI.getRegClassFor(VT));
134     BuildMI(MBB, DL, TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
135   }
136   
137   // If target-independent code couldn't handle the value, give target-specific
138   // code a try.
139   if (!Reg && isa<Constant>(V))
140     Reg = TargetMaterializeConstant(cast<Constant>(V));
141   
142   // Don't cache constant materializations in the general ValueMap.
143   // To do so would require tracking what uses they dominate.
144   if (Reg != 0)
145     LocalValueMap[V] = Reg;
146   return Reg;
147 }
148
149 unsigned FastISel::lookUpRegForValue(const Value *V) {
150   // Look up the value to see if we already have a register for it. We
151   // cache values defined by Instructions across blocks, and other values
152   // only locally. This is because Instructions already have the SSA
153   // def-dominates-use requirement enforced.
154   if (ValueMap.count(V))
155     return ValueMap[V];
156   return LocalValueMap[V];
157 }
158
159 /// UpdateValueMap - Update the value map to include the new mapping for this
160 /// instruction, or insert an extra copy to get the result in a previous
161 /// determined register.
162 /// NOTE: This is only necessary because we might select a block that uses
163 /// a value before we select the block that defines the value.  It might be
164 /// possible to fix this by selecting blocks in reverse postorder.
165 unsigned FastISel::UpdateValueMap(const Value *I, unsigned Reg) {
166   if (!isa<Instruction>(I)) {
167     LocalValueMap[I] = Reg;
168     return Reg;
169   }
170   
171   unsigned &AssignedReg = ValueMap[I];
172   if (AssignedReg == 0)
173     AssignedReg = Reg;
174   else if (Reg != AssignedReg) {
175     const TargetRegisterClass *RegClass = MRI.getRegClass(Reg);
176     TII.copyRegToReg(*MBB, MBB->end(), AssignedReg,
177                      Reg, RegClass, RegClass);
178   }
179   return AssignedReg;
180 }
181
182 unsigned FastISel::getRegForGEPIndex(const Value *Idx) {
183   unsigned IdxN = getRegForValue(Idx);
184   if (IdxN == 0)
185     // Unhandled operand. Halt "fast" selection and bail.
186     return 0;
187
188   // If the index is smaller or larger than intptr_t, truncate or extend it.
189   MVT PtrVT = TLI.getPointerTy();
190   EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
191   if (IdxVT.bitsLT(PtrVT))
192     IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND, IdxN);
193   else if (IdxVT.bitsGT(PtrVT))
194     IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE, IdxN);
195   return IdxN;
196 }
197
198 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
199 /// which has an opcode which directly corresponds to the given ISD opcode.
200 ///
201 bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) {
202   EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
203   if (VT == MVT::Other || !VT.isSimple())
204     // Unhandled type. Halt "fast" selection and bail.
205     return false;
206
207   // We only handle legal types. For example, on x86-32 the instruction
208   // selector contains all of the 64-bit instructions from x86-64,
209   // under the assumption that i64 won't be used if the target doesn't
210   // support it.
211   if (!TLI.isTypeLegal(VT)) {
212     // MVT::i1 is special. Allow AND, OR, or XOR because they
213     // don't require additional zeroing, which makes them easy.
214     if (VT == MVT::i1 &&
215         (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
216          ISDOpcode == ISD::XOR))
217       VT = TLI.getTypeToTransformTo(I->getContext(), VT);
218     else
219       return false;
220   }
221
222   unsigned Op0 = getRegForValue(I->getOperand(0));
223   if (Op0 == 0)
224     // Unhandled operand. Halt "fast" selection and bail.
225     return false;
226
227   // Check if the second operand is a constant and handle it appropriately.
228   if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
229     unsigned ResultReg = FastEmit_ri(VT.getSimpleVT(), VT.getSimpleVT(),
230                                      ISDOpcode, Op0, CI->getZExtValue());
231     if (ResultReg != 0) {
232       // We successfully emitted code for the given LLVM Instruction.
233       UpdateValueMap(I, ResultReg);
234       return true;
235     }
236   }
237
238   // Check if the second operand is a constant float.
239   if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
240     unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
241                                      ISDOpcode, Op0, CF);
242     if (ResultReg != 0) {
243       // We successfully emitted code for the given LLVM Instruction.
244       UpdateValueMap(I, ResultReg);
245       return true;
246     }
247   }
248
249   unsigned Op1 = getRegForValue(I->getOperand(1));
250   if (Op1 == 0)
251     // Unhandled operand. Halt "fast" selection and bail.
252     return false;
253
254   // Now we have both operands in registers. Emit the instruction.
255   unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
256                                    ISDOpcode, Op0, Op1);
257   if (ResultReg == 0)
258     // Target-specific code wasn't able to find a machine opcode for
259     // the given ISD opcode and type. Halt "fast" selection and bail.
260     return false;
261
262   // We successfully emitted code for the given LLVM Instruction.
263   UpdateValueMap(I, ResultReg);
264   return true;
265 }
266
267 bool FastISel::SelectGetElementPtr(const User *I) {
268   unsigned N = getRegForValue(I->getOperand(0));
269   if (N == 0)
270     // Unhandled operand. Halt "fast" selection and bail.
271     return false;
272
273   const Type *Ty = I->getOperand(0)->getType();
274   MVT VT = TLI.getPointerTy();
275   for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1,
276        E = I->op_end(); OI != E; ++OI) {
277     const Value *Idx = *OI;
278     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
279       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
280       if (Field) {
281         // N = N + Offset
282         uint64_t Offs = TD.getStructLayout(StTy)->getElementOffset(Field);
283         // FIXME: This can be optimized by combining the add with a
284         // subsequent one.
285         N = FastEmit_ri_(VT, ISD::ADD, N, Offs, VT);
286         if (N == 0)
287           // Unhandled operand. Halt "fast" selection and bail.
288           return false;
289       }
290       Ty = StTy->getElementType(Field);
291     } else {
292       Ty = cast<SequentialType>(Ty)->getElementType();
293
294       // If this is a constant subscript, handle it quickly.
295       if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
296         if (CI->getZExtValue() == 0) continue;
297         uint64_t Offs = 
298           TD.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
299         N = FastEmit_ri_(VT, ISD::ADD, N, Offs, VT);
300         if (N == 0)
301           // Unhandled operand. Halt "fast" selection and bail.
302           return false;
303         continue;
304       }
305       
306       // N = N + Idx * ElementSize;
307       uint64_t ElementSize = TD.getTypeAllocSize(Ty);
308       unsigned IdxN = getRegForGEPIndex(Idx);
309       if (IdxN == 0)
310         // Unhandled operand. Halt "fast" selection and bail.
311         return false;
312
313       if (ElementSize != 1) {
314         IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, ElementSize, VT);
315         if (IdxN == 0)
316           // Unhandled operand. Halt "fast" selection and bail.
317           return false;
318       }
319       N = FastEmit_rr(VT, VT, ISD::ADD, N, IdxN);
320       if (N == 0)
321         // Unhandled operand. Halt "fast" selection and bail.
322         return false;
323     }
324   }
325
326   // We successfully emitted code for the given LLVM Instruction.
327   UpdateValueMap(I, N);
328   return true;
329 }
330
331 bool FastISel::SelectCall(const User *I) {
332   const Function *F = cast<CallInst>(I)->getCalledFunction();
333   if (!F) return false;
334
335   // Handle selected intrinsic function calls.
336   unsigned IID = F->getIntrinsicID();
337   switch (IID) {
338   default: break;
339   case Intrinsic::dbg_declare: {
340     const DbgDeclareInst *DI = cast<DbgDeclareInst>(I);
341     if (!DIDescriptor::ValidDebugInfo(DI->getVariable(), CodeGenOpt::None) ||
342         !MF.getMMI().hasDebugInfo())
343       return true;
344
345     const Value *Address = DI->getAddress();
346     if (!Address)
347       return true;
348     if (isa<UndefValue>(Address))
349       return true;
350     const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
351     // Don't handle byval struct arguments or VLAs, for example.
352     // Note that if we have a byval struct argument, fast ISel is turned off;
353     // those are handled in SelectionDAGBuilder.
354     if (AI) {
355       DenseMap<const AllocaInst*, int>::iterator SI =
356         StaticAllocaMap.find(AI);
357       if (SI == StaticAllocaMap.end()) break; // VLAs.
358       int FI = SI->second;
359       if (!DI->getDebugLoc().isUnknown())
360         MF.getMMI().setVariableDbgInfo(DI->getVariable(), FI, DI->getDebugLoc());
361     } else
362       // Building the map above is target independent.  Generating DBG_VALUE
363       // inline is target dependent; do this now.
364       (void)TargetSelectInstruction(cast<Instruction>(I));
365     return true;
366   }
367   case Intrinsic::dbg_value: {
368     // This form of DBG_VALUE is target-independent.
369     const DbgValueInst *DI = cast<DbgValueInst>(I);
370     const TargetInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
371     const Value *V = DI->getValue();
372     if (!V) {
373       // Currently the optimizer can produce this; insert an undef to
374       // help debugging.  Probably the optimizer should not do this.
375       BuildMI(MBB, DL, II).addReg(0U).addImm(DI->getOffset()).
376                                      addMetadata(DI->getVariable());
377     } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
378       BuildMI(MBB, DL, II).addImm(CI->getZExtValue()).addImm(DI->getOffset()).
379                                      addMetadata(DI->getVariable());
380     } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
381       BuildMI(MBB, DL, II).addFPImm(CF).addImm(DI->getOffset()).
382                                      addMetadata(DI->getVariable());
383     } else if (unsigned Reg = lookUpRegForValue(V)) {
384       BuildMI(MBB, DL, II).addReg(Reg, RegState::Debug).addImm(DI->getOffset()).
385                                      addMetadata(DI->getVariable());
386     } else {
387       // We can't yet handle anything else here because it would require
388       // generating code, thus altering codegen because of debug info.
389       // Insert an undef so we can see what we dropped.
390       BuildMI(MBB, DL, II).addReg(0U).addImm(DI->getOffset()).
391                                      addMetadata(DI->getVariable());
392     }     
393     return true;
394   }
395   case Intrinsic::eh_exception: {
396     EVT VT = TLI.getValueType(I->getType());
397     switch (TLI.getOperationAction(ISD::EXCEPTIONADDR, VT)) {
398     default: break;
399     case TargetLowering::Expand: {
400       assert(MBB->isLandingPad() && "Call to eh.exception not in landing pad!");
401       unsigned Reg = TLI.getExceptionAddressRegister();
402       const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
403       unsigned ResultReg = createResultReg(RC);
404       bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
405                                            Reg, RC, RC);
406       assert(InsertedCopy && "Can't copy address registers!");
407       InsertedCopy = InsertedCopy;
408       UpdateValueMap(I, ResultReg);
409       return true;
410     }
411     }
412     break;
413   }
414   case Intrinsic::eh_selector: {
415     EVT VT = TLI.getValueType(I->getType());
416     switch (TLI.getOperationAction(ISD::EHSELECTION, VT)) {
417     default: break;
418     case TargetLowering::Expand: {
419       if (MBB->isLandingPad())
420         AddCatchInfo(*cast<CallInst>(I), &MF.getMMI(), MBB);
421       else {
422 #ifndef NDEBUG
423         CatchInfoLost.insert(cast<CallInst>(I));
424 #endif
425         // FIXME: Mark exception selector register as live in.  Hack for PR1508.
426         unsigned Reg = TLI.getExceptionSelectorRegister();
427         if (Reg) MBB->addLiveIn(Reg);
428       }
429
430       unsigned Reg = TLI.getExceptionSelectorRegister();
431       EVT SrcVT = TLI.getPointerTy();
432       const TargetRegisterClass *RC = TLI.getRegClassFor(SrcVT);
433       unsigned ResultReg = createResultReg(RC);
434       bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg, Reg,
435                                            RC, RC);
436       assert(InsertedCopy && "Can't copy address registers!");
437       InsertedCopy = InsertedCopy;
438
439       // Cast the register to the type of the selector.
440       if (SrcVT.bitsGT(MVT::i32))
441         ResultReg = FastEmit_r(SrcVT.getSimpleVT(), MVT::i32, ISD::TRUNCATE,
442                                ResultReg);
443       else if (SrcVT.bitsLT(MVT::i32))
444         ResultReg = FastEmit_r(SrcVT.getSimpleVT(), MVT::i32,
445                                ISD::SIGN_EXTEND, ResultReg);
446       if (ResultReg == 0)
447         // Unhandled operand. Halt "fast" selection and bail.
448         return false;
449
450       UpdateValueMap(I, ResultReg);
451
452       return true;
453     }
454     }
455     break;
456   }
457   }
458
459   // An arbitrary call. Bail.
460   return false;
461 }
462
463 bool FastISel::SelectCast(const User *I, unsigned Opcode) {
464   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
465   EVT DstVT = TLI.getValueType(I->getType());
466     
467   if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
468       DstVT == MVT::Other || !DstVT.isSimple())
469     // Unhandled type. Halt "fast" selection and bail.
470     return false;
471     
472   // Check if the destination type is legal. Or as a special case,
473   // it may be i1 if we're doing a truncate because that's
474   // easy and somewhat common.
475   if (!TLI.isTypeLegal(DstVT))
476     if (DstVT != MVT::i1 || Opcode != ISD::TRUNCATE)
477       // Unhandled type. Halt "fast" selection and bail.
478       return false;
479
480   // Check if the source operand is legal. Or as a special case,
481   // it may be i1 if we're doing zero-extension because that's
482   // easy and somewhat common.
483   if (!TLI.isTypeLegal(SrcVT))
484     if (SrcVT != MVT::i1 || Opcode != ISD::ZERO_EXTEND)
485       // Unhandled type. Halt "fast" selection and bail.
486       return false;
487
488   unsigned InputReg = getRegForValue(I->getOperand(0));
489   if (!InputReg)
490     // Unhandled operand.  Halt "fast" selection and bail.
491     return false;
492
493   // If the operand is i1, arrange for the high bits in the register to be zero.
494   if (SrcVT == MVT::i1) {
495    SrcVT = TLI.getTypeToTransformTo(I->getContext(), SrcVT);
496    InputReg = FastEmitZExtFromI1(SrcVT.getSimpleVT(), InputReg);
497    if (!InputReg)
498      return false;
499   }
500   // If the result is i1, truncate to the target's type for i1 first.
501   if (DstVT == MVT::i1)
502     DstVT = TLI.getTypeToTransformTo(I->getContext(), DstVT);
503
504   unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
505                                   DstVT.getSimpleVT(),
506                                   Opcode,
507                                   InputReg);
508   if (!ResultReg)
509     return false;
510     
511   UpdateValueMap(I, ResultReg);
512   return true;
513 }
514
515 bool FastISel::SelectBitCast(const User *I) {
516   // If the bitcast doesn't change the type, just use the operand value.
517   if (I->getType() == I->getOperand(0)->getType()) {
518     unsigned Reg = getRegForValue(I->getOperand(0));
519     if (Reg == 0)
520       return false;
521     UpdateValueMap(I, Reg);
522     return true;
523   }
524
525   // Bitcasts of other values become reg-reg copies or BIT_CONVERT operators.
526   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
527   EVT DstVT = TLI.getValueType(I->getType());
528   
529   if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
530       DstVT == MVT::Other || !DstVT.isSimple() ||
531       !TLI.isTypeLegal(SrcVT) || !TLI.isTypeLegal(DstVT))
532     // Unhandled type. Halt "fast" selection and bail.
533     return false;
534   
535   unsigned Op0 = getRegForValue(I->getOperand(0));
536   if (Op0 == 0)
537     // Unhandled operand. Halt "fast" selection and bail.
538     return false;
539   
540   // First, try to perform the bitcast by inserting a reg-reg copy.
541   unsigned ResultReg = 0;
542   if (SrcVT.getSimpleVT() == DstVT.getSimpleVT()) {
543     TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
544     TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
545     ResultReg = createResultReg(DstClass);
546     
547     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
548                                          Op0, DstClass, SrcClass);
549     if (!InsertedCopy)
550       ResultReg = 0;
551   }
552   
553   // If the reg-reg copy failed, select a BIT_CONVERT opcode.
554   if (!ResultReg)
555     ResultReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
556                            ISD::BIT_CONVERT, Op0);
557   
558   if (!ResultReg)
559     return false;
560   
561   UpdateValueMap(I, ResultReg);
562   return true;
563 }
564
565 bool
566 FastISel::SelectInstruction(const Instruction *I) {
567   // Just before the terminator instruction, insert instructions to
568   // feed PHI nodes in successor blocks.
569   if (isa<TerminatorInst>(I))
570     if (!HandlePHINodesInSuccessorBlocks(I->getParent()))
571       return false;
572
573   DL = I->getDebugLoc();
574
575   // First, try doing target-independent selection.
576   if (SelectOperator(I, I->getOpcode())) {
577     DL = DebugLoc();
578     return true;
579   }
580
581   // Next, try calling the target to attempt to handle the instruction.
582   if (TargetSelectInstruction(I)) {
583     DL = DebugLoc();
584     return true;
585   }
586
587   DL = DebugLoc();
588   return false;
589 }
590
591 /// FastEmitBranch - Emit an unconditional branch to the given block,
592 /// unless it is the immediate (fall-through) successor, and update
593 /// the CFG.
594 void
595 FastISel::FastEmitBranch(MachineBasicBlock *MSucc) {
596   if (MBB->isLayoutSuccessor(MSucc)) {
597     // The unconditional fall-through case, which needs no instructions.
598   } else {
599     // The unconditional branch case.
600     TII.InsertBranch(*MBB, MSucc, NULL, SmallVector<MachineOperand, 0>());
601   }
602   MBB->addSuccessor(MSucc);
603 }
604
605 /// SelectFNeg - Emit an FNeg operation.
606 ///
607 bool
608 FastISel::SelectFNeg(const User *I) {
609   unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
610   if (OpReg == 0) return false;
611
612   // If the target has ISD::FNEG, use it.
613   EVT VT = TLI.getValueType(I->getType());
614   unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(),
615                                   ISD::FNEG, OpReg);
616   if (ResultReg != 0) {
617     UpdateValueMap(I, ResultReg);
618     return true;
619   }
620
621   // Bitcast the value to integer, twiddle the sign bit with xor,
622   // and then bitcast it back to floating-point.
623   if (VT.getSizeInBits() > 64) return false;
624   EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
625   if (!TLI.isTypeLegal(IntVT))
626     return false;
627
628   unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
629                                ISD::BIT_CONVERT, OpReg);
630   if (IntReg == 0)
631     return false;
632
633   unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR, IntReg,
634                                        UINT64_C(1) << (VT.getSizeInBits()-1),
635                                        IntVT.getSimpleVT());
636   if (IntResultReg == 0)
637     return false;
638
639   ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(),
640                          ISD::BIT_CONVERT, IntResultReg);
641   if (ResultReg == 0)
642     return false;
643
644   UpdateValueMap(I, ResultReg);
645   return true;
646 }
647
648 bool
649 FastISel::SelectOperator(const User *I, unsigned Opcode) {
650   switch (Opcode) {
651   case Instruction::Add:
652     return SelectBinaryOp(I, ISD::ADD);
653   case Instruction::FAdd:
654     return SelectBinaryOp(I, ISD::FADD);
655   case Instruction::Sub:
656     return SelectBinaryOp(I, ISD::SUB);
657   case Instruction::FSub:
658     // FNeg is currently represented in LLVM IR as a special case of FSub.
659     if (BinaryOperator::isFNeg(I))
660       return SelectFNeg(I);
661     return SelectBinaryOp(I, ISD::FSUB);
662   case Instruction::Mul:
663     return SelectBinaryOp(I, ISD::MUL);
664   case Instruction::FMul:
665     return SelectBinaryOp(I, ISD::FMUL);
666   case Instruction::SDiv:
667     return SelectBinaryOp(I, ISD::SDIV);
668   case Instruction::UDiv:
669     return SelectBinaryOp(I, ISD::UDIV);
670   case Instruction::FDiv:
671     return SelectBinaryOp(I, ISD::FDIV);
672   case Instruction::SRem:
673     return SelectBinaryOp(I, ISD::SREM);
674   case Instruction::URem:
675     return SelectBinaryOp(I, ISD::UREM);
676   case Instruction::FRem:
677     return SelectBinaryOp(I, ISD::FREM);
678   case Instruction::Shl:
679     return SelectBinaryOp(I, ISD::SHL);
680   case Instruction::LShr:
681     return SelectBinaryOp(I, ISD::SRL);
682   case Instruction::AShr:
683     return SelectBinaryOp(I, ISD::SRA);
684   case Instruction::And:
685     return SelectBinaryOp(I, ISD::AND);
686   case Instruction::Or:
687     return SelectBinaryOp(I, ISD::OR);
688   case Instruction::Xor:
689     return SelectBinaryOp(I, ISD::XOR);
690
691   case Instruction::GetElementPtr:
692     return SelectGetElementPtr(I);
693
694   case Instruction::Br: {
695     const BranchInst *BI = cast<BranchInst>(I);
696
697     if (BI->isUnconditional()) {
698       const BasicBlock *LLVMSucc = BI->getSuccessor(0);
699       MachineBasicBlock *MSucc = MBBMap[LLVMSucc];
700       FastEmitBranch(MSucc);
701       return true;
702     }
703
704     // Conditional branches are not handed yet.
705     // Halt "fast" selection and bail.
706     return false;
707   }
708
709   case Instruction::Unreachable:
710     // Nothing to emit.
711     return true;
712
713   case Instruction::Alloca:
714     // FunctionLowering has the static-sized case covered.
715     if (StaticAllocaMap.count(cast<AllocaInst>(I)))
716       return true;
717
718     // Dynamic-sized alloca is not handled yet.
719     return false;
720     
721   case Instruction::Call:
722     return SelectCall(I);
723   
724   case Instruction::BitCast:
725     return SelectBitCast(I);
726
727   case Instruction::FPToSI:
728     return SelectCast(I, ISD::FP_TO_SINT);
729   case Instruction::ZExt:
730     return SelectCast(I, ISD::ZERO_EXTEND);
731   case Instruction::SExt:
732     return SelectCast(I, ISD::SIGN_EXTEND);
733   case Instruction::Trunc:
734     return SelectCast(I, ISD::TRUNCATE);
735   case Instruction::SIToFP:
736     return SelectCast(I, ISD::SINT_TO_FP);
737
738   case Instruction::IntToPtr: // Deliberate fall-through.
739   case Instruction::PtrToInt: {
740     EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
741     EVT DstVT = TLI.getValueType(I->getType());
742     if (DstVT.bitsGT(SrcVT))
743       return SelectCast(I, ISD::ZERO_EXTEND);
744     if (DstVT.bitsLT(SrcVT))
745       return SelectCast(I, ISD::TRUNCATE);
746     unsigned Reg = getRegForValue(I->getOperand(0));
747     if (Reg == 0) return false;
748     UpdateValueMap(I, Reg);
749     return true;
750   }
751
752   case Instruction::PHI:
753     llvm_unreachable("FastISel shouldn't visit PHI nodes!");
754
755   default:
756     // Unhandled instruction. Halt "fast" selection and bail.
757     return false;
758   }
759 }
760
761 FastISel::FastISel(MachineFunction &mf,
762                    DenseMap<const Value *, unsigned> &vm,
763                    DenseMap<const BasicBlock *, MachineBasicBlock *> &bm,
764                    DenseMap<const AllocaInst *, int> &am,
765                    std::vector<std::pair<MachineInstr*, unsigned> > &pn
766 #ifndef NDEBUG
767                    , SmallSet<const Instruction *, 8> &cil
768 #endif
769                    )
770   : MBB(0),
771     ValueMap(vm),
772     MBBMap(bm),
773     StaticAllocaMap(am),
774     PHINodesToUpdate(pn),
775 #ifndef NDEBUG
776     CatchInfoLost(cil),
777 #endif
778     MF(mf),
779     MRI(MF.getRegInfo()),
780     MFI(*MF.getFrameInfo()),
781     MCP(*MF.getConstantPool()),
782     TM(MF.getTarget()),
783     TD(*TM.getTargetData()),
784     TII(*TM.getInstrInfo()),
785     TLI(*TM.getTargetLowering()) {
786 }
787
788 FastISel::~FastISel() {}
789
790 unsigned FastISel::FastEmit_(MVT, MVT,
791                              unsigned) {
792   return 0;
793 }
794
795 unsigned FastISel::FastEmit_r(MVT, MVT,
796                               unsigned, unsigned /*Op0*/) {
797   return 0;
798 }
799
800 unsigned FastISel::FastEmit_rr(MVT, MVT, 
801                                unsigned, unsigned /*Op0*/,
802                                unsigned /*Op0*/) {
803   return 0;
804 }
805
806 unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
807   return 0;
808 }
809
810 unsigned FastISel::FastEmit_f(MVT, MVT,
811                               unsigned, const ConstantFP * /*FPImm*/) {
812   return 0;
813 }
814
815 unsigned FastISel::FastEmit_ri(MVT, MVT,
816                                unsigned, unsigned /*Op0*/,
817                                uint64_t /*Imm*/) {
818   return 0;
819 }
820
821 unsigned FastISel::FastEmit_rf(MVT, MVT,
822                                unsigned, unsigned /*Op0*/,
823                                const ConstantFP * /*FPImm*/) {
824   return 0;
825 }
826
827 unsigned FastISel::FastEmit_rri(MVT, MVT,
828                                 unsigned,
829                                 unsigned /*Op0*/, unsigned /*Op1*/,
830                                 uint64_t /*Imm*/) {
831   return 0;
832 }
833
834 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
835 /// to emit an instruction with an immediate operand using FastEmit_ri.
836 /// If that fails, it materializes the immediate into a register and try
837 /// FastEmit_rr instead.
838 unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode,
839                                 unsigned Op0, uint64_t Imm,
840                                 MVT ImmType) {
841   // First check if immediate type is legal. If not, we can't use the ri form.
842   unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Imm);
843   if (ResultReg != 0)
844     return ResultReg;
845   unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
846   if (MaterialReg == 0)
847     return 0;
848   return FastEmit_rr(VT, VT, Opcode, Op0, MaterialReg);
849 }
850
851 /// FastEmit_rf_ - This method is a wrapper of FastEmit_ri. It first tries
852 /// to emit an instruction with a floating-point immediate operand using
853 /// FastEmit_rf. If that fails, it materializes the immediate into a register
854 /// and try FastEmit_rr instead.
855 unsigned FastISel::FastEmit_rf_(MVT VT, unsigned Opcode,
856                                 unsigned Op0, const ConstantFP *FPImm,
857                                 MVT ImmType) {
858   // First check if immediate type is legal. If not, we can't use the rf form.
859   unsigned ResultReg = FastEmit_rf(VT, VT, Opcode, Op0, FPImm);
860   if (ResultReg != 0)
861     return ResultReg;
862
863   // Materialize the constant in a register.
864   unsigned MaterialReg = FastEmit_f(ImmType, ImmType, ISD::ConstantFP, FPImm);
865   if (MaterialReg == 0) {
866     // If the target doesn't have a way to directly enter a floating-point
867     // value into a register, use an alternate approach.
868     // TODO: The current approach only supports floating-point constants
869     // that can be constructed by conversion from integer values. This should
870     // be replaced by code that creates a load from a constant-pool entry,
871     // which will require some target-specific work.
872     const APFloat &Flt = FPImm->getValueAPF();
873     EVT IntVT = TLI.getPointerTy();
874
875     uint64_t x[2];
876     uint32_t IntBitWidth = IntVT.getSizeInBits();
877     bool isExact;
878     (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
879                              APFloat::rmTowardZero, &isExact);
880     if (!isExact)
881       return 0;
882     APInt IntVal(IntBitWidth, 2, x);
883
884     unsigned IntegerReg = FastEmit_i(IntVT.getSimpleVT(), IntVT.getSimpleVT(),
885                                      ISD::Constant, IntVal.getZExtValue());
886     if (IntegerReg == 0)
887       return 0;
888     MaterialReg = FastEmit_r(IntVT.getSimpleVT(), VT,
889                              ISD::SINT_TO_FP, IntegerReg);
890     if (MaterialReg == 0)
891       return 0;
892   }
893   return FastEmit_rr(VT, VT, Opcode, Op0, MaterialReg);
894 }
895
896 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
897   return MRI.createVirtualRegister(RC);
898 }
899
900 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
901                                  const TargetRegisterClass* RC) {
902   unsigned ResultReg = createResultReg(RC);
903   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
904
905   BuildMI(MBB, DL, II, ResultReg);
906   return ResultReg;
907 }
908
909 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
910                                   const TargetRegisterClass *RC,
911                                   unsigned Op0) {
912   unsigned ResultReg = createResultReg(RC);
913   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
914
915   if (II.getNumDefs() >= 1)
916     BuildMI(MBB, DL, II, ResultReg).addReg(Op0);
917   else {
918     BuildMI(MBB, DL, II).addReg(Op0);
919     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
920                                          II.ImplicitDefs[0], RC, RC);
921     if (!InsertedCopy)
922       ResultReg = 0;
923   }
924
925   return ResultReg;
926 }
927
928 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
929                                    const TargetRegisterClass *RC,
930                                    unsigned Op0, unsigned Op1) {
931   unsigned ResultReg = createResultReg(RC);
932   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
933
934   if (II.getNumDefs() >= 1)
935     BuildMI(MBB, DL, II, ResultReg).addReg(Op0).addReg(Op1);
936   else {
937     BuildMI(MBB, DL, II).addReg(Op0).addReg(Op1);
938     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
939                                          II.ImplicitDefs[0], RC, RC);
940     if (!InsertedCopy)
941       ResultReg = 0;
942   }
943   return ResultReg;
944 }
945
946 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
947                                    const TargetRegisterClass *RC,
948                                    unsigned Op0, uint64_t Imm) {
949   unsigned ResultReg = createResultReg(RC);
950   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
951
952   if (II.getNumDefs() >= 1)
953     BuildMI(MBB, DL, II, ResultReg).addReg(Op0).addImm(Imm);
954   else {
955     BuildMI(MBB, DL, II).addReg(Op0).addImm(Imm);
956     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
957                                          II.ImplicitDefs[0], RC, RC);
958     if (!InsertedCopy)
959       ResultReg = 0;
960   }
961   return ResultReg;
962 }
963
964 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
965                                    const TargetRegisterClass *RC,
966                                    unsigned Op0, const ConstantFP *FPImm) {
967   unsigned ResultReg = createResultReg(RC);
968   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
969
970   if (II.getNumDefs() >= 1)
971     BuildMI(MBB, DL, II, ResultReg).addReg(Op0).addFPImm(FPImm);
972   else {
973     BuildMI(MBB, DL, II).addReg(Op0).addFPImm(FPImm);
974     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
975                                          II.ImplicitDefs[0], RC, RC);
976     if (!InsertedCopy)
977       ResultReg = 0;
978   }
979   return ResultReg;
980 }
981
982 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
983                                     const TargetRegisterClass *RC,
984                                     unsigned Op0, unsigned Op1, uint64_t Imm) {
985   unsigned ResultReg = createResultReg(RC);
986   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
987
988   if (II.getNumDefs() >= 1)
989     BuildMI(MBB, DL, II, ResultReg).addReg(Op0).addReg(Op1).addImm(Imm);
990   else {
991     BuildMI(MBB, DL, II).addReg(Op0).addReg(Op1).addImm(Imm);
992     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
993                                          II.ImplicitDefs[0], RC, RC);
994     if (!InsertedCopy)
995       ResultReg = 0;
996   }
997   return ResultReg;
998 }
999
1000 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
1001                                   const TargetRegisterClass *RC,
1002                                   uint64_t Imm) {
1003   unsigned ResultReg = createResultReg(RC);
1004   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
1005   
1006   if (II.getNumDefs() >= 1)
1007     BuildMI(MBB, DL, II, ResultReg).addImm(Imm);
1008   else {
1009     BuildMI(MBB, DL, II).addImm(Imm);
1010     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
1011                                          II.ImplicitDefs[0], RC, RC);
1012     if (!InsertedCopy)
1013       ResultReg = 0;
1014   }
1015   return ResultReg;
1016 }
1017
1018 unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT,
1019                                               unsigned Op0, uint32_t Idx) {
1020   const TargetRegisterClass* RC = MRI.getRegClass(Op0);
1021   
1022   unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1023   const TargetInstrDesc &II = TII.get(TargetOpcode::EXTRACT_SUBREG);
1024   
1025   if (II.getNumDefs() >= 1)
1026     BuildMI(MBB, DL, II, ResultReg).addReg(Op0).addImm(Idx);
1027   else {
1028     BuildMI(MBB, DL, II).addReg(Op0).addImm(Idx);
1029     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
1030                                          II.ImplicitDefs[0], RC, RC);
1031     if (!InsertedCopy)
1032       ResultReg = 0;
1033   }
1034   return ResultReg;
1035 }
1036
1037 /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
1038 /// with all but the least significant bit set to zero.
1039 unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op) {
1040   return FastEmit_ri(VT, VT, ISD::AND, Op, 1);
1041 }
1042
1043 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
1044 /// Emit code to ensure constants are copied into registers when needed.
1045 /// Remember the virtual registers that need to be added to the Machine PHI
1046 /// nodes as input.  We cannot just directly add them, because expansion
1047 /// might result in multiple MBB's for one BB.  As such, the start of the
1048 /// BB might correspond to a different MBB than the end.
1049 bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
1050   const TerminatorInst *TI = LLVMBB->getTerminator();
1051
1052   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
1053   unsigned OrigNumPHINodesToUpdate = PHINodesToUpdate.size();
1054
1055   // Check successor nodes' PHI nodes that expect a constant to be available
1056   // from this block.
1057   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1058     const BasicBlock *SuccBB = TI->getSuccessor(succ);
1059     if (!isa<PHINode>(SuccBB->begin())) continue;
1060     MachineBasicBlock *SuccMBB = MBBMap[SuccBB];
1061
1062     // If this terminator has multiple identical successors (common for
1063     // switches), only handle each succ once.
1064     if (!SuccsHandled.insert(SuccMBB)) continue;
1065
1066     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
1067
1068     // At this point we know that there is a 1-1 correspondence between LLVM PHI
1069     // nodes and Machine PHI nodes, but the incoming operands have not been
1070     // emitted yet.
1071     for (BasicBlock::const_iterator I = SuccBB->begin();
1072          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1073       // Ignore dead phi's.
1074       if (PN->use_empty()) continue;
1075
1076       // Only handle legal types. Two interesting things to note here. First,
1077       // by bailing out early, we may leave behind some dead instructions,
1078       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
1079       // own moves. Second, this check is necessary becuase FastISel doesn't
1080       // use CreateRegForValue to create registers, so it always creates
1081       // exactly one register for each non-void instruction.
1082       EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
1083       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
1084         // Promote MVT::i1.
1085         if (VT == MVT::i1)
1086           VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
1087         else {
1088           PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1089           return false;
1090         }
1091       }
1092
1093       const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1094
1095       unsigned Reg = getRegForValue(PHIOp);
1096       if (Reg == 0) {
1097         PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1098         return false;
1099       }
1100       PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
1101     }
1102   }
1103
1104   return true;
1105 }