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