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