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