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