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