Correct partially defined variable
[oota-llvm.git] / lib / Target / PowerPC / PPCFastISel.cpp
1 //===-- PPCFastISel.cpp - PowerPC FastISel implementation -----------------===//
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 defines the PowerPC-specific support for the FastISel class. Some
11 // of the target-specific code is generated by tablegen in the file
12 // PPCGenFastISel.inc, which is #included here.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "ppcfastisel"
17 #include "PPC.h"
18 #include "PPCISelLowering.h"
19 #include "PPCSubtarget.h"
20 #include "PPCTargetMachine.h"
21 #include "MCTargetDesc/PPCPredicates.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/FastISel.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetMachine.h"
39
40 using namespace llvm;
41
42 namespace {
43
44 typedef struct Address {
45   enum {
46     RegBase,
47     FrameIndexBase
48   } BaseType;
49
50   union {
51     unsigned Reg;
52     int FI;
53   } Base;
54
55   long Offset;
56
57   // Innocuous defaults for our address.
58   Address()
59    : BaseType(RegBase), Offset(0) {
60      Base.Reg = 0;
61    }
62 } Address;
63
64 class PPCFastISel : public FastISel {
65
66   const TargetMachine &TM;
67   const TargetInstrInfo &TII;
68   const TargetLowering &TLI;
69   const PPCSubtarget &PPCSubTarget;
70   LLVMContext *Context;
71
72   public:
73     explicit PPCFastISel(FunctionLoweringInfo &FuncInfo,
74                          const TargetLibraryInfo *LibInfo)
75     : FastISel(FuncInfo, LibInfo),
76       TM(FuncInfo.MF->getTarget()),
77       TII(*TM.getInstrInfo()),
78       TLI(*TM.getTargetLowering()),
79       PPCSubTarget(
80        *((static_cast<const PPCTargetMachine *>(&TM))->getSubtargetImpl())
81       ),
82       Context(&FuncInfo.Fn->getContext()) { }
83
84   // Backend specific FastISel code.
85   private:
86     virtual bool TargetSelectInstruction(const Instruction *I);
87     virtual unsigned TargetMaterializeConstant(const Constant *C);
88     virtual unsigned TargetMaterializeAlloca(const AllocaInst *AI);
89     virtual bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
90                                      const LoadInst *LI);
91     virtual bool FastLowerArguments();
92     virtual unsigned FastEmit_i(MVT Ty, MVT RetTy, unsigned Opc, uint64_t Imm);
93     virtual unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
94                                      const TargetRegisterClass *RC,
95                                      unsigned Op0, bool Op0IsKill,
96                                      uint64_t Imm);
97     virtual unsigned FastEmitInst_r(unsigned MachineInstOpcode,
98                                     const TargetRegisterClass *RC,
99                                     unsigned Op0, bool Op0IsKill);
100     virtual unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
101                                      const TargetRegisterClass *RC,
102                                      unsigned Op0, bool Op0IsKill,
103                                      unsigned Op1, bool Op1IsKill);
104
105   // Instruction selection routines.
106   private:
107     bool SelectLoad(const Instruction *I);
108     bool SelectStore(const Instruction *I);
109     bool SelectBranch(const Instruction *I);
110     bool SelectIndirectBr(const Instruction *I);
111     bool SelectCmp(const Instruction *I);
112     bool SelectFPExt(const Instruction *I);
113     bool SelectFPTrunc(const Instruction *I);
114     bool SelectIToFP(const Instruction *I, bool IsSigned);
115     bool SelectFPToI(const Instruction *I, bool IsSigned);
116     bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
117     bool SelectCall(const Instruction *I);
118     bool SelectRet(const Instruction *I);
119     bool SelectIntExt(const Instruction *I);
120
121   // Utility routines.
122   private:
123     bool isTypeLegal(Type *Ty, MVT &VT);
124     bool isLoadTypeLegal(Type *Ty, MVT &VT);
125     bool PPCEmitCmp(const Value *Src1Value, const Value *Src2Value,
126                     bool isZExt, unsigned DestReg);
127     bool PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
128                      const TargetRegisterClass *RC, bool IsZExt = true,
129                      unsigned FP64LoadOpc = PPC::LFD);
130     bool PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr);
131     bool PPCComputeAddress(const Value *Obj, Address &Addr);
132     void PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
133                             unsigned &IndexReg);
134     bool PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
135                            unsigned DestReg, bool IsZExt);
136     unsigned PPCMaterializeFP(const ConstantFP *CFP, MVT VT);
137     unsigned PPCMaterializeGV(const GlobalValue *GV, MVT VT);
138     unsigned PPCMaterializeInt(const Constant *C, MVT VT);
139     unsigned PPCMaterialize32BitInt(int64_t Imm,
140                                     const TargetRegisterClass *RC);
141     unsigned PPCMaterialize64BitInt(int64_t Imm,
142                                     const TargetRegisterClass *RC);
143     unsigned PPCMoveToIntReg(const Instruction *I, MVT VT,
144                              unsigned SrcReg, bool IsSigned);
145     unsigned PPCMoveToFPReg(MVT VT, unsigned SrcReg, bool IsSigned);
146
147   // Call handling routines.
148   private:
149     bool processCallArgs(SmallVectorImpl<Value*> &Args,
150                          SmallVectorImpl<unsigned> &ArgRegs,
151                          SmallVectorImpl<MVT> &ArgVTs,
152                          SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
153                          SmallVectorImpl<unsigned> &RegArgs,
154                          CallingConv::ID CC,
155                          unsigned &NumBytes,
156                          bool IsVarArg);
157     void finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
158                     const Instruction *I, CallingConv::ID CC,
159                     unsigned &NumBytes, bool IsVarArg);
160     CCAssignFn *usePPC32CCs(unsigned Flag);
161
162   private:
163   #include "PPCGenFastISel.inc"
164
165 };
166
167 } // end anonymous namespace
168
169 #include "PPCGenCallingConv.inc"
170
171 // Function whose sole purpose is to kill compiler warnings 
172 // stemming from unused functions included from PPCGenCallingConv.inc.
173 CCAssignFn *PPCFastISel::usePPC32CCs(unsigned Flag) {
174   if (Flag == 1)
175     return CC_PPC32_SVR4;
176   else if (Flag == 2)
177     return CC_PPC32_SVR4_ByVal;
178   else if (Flag == 3)
179     return CC_PPC32_SVR4_VarArg;
180   else
181     return RetCC_PPC;
182 }
183
184 static Optional<PPC::Predicate> getComparePred(CmpInst::Predicate Pred) {
185   switch (Pred) {
186     // These are not representable with any single compare.
187     case CmpInst::FCMP_FALSE:
188     case CmpInst::FCMP_UEQ:
189     case CmpInst::FCMP_UGT:
190     case CmpInst::FCMP_UGE:
191     case CmpInst::FCMP_ULT:
192     case CmpInst::FCMP_ULE:
193     case CmpInst::FCMP_UNE:
194     case CmpInst::FCMP_TRUE:
195     default:
196       return Optional<PPC::Predicate>();
197
198     case CmpInst::FCMP_OEQ:
199     case CmpInst::ICMP_EQ:
200       return PPC::PRED_EQ;
201
202     case CmpInst::FCMP_OGT:
203     case CmpInst::ICMP_UGT:
204     case CmpInst::ICMP_SGT:
205       return PPC::PRED_GT;
206
207     case CmpInst::FCMP_OGE:
208     case CmpInst::ICMP_UGE:
209     case CmpInst::ICMP_SGE:
210       return PPC::PRED_GE;
211
212     case CmpInst::FCMP_OLT:
213     case CmpInst::ICMP_ULT:
214     case CmpInst::ICMP_SLT:
215       return PPC::PRED_LT;
216
217     case CmpInst::FCMP_OLE:
218     case CmpInst::ICMP_ULE:
219     case CmpInst::ICMP_SLE:
220       return PPC::PRED_LE;
221
222     case CmpInst::FCMP_ONE:
223     case CmpInst::ICMP_NE:
224       return PPC::PRED_NE;
225
226     case CmpInst::FCMP_ORD:
227       return PPC::PRED_NU;
228
229     case CmpInst::FCMP_UNO:
230       return PPC::PRED_UN;
231   }
232 }
233
234 // Determine whether the type Ty is simple enough to be handled by
235 // fast-isel, and return its equivalent machine type in VT.
236 // FIXME: Copied directly from ARM -- factor into base class?
237 bool PPCFastISel::isTypeLegal(Type *Ty, MVT &VT) {
238   EVT Evt = TLI.getValueType(Ty, true);
239
240   // Only handle simple types.
241   if (Evt == MVT::Other || !Evt.isSimple()) return false;
242   VT = Evt.getSimpleVT();
243
244   // Handle all legal types, i.e. a register that will directly hold this
245   // value.
246   return TLI.isTypeLegal(VT);
247 }
248
249 // Determine whether the type Ty is simple enough to be handled by
250 // fast-isel as a load target, and return its equivalent machine type in VT.
251 bool PPCFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
252   if (isTypeLegal(Ty, VT)) return true;
253
254   // If this is a type than can be sign or zero-extended to a basic operation
255   // go ahead and accept it now.
256   if (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) {
257     return true;
258   }
259
260   return false;
261 }
262
263 // Given a value Obj, create an Address object Addr that represents its
264 // address.  Return false if we can't handle it.
265 bool PPCFastISel::PPCComputeAddress(const Value *Obj, Address &Addr) {
266   const User *U = NULL;
267   unsigned Opcode = Instruction::UserOp1;
268   if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
269     // Don't walk into other basic blocks unless the object is an alloca from
270     // another block, otherwise it may not have a virtual register assigned.
271     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
272         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
273       Opcode = I->getOpcode();
274       U = I;
275     }
276   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
277     Opcode = C->getOpcode();
278     U = C;
279   }
280
281   switch (Opcode) {
282     default:
283       break;
284     case Instruction::BitCast:
285       // Look through bitcasts.
286       return PPCComputeAddress(U->getOperand(0), Addr);
287     case Instruction::IntToPtr:
288       // Look past no-op inttoptrs.
289       if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
290         return PPCComputeAddress(U->getOperand(0), Addr);
291       break;
292     case Instruction::PtrToInt:
293       // Look past no-op ptrtoints.
294       if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
295         return PPCComputeAddress(U->getOperand(0), Addr);
296       break;
297     case Instruction::GetElementPtr: {
298       Address SavedAddr = Addr;
299       long TmpOffset = Addr.Offset;
300
301       // Iterate through the GEP folding the constants into offsets where
302       // we can.
303       gep_type_iterator GTI = gep_type_begin(U);
304       for (User::const_op_iterator II = U->op_begin() + 1, IE = U->op_end();
305            II != IE; ++II, ++GTI) {
306         const Value *Op = *II;
307         if (StructType *STy = dyn_cast<StructType>(*GTI)) {
308           const StructLayout *SL = TD.getStructLayout(STy);
309           unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
310           TmpOffset += SL->getElementOffset(Idx);
311         } else {
312           uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
313           for (;;) {
314             if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
315               // Constant-offset addressing.
316               TmpOffset += CI->getSExtValue() * S;
317               break;
318             }
319             if (isa<AddOperator>(Op) &&
320                 (!isa<Instruction>(Op) ||
321                  FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
322                  == FuncInfo.MBB) &&
323                 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
324               // An add (in the same block) with a constant operand. Fold the
325               // constant.
326               ConstantInt *CI =
327               cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
328               TmpOffset += CI->getSExtValue() * S;
329               // Iterate on the other operand.
330               Op = cast<AddOperator>(Op)->getOperand(0);
331               continue;
332             }
333             // Unsupported
334             goto unsupported_gep;
335           }
336         }
337       }
338
339       // Try to grab the base operand now.
340       Addr.Offset = TmpOffset;
341       if (PPCComputeAddress(U->getOperand(0), Addr)) return true;
342
343       // We failed, restore everything and try the other options.
344       Addr = SavedAddr;
345
346       unsupported_gep:
347       break;
348     }
349     case Instruction::Alloca: {
350       const AllocaInst *AI = cast<AllocaInst>(Obj);
351       DenseMap<const AllocaInst*, int>::iterator SI =
352         FuncInfo.StaticAllocaMap.find(AI);
353       if (SI != FuncInfo.StaticAllocaMap.end()) {
354         Addr.BaseType = Address::FrameIndexBase;
355         Addr.Base.FI = SI->second;
356         return true;
357       }
358       break;
359     }
360   }
361
362   // FIXME: References to parameters fall through to the behavior
363   // below.  They should be able to reference a frame index since
364   // they are stored to the stack, so we can get "ld rx, offset(r1)"
365   // instead of "addi ry, r1, offset / ld rx, 0(ry)".  Obj will
366   // just contain the parameter.  Try to handle this with a FI.
367
368   // Try to get this in a register if nothing else has worked.
369   if (Addr.Base.Reg == 0)
370     Addr.Base.Reg = getRegForValue(Obj);
371
372   // Prevent assignment of base register to X0, which is inappropriate
373   // for loads and stores alike.
374   if (Addr.Base.Reg != 0)
375     MRI.setRegClass(Addr.Base.Reg, &PPC::G8RC_and_G8RC_NOX0RegClass);
376
377   return Addr.Base.Reg != 0;
378 }
379
380 // Fix up some addresses that can't be used directly.  For example, if
381 // an offset won't fit in an instruction field, we may need to move it
382 // into an index register.
383 void PPCFastISel::PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
384                                      unsigned &IndexReg) {
385
386   // Check whether the offset fits in the instruction field.
387   if (!isInt<16>(Addr.Offset))
388     UseOffset = false;
389
390   // If this is a stack pointer and the offset needs to be simplified then
391   // put the alloca address into a register, set the base type back to
392   // register and continue. This should almost never happen.
393   if (!UseOffset && Addr.BaseType == Address::FrameIndexBase) {
394     unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
395     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDI8),
396             ResultReg).addFrameIndex(Addr.Base.FI).addImm(0);
397     Addr.Base.Reg = ResultReg;
398     Addr.BaseType = Address::RegBase;
399   }
400
401   if (!UseOffset) {
402     IntegerType *OffsetTy = ((VT == MVT::i32) ? Type::getInt32Ty(*Context)
403                              : Type::getInt64Ty(*Context));
404     const ConstantInt *Offset =
405       ConstantInt::getSigned(OffsetTy, (int64_t)(Addr.Offset));
406     IndexReg = PPCMaterializeInt(Offset, MVT::i64);
407     assert(IndexReg && "Unexpected error in PPCMaterializeInt!");
408   }
409 }
410
411 // Emit a load instruction if possible, returning true if we succeeded,
412 // otherwise false.  See commentary below for how the register class of
413 // the load is determined. 
414 bool PPCFastISel::PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
415                               const TargetRegisterClass *RC,
416                               bool IsZExt, unsigned FP64LoadOpc) {
417   unsigned Opc;
418   bool UseOffset = true;
419
420   // If ResultReg is given, it determines the register class of the load.
421   // Otherwise, RC is the register class to use.  If the result of the
422   // load isn't anticipated in this block, both may be zero, in which
423   // case we must make a conservative guess.  In particular, don't assign
424   // R0 or X0 to the result register, as the result may be used in a load,
425   // store, add-immediate, or isel that won't permit this.  (Though
426   // perhaps the spill and reload of live-exit values would handle this?)
427   const TargetRegisterClass *UseRC =
428     (ResultReg ? MRI.getRegClass(ResultReg) :
429      (RC ? RC :
430       (VT == MVT::f64 ? &PPC::F8RCRegClass :
431        (VT == MVT::f32 ? &PPC::F4RCRegClass :
432         (VT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
433          &PPC::GPRC_and_GPRC_NOR0RegClass)))));
434
435   bool Is32BitInt = UseRC->hasSuperClassEq(&PPC::GPRCRegClass);
436
437   switch (VT.SimpleTy) {
438     default: // e.g., vector types not handled
439       return false;
440     case MVT::i8:
441       Opc = Is32BitInt ? PPC::LBZ : PPC::LBZ8;
442       break;
443     case MVT::i16:
444       Opc = (IsZExt ?
445              (Is32BitInt ? PPC::LHZ : PPC::LHZ8) : 
446              (Is32BitInt ? PPC::LHA : PPC::LHA8));
447       break;
448     case MVT::i32:
449       Opc = (IsZExt ? 
450              (Is32BitInt ? PPC::LWZ : PPC::LWZ8) :
451              (Is32BitInt ? PPC::LWA_32 : PPC::LWA));
452       if ((Opc == PPC::LWA || Opc == PPC::LWA_32) && ((Addr.Offset & 3) != 0))
453         UseOffset = false;
454       break;
455     case MVT::i64:
456       Opc = PPC::LD;
457       assert(UseRC->hasSuperClassEq(&PPC::G8RCRegClass) && 
458              "64-bit load with 32-bit target??");
459       UseOffset = ((Addr.Offset & 3) == 0);
460       break;
461     case MVT::f32:
462       Opc = PPC::LFS;
463       break;
464     case MVT::f64:
465       Opc = FP64LoadOpc;
466       break;
467   }
468
469   // If necessary, materialize the offset into a register and use
470   // the indexed form.  Also handle stack pointers with special needs.
471   unsigned IndexReg = 0;
472   PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
473   if (ResultReg == 0)
474     ResultReg = createResultReg(UseRC);
475
476   // Note: If we still have a frame index here, we know the offset is
477   // in range, as otherwise PPCSimplifyAddress would have converted it
478   // into a RegBase.
479   if (Addr.BaseType == Address::FrameIndexBase) {
480
481     MachineMemOperand *MMO =
482       FuncInfo.MF->getMachineMemOperand(
483         MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
484         MachineMemOperand::MOLoad, MFI.getObjectSize(Addr.Base.FI),
485         MFI.getObjectAlignment(Addr.Base.FI));
486
487     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
488       .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
489
490   // Base reg with offset in range.
491   } else if (UseOffset) {
492
493     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
494       .addImm(Addr.Offset).addReg(Addr.Base.Reg);
495
496   // Indexed form.
497   } else {
498     // Get the RR opcode corresponding to the RI one.  FIXME: It would be
499     // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
500     // is hard to get at.
501     switch (Opc) {
502       default:        llvm_unreachable("Unexpected opcode!");
503       case PPC::LBZ:    Opc = PPC::LBZX;    break;
504       case PPC::LBZ8:   Opc = PPC::LBZX8;   break;
505       case PPC::LHZ:    Opc = PPC::LHZX;    break;
506       case PPC::LHZ8:   Opc = PPC::LHZX8;   break;
507       case PPC::LHA:    Opc = PPC::LHAX;    break;
508       case PPC::LHA8:   Opc = PPC::LHAX8;   break;
509       case PPC::LWZ:    Opc = PPC::LWZX;    break;
510       case PPC::LWZ8:   Opc = PPC::LWZX8;   break;
511       case PPC::LWA:    Opc = PPC::LWAX;    break;
512       case PPC::LWA_32: Opc = PPC::LWAX_32; break;
513       case PPC::LD:     Opc = PPC::LDX;     break;
514       case PPC::LFS:    Opc = PPC::LFSX;    break;
515       case PPC::LFD:    Opc = PPC::LFDX;    break;
516     }
517     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
518       .addReg(Addr.Base.Reg).addReg(IndexReg);
519   }
520
521   return true;
522 }
523
524 // Attempt to fast-select a load instruction.
525 bool PPCFastISel::SelectLoad(const Instruction *I) {
526   // FIXME: No atomic loads are supported.
527   if (cast<LoadInst>(I)->isAtomic())
528     return false;
529
530   // Verify we have a legal type before going any further.
531   MVT VT;
532   if (!isLoadTypeLegal(I->getType(), VT))
533     return false;
534
535   // See if we can handle this address.
536   Address Addr;
537   if (!PPCComputeAddress(I->getOperand(0), Addr))
538     return false;
539
540   // Look at the currently assigned register for this instruction
541   // to determine the required register class.  This is necessary
542   // to constrain RA from using R0/X0 when this is not legal.
543   unsigned AssignedReg = FuncInfo.ValueMap[I];
544   const TargetRegisterClass *RC =
545     AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
546
547   unsigned ResultReg = 0;
548   if (!PPCEmitLoad(VT, ResultReg, Addr, RC))
549     return false;
550   UpdateValueMap(I, ResultReg);
551   return true;
552 }
553
554 // Emit a store instruction to store SrcReg at Addr.
555 bool PPCFastISel::PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr) {
556   assert(SrcReg && "Nothing to store!");
557   unsigned Opc;
558   bool UseOffset = true;
559
560   const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
561   bool Is32BitInt = RC->hasSuperClassEq(&PPC::GPRCRegClass);
562
563   switch (VT.SimpleTy) {
564     default: // e.g., vector types not handled
565       return false;
566     case MVT::i8:
567       Opc = Is32BitInt ? PPC::STB : PPC::STB8;
568       break;
569     case MVT::i16:
570       Opc = Is32BitInt ? PPC::STH : PPC::STH8;
571       break;
572     case MVT::i32:
573       assert(Is32BitInt && "Not GPRC for i32??");
574       Opc = PPC::STW;
575       break;
576     case MVT::i64:
577       Opc = PPC::STD;
578       UseOffset = ((Addr.Offset & 3) == 0);
579       break;
580     case MVT::f32:
581       Opc = PPC::STFS;
582       break;
583     case MVT::f64:
584       Opc = PPC::STFD;
585       break;
586   }
587
588   // If necessary, materialize the offset into a register and use
589   // the indexed form.  Also handle stack pointers with special needs.
590   unsigned IndexReg = 0;
591   PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
592
593   // Note: If we still have a frame index here, we know the offset is
594   // in range, as otherwise PPCSimplifyAddress would have converted it
595   // into a RegBase.
596   if (Addr.BaseType == Address::FrameIndexBase) {
597     MachineMemOperand *MMO =
598       FuncInfo.MF->getMachineMemOperand(
599         MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
600         MachineMemOperand::MOStore, MFI.getObjectSize(Addr.Base.FI),
601         MFI.getObjectAlignment(Addr.Base.FI));
602
603     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc)).addReg(SrcReg)
604       .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
605
606   // Base reg with offset in range.
607   } else if (UseOffset)
608     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
609       .addReg(SrcReg).addImm(Addr.Offset).addReg(Addr.Base.Reg);
610
611   // Indexed form.
612   else {
613     // Get the RR opcode corresponding to the RI one.  FIXME: It would be
614     // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
615     // is hard to get at.
616     switch (Opc) {
617       default:        llvm_unreachable("Unexpected opcode!");
618       case PPC::STB:  Opc = PPC::STBX;  break;
619       case PPC::STH : Opc = PPC::STHX;  break;
620       case PPC::STW : Opc = PPC::STWX;  break;
621       case PPC::STB8: Opc = PPC::STBX8; break;
622       case PPC::STH8: Opc = PPC::STHX8; break;
623       case PPC::STW8: Opc = PPC::STWX8; break;
624       case PPC::STD:  Opc = PPC::STDX;  break;
625       case PPC::STFS: Opc = PPC::STFSX; break;
626       case PPC::STFD: Opc = PPC::STFDX; break;
627     }
628     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
629       .addReg(SrcReg).addReg(Addr.Base.Reg).addReg(IndexReg);
630   }
631
632   return true;
633 }
634
635 // Attempt to fast-select a store instruction.
636 bool PPCFastISel::SelectStore(const Instruction *I) {
637   Value *Op0 = I->getOperand(0);
638   unsigned SrcReg = 0;
639
640   // FIXME: No atomics loads are supported.
641   if (cast<StoreInst>(I)->isAtomic())
642     return false;
643
644   // Verify we have a legal type before going any further.
645   MVT VT;
646   if (!isLoadTypeLegal(Op0->getType(), VT))
647     return false;
648
649   // Get the value to be stored into a register.
650   SrcReg = getRegForValue(Op0);
651   if (SrcReg == 0)
652     return false;
653
654   // See if we can handle this address.
655   Address Addr;
656   if (!PPCComputeAddress(I->getOperand(1), Addr))
657     return false;
658
659   if (!PPCEmitStore(VT, SrcReg, Addr))
660     return false;
661
662   return true;
663 }
664
665 // Attempt to fast-select a branch instruction.
666 bool PPCFastISel::SelectBranch(const Instruction *I) {
667   const BranchInst *BI = cast<BranchInst>(I);
668   MachineBasicBlock *BrBB = FuncInfo.MBB;
669   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
670   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
671
672   // For now, just try the simplest case where it's fed by a compare.
673   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
674     Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
675     if (!OptPPCPred)
676       return false;
677
678     PPC::Predicate PPCPred = OptPPCPred.getValue();
679
680     // Take advantage of fall-through opportunities.
681     if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
682       std::swap(TBB, FBB);
683       PPCPred = PPC::InvertPredicate(PPCPred);
684     }
685
686     unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
687
688     if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
689                     CondReg))
690       return false;
691
692     BuildMI(*BrBB, FuncInfo.InsertPt, DL, TII.get(PPC::BCC))
693       .addImm(PPCPred).addReg(CondReg).addMBB(TBB);
694     FastEmitBranch(FBB, DL);
695     FuncInfo.MBB->addSuccessor(TBB);
696     return true;
697
698   } else if (const ConstantInt *CI =
699              dyn_cast<ConstantInt>(BI->getCondition())) {
700     uint64_t Imm = CI->getZExtValue();
701     MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
702     FastEmitBranch(Target, DL);
703     return true;
704   }
705
706   // FIXME: ARM looks for a case where the block containing the compare
707   // has been split from the block containing the branch.  If this happens,
708   // there is a vreg available containing the result of the compare.  I'm
709   // not sure we can do much, as we've lost the predicate information with
710   // the compare instruction -- we have a 4-bit CR but don't know which bit
711   // to test here.
712   return false;
713 }
714
715 // Attempt to emit a compare of the two source values.  Signed and unsigned
716 // comparisons are supported.  Return false if we can't handle it.
717 bool PPCFastISel::PPCEmitCmp(const Value *SrcValue1, const Value *SrcValue2,
718                              bool IsZExt, unsigned DestReg) {
719   Type *Ty = SrcValue1->getType();
720   EVT SrcEVT = TLI.getValueType(Ty, true);
721   if (!SrcEVT.isSimple())
722     return false;
723   MVT SrcVT = SrcEVT.getSimpleVT();
724
725   // See if operand 2 is an immediate encodeable in the compare.
726   // FIXME: Operands are not in canonical order at -O0, so an immediate
727   // operand in position 1 is a lost opportunity for now.  We are
728   // similar to ARM in this regard.
729   long Imm = 0;
730   bool UseImm = false;
731
732   // Only 16-bit integer constants can be represented in compares for 
733   // PowerPC.  Others will be materialized into a register.
734   if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(SrcValue2)) {
735     if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
736         SrcVT == MVT::i8 || SrcVT == MVT::i1) {
737       const APInt &CIVal = ConstInt->getValue();
738       Imm = (IsZExt) ? (long)CIVal.getZExtValue() : (long)CIVal.getSExtValue();
739       if ((IsZExt && isUInt<16>(Imm)) || (!IsZExt && isInt<16>(Imm)))
740         UseImm = true;
741     }
742   }
743
744   unsigned CmpOpc;
745   bool NeedsExt = false;
746   switch (SrcVT.SimpleTy) {
747     default: return false;
748     case MVT::f32:
749       CmpOpc = PPC::FCMPUS;
750       break;
751     case MVT::f64:
752       CmpOpc = PPC::FCMPUD;
753       break;
754     case MVT::i1:
755     case MVT::i8:
756     case MVT::i16:
757       NeedsExt = true;
758       // Intentional fall-through.
759     case MVT::i32:
760       if (!UseImm)
761         CmpOpc = IsZExt ? PPC::CMPLW : PPC::CMPW;
762       else
763         CmpOpc = IsZExt ? PPC::CMPLWI : PPC::CMPWI;
764       break;
765     case MVT::i64:
766       if (!UseImm)
767         CmpOpc = IsZExt ? PPC::CMPLD : PPC::CMPD;
768       else
769         CmpOpc = IsZExt ? PPC::CMPLDI : PPC::CMPDI;
770       break;
771   }
772
773   unsigned SrcReg1 = getRegForValue(SrcValue1);
774   if (SrcReg1 == 0)
775     return false;
776
777   unsigned SrcReg2 = 0;
778   if (!UseImm) {
779     SrcReg2 = getRegForValue(SrcValue2);
780     if (SrcReg2 == 0)
781       return false;
782   }
783
784   if (NeedsExt) {
785     unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
786     if (!PPCEmitIntExt(SrcVT, SrcReg1, MVT::i32, ExtReg, IsZExt))
787       return false;
788     SrcReg1 = ExtReg;
789
790     if (!UseImm) {
791       unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
792       if (!PPCEmitIntExt(SrcVT, SrcReg2, MVT::i32, ExtReg, IsZExt))
793         return false;
794       SrcReg2 = ExtReg;
795     }
796   }
797
798   if (!UseImm)
799     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc), DestReg)
800       .addReg(SrcReg1).addReg(SrcReg2);
801   else
802     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc), DestReg)
803       .addReg(SrcReg1).addImm(Imm);
804
805   return true;
806 }
807
808 // Attempt to fast-select a floating-point extend instruction.
809 bool PPCFastISel::SelectFPExt(const Instruction *I) {
810   Value *Src  = I->getOperand(0);
811   EVT SrcVT  = TLI.getValueType(Src->getType(), true);
812   EVT DestVT = TLI.getValueType(I->getType(), true);
813
814   if (SrcVT != MVT::f32 || DestVT != MVT::f64)
815     return false;
816
817   unsigned SrcReg = getRegForValue(Src);
818   if (!SrcReg)
819     return false;
820
821   // No code is generated for a FP extend.
822   UpdateValueMap(I, SrcReg);
823   return true;
824 }
825
826 // Attempt to fast-select a floating-point truncate instruction.
827 bool PPCFastISel::SelectFPTrunc(const Instruction *I) {
828   Value *Src  = I->getOperand(0);
829   EVT SrcVT  = TLI.getValueType(Src->getType(), true);
830   EVT DestVT = TLI.getValueType(I->getType(), true);
831
832   if (SrcVT != MVT::f64 || DestVT != MVT::f32)
833     return false;
834
835   unsigned SrcReg = getRegForValue(Src);
836   if (!SrcReg)
837     return false;
838
839   // Round the result to single precision.
840   unsigned DestReg = createResultReg(&PPC::F4RCRegClass);
841   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::FRSP), DestReg)
842     .addReg(SrcReg);
843
844   UpdateValueMap(I, DestReg);
845   return true;
846 }
847
848 // Move an i32 or i64 value in a GPR to an f64 value in an FPR.
849 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
850 // those should be used instead of moving via a stack slot when the
851 // subtarget permits.
852 // FIXME: The code here is sloppy for the 4-byte case.  Can use a 4-byte
853 // stack slot and 4-byte store/load sequence.  Or just sext the 4-byte
854 // case to 8 bytes which produces tighter code but wastes stack space.
855 unsigned PPCFastISel::PPCMoveToFPReg(MVT SrcVT, unsigned SrcReg,
856                                      bool IsSigned) {
857
858   // If necessary, extend 32-bit int to 64-bit.
859   if (SrcVT == MVT::i32) {
860     unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
861     if (!PPCEmitIntExt(MVT::i32, SrcReg, MVT::i64, TmpReg, !IsSigned))
862       return 0;
863     SrcReg = TmpReg;
864   }
865
866   // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
867   Address Addr;
868   Addr.BaseType = Address::FrameIndexBase;
869   Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
870
871   // Store the value from the GPR.
872   if (!PPCEmitStore(MVT::i64, SrcReg, Addr))
873     return 0;
874
875   // Load the integer value into an FPR.  The kind of load used depends
876   // on a number of conditions.
877   unsigned LoadOpc = PPC::LFD;
878
879   if (SrcVT == MVT::i32) {
880     Addr.Offset = 4;
881     if (!IsSigned)
882       LoadOpc = PPC::LFIWZX;
883     else if (PPCSubTarget.hasLFIWAX())
884       LoadOpc = PPC::LFIWAX;
885   }
886
887   const TargetRegisterClass *RC = &PPC::F8RCRegClass;
888   unsigned ResultReg = 0;
889   if (!PPCEmitLoad(MVT::f64, ResultReg, Addr, RC, !IsSigned, LoadOpc))
890     return 0;
891
892   return ResultReg;
893 }
894
895 // Attempt to fast-select an integer-to-floating-point conversion.
896 bool PPCFastISel::SelectIToFP(const Instruction *I, bool IsSigned) {
897   MVT DstVT;
898   Type *DstTy = I->getType();
899   if (!isTypeLegal(DstTy, DstVT))
900     return false;
901
902   if (DstVT != MVT::f32 && DstVT != MVT::f64)
903     return false;
904
905   Value *Src = I->getOperand(0);
906   EVT SrcEVT = TLI.getValueType(Src->getType(), true);
907   if (!SrcEVT.isSimple())
908     return false;
909
910   MVT SrcVT = SrcEVT.getSimpleVT();
911
912   if (SrcVT != MVT::i8  && SrcVT != MVT::i16 &&
913       SrcVT != MVT::i32 && SrcVT != MVT::i64)
914     return false;
915
916   unsigned SrcReg = getRegForValue(Src);
917   if (SrcReg == 0)
918     return false;
919
920   // We can only lower an unsigned convert if we have the newer
921   // floating-point conversion operations.
922   if (!IsSigned && !PPCSubTarget.hasFPCVT())
923     return false;
924
925   // FIXME: For now we require the newer floating-point conversion operations
926   // (which are present only on P7 and A2 server models) when converting
927   // to single-precision float.  Otherwise we have to generate a lot of
928   // fiddly code to avoid double rounding.  If necessary, the fiddly code
929   // can be found in PPCTargetLowering::LowerINT_TO_FP().
930   if (DstVT == MVT::f32 && !PPCSubTarget.hasFPCVT())
931     return false;
932
933   // Extend the input if necessary.
934   if (SrcVT == MVT::i8 || SrcVT == MVT::i16) {
935     unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
936     if (!PPCEmitIntExt(SrcVT, SrcReg, MVT::i64, TmpReg, !IsSigned))
937       return false;
938     SrcVT = MVT::i64;
939     SrcReg = TmpReg;
940   }
941
942   // Move the integer value to an FPR.
943   unsigned FPReg = PPCMoveToFPReg(SrcVT, SrcReg, IsSigned);
944   if (FPReg == 0)
945     return false;
946
947   // Determine the opcode for the conversion.
948   const TargetRegisterClass *RC = &PPC::F8RCRegClass;
949   unsigned DestReg = createResultReg(RC);
950   unsigned Opc;
951
952   if (DstVT == MVT::f32)
953     Opc = IsSigned ? PPC::FCFIDS : PPC::FCFIDUS;
954   else
955     Opc = IsSigned ? PPC::FCFID : PPC::FCFIDU;
956
957   // Generate the convert.
958   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
959     .addReg(FPReg);
960
961   UpdateValueMap(I, DestReg);
962   return true;
963 }
964
965 // Move the floating-point value in SrcReg into an integer destination
966 // register, and return the register (or zero if we can't handle it).
967 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
968 // those should be used instead of moving via a stack slot when the
969 // subtarget permits.
970 unsigned PPCFastISel::PPCMoveToIntReg(const Instruction *I, MVT VT,
971                                       unsigned SrcReg, bool IsSigned) {
972   // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
973   // Note that if have STFIWX available, we could use a 4-byte stack
974   // slot for i32, but this being fast-isel we'll just go with the
975   // easiest code gen possible.
976   Address Addr;
977   Addr.BaseType = Address::FrameIndexBase;
978   Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
979
980   // Store the value from the FPR.
981   if (!PPCEmitStore(MVT::f64, SrcReg, Addr))
982     return 0;
983
984   // Reload it into a GPR.  If we want an i32, modify the address
985   // to have a 4-byte offset so we load from the right place.
986   if (VT == MVT::i32)
987     Addr.Offset = 4;
988
989   // Look at the currently assigned register for this instruction
990   // to determine the required register class.
991   unsigned AssignedReg = FuncInfo.ValueMap[I];
992   const TargetRegisterClass *RC =
993     AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
994
995   unsigned ResultReg = 0;
996   if (!PPCEmitLoad(VT, ResultReg, Addr, RC, !IsSigned))
997     return 0;
998
999   return ResultReg;
1000 }
1001
1002 // Attempt to fast-select a floating-point-to-integer conversion.
1003 bool PPCFastISel::SelectFPToI(const Instruction *I, bool IsSigned) {
1004   MVT DstVT, SrcVT;
1005   Type *DstTy = I->getType();
1006   if (!isTypeLegal(DstTy, DstVT))
1007     return false;
1008
1009   if (DstVT != MVT::i32 && DstVT != MVT::i64)
1010     return false;
1011
1012   Value *Src = I->getOperand(0);
1013   Type *SrcTy = Src->getType();
1014   if (!isTypeLegal(SrcTy, SrcVT))
1015     return false;
1016
1017   if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
1018     return false;
1019
1020   unsigned SrcReg = getRegForValue(Src);
1021   if (SrcReg == 0)
1022     return false;
1023
1024   // Convert f32 to f64 if necessary.  This is just a meaningless copy
1025   // to get the register class right.  COPY_TO_REGCLASS is needed since
1026   // a COPY from F4RC to F8RC is converted to a F4RC-F4RC copy downstream.
1027   const TargetRegisterClass *InRC = MRI.getRegClass(SrcReg);
1028   if (InRC == &PPC::F4RCRegClass) {
1029     unsigned TmpReg = createResultReg(&PPC::F8RCRegClass);
1030     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1031             TII.get(TargetOpcode::COPY_TO_REGCLASS), TmpReg)
1032       .addReg(SrcReg).addImm(PPC::F8RCRegClassID);
1033     SrcReg = TmpReg;
1034   }
1035
1036   // Determine the opcode for the conversion, which takes place
1037   // entirely within FPRs.
1038   unsigned DestReg = createResultReg(&PPC::F8RCRegClass);
1039   unsigned Opc;
1040
1041   if (DstVT == MVT::i32)
1042     if (IsSigned)
1043       Opc = PPC::FCTIWZ;
1044     else
1045       Opc = PPCSubTarget.hasFPCVT() ? PPC::FCTIWUZ : PPC::FCTIDZ;
1046   else
1047     Opc = IsSigned ? PPC::FCTIDZ : PPC::FCTIDUZ;
1048
1049   // Generate the convert.
1050   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1051     .addReg(SrcReg);
1052
1053   // Now move the integer value from a float register to an integer register.
1054   unsigned IntReg = PPCMoveToIntReg(I, DstVT, DestReg, IsSigned);
1055   if (IntReg == 0)
1056     return false;
1057
1058   UpdateValueMap(I, IntReg);
1059   return true;
1060 }
1061
1062 // Attempt to fast-select a binary integer operation that isn't already
1063 // handled automatically.
1064 bool PPCFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1065   EVT DestVT  = TLI.getValueType(I->getType(), true);
1066
1067   // We can get here in the case when we have a binary operation on a non-legal
1068   // type and the target independent selector doesn't know how to handle it.
1069   if (DestVT != MVT::i16 && DestVT != MVT::i8)
1070     return false;
1071
1072   // Look at the currently assigned register for this instruction
1073   // to determine the required register class.  If there is no register,
1074   // make a conservative choice (don't assign R0).
1075   unsigned AssignedReg = FuncInfo.ValueMap[I];
1076   const TargetRegisterClass *RC =
1077     (AssignedReg ? MRI.getRegClass(AssignedReg) :
1078      &PPC::GPRC_and_GPRC_NOR0RegClass);
1079   bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1080
1081   unsigned Opc;
1082   switch (ISDOpcode) {
1083     default: return false;
1084     case ISD::ADD:
1085       Opc = IsGPRC ? PPC::ADD4 : PPC::ADD8;
1086       break;
1087     case ISD::OR:
1088       Opc = IsGPRC ? PPC::OR : PPC::OR8;
1089       break;
1090     case ISD::SUB:
1091       Opc = IsGPRC ? PPC::SUBF : PPC::SUBF8;
1092       break;
1093   }
1094
1095   unsigned ResultReg = createResultReg(RC ? RC : &PPC::G8RCRegClass);
1096   unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1097   if (SrcReg1 == 0) return false;
1098
1099   // Handle case of small immediate operand.
1100   if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(1))) {
1101     const APInt &CIVal = ConstInt->getValue();
1102     int Imm = (int)CIVal.getSExtValue();
1103     bool UseImm = true;
1104     if (isInt<16>(Imm)) {
1105       switch (Opc) {
1106         default:
1107           llvm_unreachable("Missing case!");
1108         case PPC::ADD4:
1109           Opc = PPC::ADDI;
1110           MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1111           break;
1112         case PPC::ADD8:
1113           Opc = PPC::ADDI8;
1114           MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1115           break;
1116         case PPC::OR:
1117           Opc = PPC::ORI;
1118           break;
1119         case PPC::OR8:
1120           Opc = PPC::ORI8;
1121           break;
1122         case PPC::SUBF:
1123           if (Imm == -32768)
1124             UseImm = false;
1125           else {
1126             Opc = PPC::ADDI;
1127             MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1128             Imm = -Imm;
1129           }
1130           break;
1131         case PPC::SUBF8:
1132           if (Imm == -32768)
1133             UseImm = false;
1134           else {
1135             Opc = PPC::ADDI8;
1136             MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1137             Imm = -Imm;
1138           }
1139           break;
1140       }
1141
1142       if (UseImm) {
1143         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1144           .addReg(SrcReg1).addImm(Imm);
1145         UpdateValueMap(I, ResultReg);
1146         return true;
1147       }
1148     }
1149   }
1150
1151   // Reg-reg case.
1152   unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1153   if (SrcReg2 == 0) return false;
1154
1155   // Reverse operands for subtract-from.
1156   if (ISDOpcode == ISD::SUB)
1157     std::swap(SrcReg1, SrcReg2);
1158
1159   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1160     .addReg(SrcReg1).addReg(SrcReg2);
1161   UpdateValueMap(I, ResultReg);
1162   return true;
1163 }
1164
1165 // Handle arguments to a call that we're attempting to fast-select.
1166 // Return false if the arguments are too complex for us at the moment.
1167 bool PPCFastISel::processCallArgs(SmallVectorImpl<Value*> &Args,
1168                                   SmallVectorImpl<unsigned> &ArgRegs,
1169                                   SmallVectorImpl<MVT> &ArgVTs,
1170                                   SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1171                                   SmallVectorImpl<unsigned> &RegArgs,
1172                                   CallingConv::ID CC,
1173                                   unsigned &NumBytes,
1174                                   bool IsVarArg) {
1175   SmallVector<CCValAssign, 16> ArgLocs;
1176   CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, ArgLocs, *Context);
1177   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_PPC64_ELF_FIS);
1178
1179   // Bail out if we can't handle any of the arguments.
1180   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1181     CCValAssign &VA = ArgLocs[I];
1182     MVT ArgVT = ArgVTs[VA.getValNo()];
1183
1184     // Skip vector arguments for now, as well as long double and
1185     // uint128_t, and anything that isn't passed in a register.
1186     if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64 ||
1187         !VA.isRegLoc() || VA.needsCustom())
1188       return false;
1189
1190     // Skip bit-converted arguments for now.
1191     if (VA.getLocInfo() == CCValAssign::BCvt)
1192       return false;
1193   }
1194
1195   // Get a count of how many bytes are to be pushed onto the stack.
1196   NumBytes = CCInfo.getNextStackOffset();
1197
1198   // Issue CALLSEQ_START.
1199   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1200           TII.get(TII.getCallFrameSetupOpcode()))
1201     .addImm(NumBytes);
1202
1203   // Prepare to assign register arguments.  Every argument uses up a
1204   // GPR protocol register even if it's passed in a floating-point
1205   // register.
1206   unsigned NextGPR = PPC::X3;
1207   unsigned NextFPR = PPC::F1;
1208
1209   // Process arguments.
1210   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1211     CCValAssign &VA = ArgLocs[I];
1212     unsigned Arg = ArgRegs[VA.getValNo()];
1213     MVT ArgVT = ArgVTs[VA.getValNo()];
1214
1215     // Handle argument promotion and bitcasts.
1216     switch (VA.getLocInfo()) {
1217       default:
1218         llvm_unreachable("Unknown loc info!");
1219       case CCValAssign::Full:
1220         break;
1221       case CCValAssign::SExt: {
1222         MVT DestVT = VA.getLocVT();
1223         const TargetRegisterClass *RC =
1224           (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1225         unsigned TmpReg = createResultReg(RC);
1226         if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/false))
1227           llvm_unreachable("Failed to emit a sext!");
1228         ArgVT = DestVT;
1229         Arg = TmpReg;
1230         break;
1231       }
1232       case CCValAssign::AExt:
1233       case CCValAssign::ZExt: {
1234         MVT DestVT = VA.getLocVT();
1235         const TargetRegisterClass *RC =
1236           (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1237         unsigned TmpReg = createResultReg(RC);
1238         if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/true))
1239           llvm_unreachable("Failed to emit a zext!");
1240         ArgVT = DestVT;
1241         Arg = TmpReg;
1242         break;
1243       }
1244       case CCValAssign::BCvt: {
1245         // FIXME: Not yet handled.
1246         llvm_unreachable("Should have bailed before getting here!");
1247         break;
1248       }
1249     }
1250
1251     // Copy this argument to the appropriate register.
1252     unsigned ArgReg;
1253     if (ArgVT == MVT::f32 || ArgVT == MVT::f64) {
1254       ArgReg = NextFPR++;
1255       ++NextGPR;
1256     } else
1257       ArgReg = NextGPR++;
1258       
1259     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1260             ArgReg).addReg(Arg);
1261     RegArgs.push_back(ArgReg);
1262   }
1263
1264   return true;
1265 }
1266
1267 // For a call that we've determined we can fast-select, finish the
1268 // call sequence and generate a copy to obtain the return value (if any).
1269 void PPCFastISel::finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1270                              const Instruction *I, CallingConv::ID CC,
1271                              unsigned &NumBytes, bool IsVarArg) {
1272   // Issue CallSEQ_END.
1273   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1274           TII.get(TII.getCallFrameDestroyOpcode()))
1275     .addImm(NumBytes).addImm(0);
1276
1277   // Next, generate a copy to obtain the return value.
1278   // FIXME: No multi-register return values yet, though I don't foresee
1279   // any real difficulties there.
1280   if (RetVT != MVT::isVoid) {
1281     SmallVector<CCValAssign, 16> RVLocs;
1282     CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
1283     CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1284     CCValAssign &VA = RVLocs[0];
1285     assert(RVLocs.size() == 1 && "No support for multi-reg return values!");
1286     assert(VA.isRegLoc() && "Can only return in registers!");
1287
1288     MVT DestVT = VA.getValVT();
1289     MVT CopyVT = DestVT;
1290
1291     // Ints smaller than a register still arrive in a full 64-bit
1292     // register, so make sure we recognize this.
1293     if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32)
1294       CopyVT = MVT::i64;
1295
1296     unsigned SourcePhysReg = VA.getLocReg();
1297     unsigned ResultReg = 0;
1298
1299     if (RetVT == CopyVT) {
1300       const TargetRegisterClass *CpyRC = TLI.getRegClassFor(CopyVT);
1301       ResultReg = createResultReg(CpyRC);
1302
1303       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1304               TII.get(TargetOpcode::COPY), ResultReg)
1305         .addReg(SourcePhysReg);
1306
1307     // If necessary, round the floating result to single precision.
1308     } else if (CopyVT == MVT::f64) {
1309       ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1310       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::FRSP),
1311               ResultReg).addReg(SourcePhysReg);
1312
1313     // If only the low half of a general register is needed, generate
1314     // a GPRC copy instead of a G8RC copy.  (EXTRACT_SUBREG can't be
1315     // used along the fast-isel path (not lowered), and downstream logic
1316     // also doesn't like a direct subreg copy on a physical reg.)
1317     } else if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32) {
1318       ResultReg = createResultReg(&PPC::GPRCRegClass);
1319       // Convert physical register from G8RC to GPRC.
1320       SourcePhysReg -= PPC::X0 - PPC::R0;
1321       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1322               TII.get(TargetOpcode::COPY), ResultReg)
1323         .addReg(SourcePhysReg);
1324     }
1325
1326     assert(ResultReg && "ResultReg unset!");
1327     UsedRegs.push_back(SourcePhysReg);
1328     UpdateValueMap(I, ResultReg);
1329   }
1330 }
1331
1332 // Attempt to fast-select a call instruction.
1333 bool PPCFastISel::SelectCall(const Instruction *I) {
1334   const CallInst *CI = cast<CallInst>(I);
1335   const Value *Callee = CI->getCalledValue();
1336
1337   // Can't handle inline asm.
1338   if (isa<InlineAsm>(Callee))
1339     return false;
1340
1341   // Allow SelectionDAG isel to handle tail calls.
1342   if (CI->isTailCall())
1343     return false;
1344
1345   // Obtain calling convention.
1346   ImmutableCallSite CS(CI);
1347   CallingConv::ID CC = CS.getCallingConv();
1348
1349   PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1350   FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1351   bool IsVarArg = FTy->isVarArg();
1352
1353   // Not ready for varargs yet.
1354   if (IsVarArg)
1355     return false;
1356
1357   // Handle simple calls for now, with legal return types and
1358   // those that can be extended.
1359   Type *RetTy = I->getType();
1360   MVT RetVT;
1361   if (RetTy->isVoidTy())
1362     RetVT = MVT::isVoid;
1363   else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
1364            RetVT != MVT::i8)
1365     return false;
1366
1367   // FIXME: No multi-register return values yet.
1368   if (RetVT != MVT::isVoid && RetVT != MVT::i8 && RetVT != MVT::i16 &&
1369       RetVT != MVT::i32 && RetVT != MVT::i64 && RetVT != MVT::f32 &&
1370       RetVT != MVT::f64) {
1371     SmallVector<CCValAssign, 16> RVLocs;
1372     CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
1373     CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1374     if (RVLocs.size() > 1)
1375       return false;
1376   }
1377
1378   // Bail early if more than 8 arguments, as we only currently
1379   // handle arguments passed in registers.
1380   unsigned NumArgs = CS.arg_size();
1381   if (NumArgs > 8)
1382     return false;
1383
1384   // Set up the argument vectors.
1385   SmallVector<Value*, 8> Args;
1386   SmallVector<unsigned, 8> ArgRegs;
1387   SmallVector<MVT, 8> ArgVTs;
1388   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1389
1390   Args.reserve(NumArgs);
1391   ArgRegs.reserve(NumArgs);
1392   ArgVTs.reserve(NumArgs);
1393   ArgFlags.reserve(NumArgs);
1394
1395   for (ImmutableCallSite::arg_iterator II = CS.arg_begin(), IE = CS.arg_end();
1396        II != IE; ++II) {
1397     // FIXME: ARM does something for intrinsic calls here, check into that.
1398
1399     unsigned AttrIdx = II - CS.arg_begin() + 1;
1400     
1401     // Only handle easy calls for now.  It would be reasonably easy
1402     // to handle <= 8-byte structures passed ByVal in registers, but we
1403     // have to ensure they are right-justified in the register.
1404     if (CS.paramHasAttr(AttrIdx, Attribute::InReg) ||
1405         CS.paramHasAttr(AttrIdx, Attribute::StructRet) ||
1406         CS.paramHasAttr(AttrIdx, Attribute::Nest) ||
1407         CS.paramHasAttr(AttrIdx, Attribute::ByVal))
1408       return false;
1409
1410     ISD::ArgFlagsTy Flags;
1411     if (CS.paramHasAttr(AttrIdx, Attribute::SExt))
1412       Flags.setSExt();
1413     if (CS.paramHasAttr(AttrIdx, Attribute::ZExt))
1414       Flags.setZExt();
1415
1416     Type *ArgTy = (*II)->getType();
1417     MVT ArgVT;
1418     if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8)
1419       return false;
1420
1421     if (ArgVT.isVector())
1422       return false;
1423
1424     unsigned Arg = getRegForValue(*II);
1425     if (Arg == 0)
1426       return false;
1427
1428     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1429     Flags.setOrigAlign(OriginalAlignment);
1430
1431     Args.push_back(*II);
1432     ArgRegs.push_back(Arg);
1433     ArgVTs.push_back(ArgVT);
1434     ArgFlags.push_back(Flags);
1435   }
1436
1437   // Process the arguments.
1438   SmallVector<unsigned, 8> RegArgs;
1439   unsigned NumBytes;
1440
1441   if (!processCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
1442                        RegArgs, CC, NumBytes, IsVarArg))
1443     return false;
1444
1445   // FIXME: No handling for function pointers yet.  This requires
1446   // implementing the function descriptor (OPD) setup.
1447   const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1448   if (!GV)
1449     return false;
1450
1451   // Build direct call with NOP for TOC restore.
1452   // FIXME: We can and should optimize away the NOP for local calls.
1453   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1454                                     TII.get(PPC::BL8_NOP));
1455   // Add callee.
1456   MIB.addGlobalAddress(GV);
1457
1458   // Add implicit physical register uses to the call.
1459   for (unsigned II = 0, IE = RegArgs.size(); II != IE; ++II)
1460     MIB.addReg(RegArgs[II], RegState::Implicit);
1461
1462   // Add a register mask with the call-preserved registers.  Proper
1463   // defs for return values will be added by setPhysRegsDeadExcept().
1464   MIB.addRegMask(TRI.getCallPreservedMask(CC));
1465
1466   // Finish off the call including any return values.
1467   SmallVector<unsigned, 4> UsedRegs;
1468   finishCall(RetVT, UsedRegs, I, CC, NumBytes, IsVarArg);
1469
1470   // Set all unused physregs defs as dead.
1471   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1472
1473   return true;
1474 }
1475
1476 // Attempt to fast-select a return instruction.
1477 bool PPCFastISel::SelectRet(const Instruction *I) {
1478
1479   if (!FuncInfo.CanLowerReturn)
1480     return false;
1481
1482   const ReturnInst *Ret = cast<ReturnInst>(I);
1483   const Function &F = *I->getParent()->getParent();
1484
1485   // Build a list of return value registers.
1486   SmallVector<unsigned, 4> RetRegs;
1487   CallingConv::ID CC = F.getCallingConv();
1488
1489   if (Ret->getNumOperands() > 0) {
1490     SmallVector<ISD::OutputArg, 4> Outs;
1491     GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1492
1493     // Analyze operands of the call, assigning locations to each operand.
1494     SmallVector<CCValAssign, 16> ValLocs;
1495     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs, *Context);
1496     CCInfo.AnalyzeReturn(Outs, RetCC_PPC64_ELF_FIS);
1497     const Value *RV = Ret->getOperand(0);
1498     
1499     // FIXME: Only one output register for now.
1500     if (ValLocs.size() > 1)
1501       return false;
1502
1503     // Special case for returning a constant integer of any size.
1504     // Materialize the constant as an i64 and copy it to the return
1505     // register.  This avoids an unnecessary extend or truncate.
1506     if (isa<ConstantInt>(*RV)) {
1507       const Constant *C = cast<Constant>(RV);
1508       unsigned SrcReg = PPCMaterializeInt(C, MVT::i64);
1509       unsigned RetReg = ValLocs[0].getLocReg();
1510       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1511               RetReg).addReg(SrcReg);
1512       RetRegs.push_back(RetReg);
1513
1514     } else {
1515       unsigned Reg = getRegForValue(RV);
1516
1517       if (Reg == 0)
1518         return false;
1519
1520       // Copy the result values into the output registers.
1521       for (unsigned i = 0; i < ValLocs.size(); ++i) {
1522
1523         CCValAssign &VA = ValLocs[i];
1524         assert(VA.isRegLoc() && "Can only return in registers!");
1525         RetRegs.push_back(VA.getLocReg());
1526         unsigned SrcReg = Reg + VA.getValNo();
1527
1528         EVT RVEVT = TLI.getValueType(RV->getType());
1529         if (!RVEVT.isSimple())
1530           return false;
1531         MVT RVVT = RVEVT.getSimpleVT();
1532         MVT DestVT = VA.getLocVT();
1533
1534         if (RVVT != DestVT && RVVT != MVT::i8 &&
1535             RVVT != MVT::i16 && RVVT != MVT::i32)
1536           return false;
1537       
1538         if (RVVT != DestVT) {
1539           switch (VA.getLocInfo()) {
1540             default:
1541               llvm_unreachable("Unknown loc info!");
1542             case CCValAssign::Full:
1543               llvm_unreachable("Full value assign but types don't match?");
1544             case CCValAssign::AExt:
1545             case CCValAssign::ZExt: {
1546               const TargetRegisterClass *RC =
1547                 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1548               unsigned TmpReg = createResultReg(RC);
1549               if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, true))
1550                 return false;
1551               SrcReg = TmpReg;
1552               break;
1553             }
1554             case CCValAssign::SExt: {
1555               const TargetRegisterClass *RC =
1556                 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1557               unsigned TmpReg = createResultReg(RC);
1558               if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, false))
1559                 return false;
1560               SrcReg = TmpReg;
1561               break;
1562             }
1563           }
1564         }
1565
1566         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1567                 TII.get(TargetOpcode::COPY), RetRegs[i])
1568           .addReg(SrcReg);
1569       }
1570     }
1571   }
1572
1573   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1574                                     TII.get(PPC::BLR));
1575
1576   for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1577     MIB.addReg(RetRegs[i], RegState::Implicit);
1578
1579   return true;
1580 }
1581
1582 // Attempt to emit an integer extend of SrcReg into DestReg.  Both
1583 // signed and zero extensions are supported.  Return false if we
1584 // can't handle it.
1585 bool PPCFastISel::PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1586                                 unsigned DestReg, bool IsZExt) {
1587   if (DestVT != MVT::i32 && DestVT != MVT::i64)
1588     return false;
1589   if (SrcVT != MVT::i8 && SrcVT != MVT::i16 && SrcVT != MVT::i32)
1590     return false;
1591
1592   // Signed extensions use EXTSB, EXTSH, EXTSW.
1593   if (!IsZExt) {
1594     unsigned Opc;
1595     if (SrcVT == MVT::i8)
1596       Opc = (DestVT == MVT::i32) ? PPC::EXTSB : PPC::EXTSB8_32_64;
1597     else if (SrcVT == MVT::i16)
1598       Opc = (DestVT == MVT::i32) ? PPC::EXTSH : PPC::EXTSH8_32_64;
1599     else {
1600       assert(DestVT == MVT::i64 && "Signed extend from i32 to i32??");
1601       Opc = PPC::EXTSW_32_64;
1602     }
1603     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1604       .addReg(SrcReg);
1605
1606   // Unsigned 32-bit extensions use RLWINM.
1607   } else if (DestVT == MVT::i32) {
1608     unsigned MB;
1609     if (SrcVT == MVT::i8)
1610       MB = 24;
1611     else {
1612       assert(SrcVT == MVT::i16 && "Unsigned extend from i32 to i32??");
1613       MB = 16;
1614     }
1615     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::RLWINM),
1616             DestReg)
1617       .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB).addImm(/*ME=*/31);
1618
1619   // Unsigned 64-bit extensions use RLDICL (with a 32-bit source).
1620   } else {
1621     unsigned MB;
1622     if (SrcVT == MVT::i8)
1623       MB = 56;
1624     else if (SrcVT == MVT::i16)
1625       MB = 48;
1626     else
1627       MB = 32;
1628     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1629             TII.get(PPC::RLDICL_32_64), DestReg)
1630       .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB);
1631   }
1632
1633   return true;
1634 }
1635
1636 // Attempt to fast-select an indirect branch instruction.
1637 bool PPCFastISel::SelectIndirectBr(const Instruction *I) {
1638   unsigned AddrReg = getRegForValue(I->getOperand(0));
1639   if (AddrReg == 0)
1640     return false;
1641
1642   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::MTCTR8))
1643     .addReg(AddrReg);
1644   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::BCTR8));
1645
1646   const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1647   for (unsigned i = 0, e = IB->getNumSuccessors(); i != e; ++i)
1648     FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[IB->getSuccessor(i)]);
1649
1650   return true;
1651 }
1652
1653 // Attempt to fast-select a compare instruction.
1654 bool PPCFastISel::SelectCmp(const Instruction *I) {
1655   const CmpInst *CI = cast<CmpInst>(I);
1656   Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
1657   if (!OptPPCPred)
1658     return false;
1659
1660   unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
1661
1662   if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
1663                   CondReg))
1664     return false;
1665
1666   UpdateValueMap(I, CondReg);
1667   return true;
1668 }
1669
1670 // Attempt to fast-select an integer extend instruction.
1671 bool PPCFastISel::SelectIntExt(const Instruction *I) {
1672   Type *DestTy = I->getType();
1673   Value *Src = I->getOperand(0);
1674   Type *SrcTy = Src->getType();
1675
1676   bool IsZExt = isa<ZExtInst>(I);
1677   unsigned SrcReg = getRegForValue(Src);
1678   if (!SrcReg) return false;
1679
1680   EVT SrcEVT, DestEVT;
1681   SrcEVT = TLI.getValueType(SrcTy, true);
1682   DestEVT = TLI.getValueType(DestTy, true);
1683   if (!SrcEVT.isSimple())
1684     return false;
1685   if (!DestEVT.isSimple())
1686     return false;
1687
1688   MVT SrcVT = SrcEVT.getSimpleVT();
1689   MVT DestVT = DestEVT.getSimpleVT();
1690
1691   // If we know the register class needed for the result of this
1692   // instruction, use it.  Otherwise pick the register class of the
1693   // correct size that does not contain X0/R0, since we don't know
1694   // whether downstream uses permit that assignment.
1695   unsigned AssignedReg = FuncInfo.ValueMap[I];
1696   const TargetRegisterClass *RC =
1697     (AssignedReg ? MRI.getRegClass(AssignedReg) :
1698      (DestVT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
1699       &PPC::GPRC_and_GPRC_NOR0RegClass));
1700   unsigned ResultReg = createResultReg(RC);
1701
1702   if (!PPCEmitIntExt(SrcVT, SrcReg, DestVT, ResultReg, IsZExt))
1703     return false;
1704
1705   UpdateValueMap(I, ResultReg);
1706   return true;
1707 }
1708
1709 // Attempt to fast-select an instruction that wasn't handled by
1710 // the table-generated machinery.
1711 bool PPCFastISel::TargetSelectInstruction(const Instruction *I) {
1712
1713   switch (I->getOpcode()) {
1714     case Instruction::Load:
1715       return SelectLoad(I);
1716     case Instruction::Store:
1717       return SelectStore(I);
1718     case Instruction::Br:
1719       return SelectBranch(I);
1720     case Instruction::IndirectBr:
1721       return SelectIndirectBr(I);
1722     case Instruction::FPExt:
1723       return SelectFPExt(I);
1724     case Instruction::FPTrunc:
1725       return SelectFPTrunc(I);
1726     case Instruction::SIToFP:
1727       return SelectIToFP(I, /*IsSigned*/ true);
1728     case Instruction::UIToFP:
1729       return SelectIToFP(I, /*IsSigned*/ false);
1730     case Instruction::FPToSI:
1731       return SelectFPToI(I, /*IsSigned*/ true);
1732     case Instruction::FPToUI:
1733       return SelectFPToI(I, /*IsSigned*/ false);
1734     case Instruction::Add:
1735       return SelectBinaryIntOp(I, ISD::ADD);
1736     case Instruction::Or:
1737       return SelectBinaryIntOp(I, ISD::OR);
1738     case Instruction::Sub:
1739       return SelectBinaryIntOp(I, ISD::SUB);
1740     case Instruction::Call:
1741       if (dyn_cast<IntrinsicInst>(I))
1742         return false;
1743       return SelectCall(I);
1744     case Instruction::Ret:
1745       return SelectRet(I);
1746     case Instruction::ZExt:
1747     case Instruction::SExt:
1748       return SelectIntExt(I);
1749     // Here add other flavors of Instruction::XXX that automated
1750     // cases don't catch.  For example, switches are terminators
1751     // that aren't yet handled.
1752     default:
1753       break;
1754   }
1755   return false;
1756 }
1757
1758 // Materialize a floating-point constant into a register, and return
1759 // the register number (or zero if we failed to handle it).
1760 unsigned PPCFastISel::PPCMaterializeFP(const ConstantFP *CFP, MVT VT) {
1761   // No plans to handle long double here.
1762   if (VT != MVT::f32 && VT != MVT::f64)
1763     return 0;
1764
1765   // All FP constants are loaded from the constant pool.
1766   unsigned Align = TD.getPrefTypeAlignment(CFP->getType());
1767   assert(Align > 0 && "Unexpectedly missing alignment information!");
1768   unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
1769   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
1770   CodeModel::Model CModel = TM.getCodeModel();
1771
1772   MachineMemOperand *MMO =
1773     FuncInfo.MF->getMachineMemOperand(
1774       MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
1775       (VT == MVT::f32) ? 4 : 8, Align);
1776
1777   unsigned Opc = (VT == MVT::f32) ? PPC::LFS : PPC::LFD;
1778   unsigned TmpReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1779
1780   // For small code model, generate a LF[SD](0, LDtocCPT(Idx, X2)).
1781   if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault) {
1782     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocCPT),
1783             TmpReg)
1784       .addConstantPoolIndex(Idx).addReg(PPC::X2);
1785     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1786       .addImm(0).addReg(TmpReg).addMemOperand(MMO);
1787   } else {
1788     // Otherwise we generate LF[SD](Idx[lo], ADDIStocHA(X2, Idx)).
1789     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDIStocHA),
1790             TmpReg).addReg(PPC::X2).addConstantPoolIndex(Idx);
1791     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1792       .addConstantPoolIndex(Idx, 0, PPCII::MO_TOC_LO)
1793       .addReg(TmpReg)
1794       .addMemOperand(MMO);
1795   }
1796
1797   return DestReg;
1798 }
1799
1800 // Materialize the address of a global value into a register, and return
1801 // the register number (or zero if we failed to handle it).
1802 unsigned PPCFastISel::PPCMaterializeGV(const GlobalValue *GV, MVT VT) {
1803   assert(VT == MVT::i64 && "Non-address!");
1804   const TargetRegisterClass *RC = &PPC::G8RC_and_G8RC_NOX0RegClass;
1805   unsigned DestReg = createResultReg(RC);
1806
1807   // Global values may be plain old object addresses, TLS object
1808   // addresses, constant pool entries, or jump tables.  How we generate
1809   // code for these may depend on small, medium, or large code model.
1810   CodeModel::Model CModel = TM.getCodeModel();
1811
1812   // FIXME: Jump tables are not yet required because fast-isel doesn't
1813   // handle switches; if that changes, we need them as well.  For now,
1814   // what follows assumes everything's a generic (or TLS) global address.
1815   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1816   if (!GVar) {
1817     // If GV is an alias, use the aliasee for determining thread-locality.
1818     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1819       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
1820   }
1821
1822   // FIXME: We don't yet handle the complexity of TLS.
1823   bool IsTLS = GVar && GVar->isThreadLocal();
1824   if (IsTLS)
1825     return 0;
1826
1827   // For small code model, generate a simple TOC load.
1828   if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault)
1829     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtoc), DestReg)
1830       .addGlobalAddress(GV).addReg(PPC::X2);
1831   else {
1832     // If the address is an externally defined symbol, a symbol with
1833     // common or externally available linkage, a function address, or a
1834     // jump table address (not yet needed), or if we are generating code
1835     // for large code model, we generate:
1836     //       LDtocL(GV, ADDIStocHA(%X2, GV))
1837     // Otherwise we generate:
1838     //       ADDItocL(ADDIStocHA(%X2, GV), GV)
1839     // Either way, start with the ADDIStocHA:
1840     unsigned HighPartReg = createResultReg(RC);
1841     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDIStocHA),
1842             HighPartReg).addReg(PPC::X2).addGlobalAddress(GV);
1843
1844     // !GVar implies a function address.  An external variable is one
1845     // without an initializer.
1846     // If/when switches are implemented, jump tables should be handled
1847     // on the "if" path here.
1848     if (CModel == CodeModel::Large || !GVar || !GVar->hasInitializer() ||
1849         GVar->hasCommonLinkage() || GVar->hasAvailableExternallyLinkage())
1850       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocL),
1851               DestReg).addGlobalAddress(GV).addReg(HighPartReg);
1852     else
1853       // Otherwise generate the ADDItocL.
1854       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDItocL),
1855               DestReg).addReg(HighPartReg).addGlobalAddress(GV);
1856   }
1857
1858   return DestReg;
1859 }
1860
1861 // Materialize a 32-bit integer constant into a register, and return
1862 // the register number (or zero if we failed to handle it).
1863 unsigned PPCFastISel::PPCMaterialize32BitInt(int64_t Imm,
1864                                              const TargetRegisterClass *RC) {
1865   unsigned Lo = Imm & 0xFFFF;
1866   unsigned Hi = (Imm >> 16) & 0xFFFF;
1867
1868   unsigned ResultReg = createResultReg(RC);
1869   bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1870
1871   if (isInt<16>(Imm))
1872     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1873             TII.get(IsGPRC ? PPC::LI : PPC::LI8), ResultReg)
1874       .addImm(Imm);
1875   else if (Lo) {
1876     // Both Lo and Hi have nonzero bits.
1877     unsigned TmpReg = createResultReg(RC);
1878     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1879             TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), TmpReg)
1880       .addImm(Hi);
1881     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1882             TII.get(IsGPRC ? PPC::ORI : PPC::ORI8), ResultReg)
1883       .addReg(TmpReg).addImm(Lo);
1884   } else
1885     // Just Hi bits.
1886     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1887             TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), ResultReg)
1888       .addImm(Hi);
1889   
1890   return ResultReg;
1891 }
1892
1893 // Materialize a 64-bit integer constant into a register, and return
1894 // the register number (or zero if we failed to handle it).
1895 unsigned PPCFastISel::PPCMaterialize64BitInt(int64_t Imm,
1896                                              const TargetRegisterClass *RC) {
1897   unsigned Remainder = 0;
1898   unsigned Shift = 0;
1899
1900   // If the value doesn't fit in 32 bits, see if we can shift it
1901   // so that it fits in 32 bits.
1902   if (!isInt<32>(Imm)) {
1903     Shift = countTrailingZeros<uint64_t>(Imm);
1904     int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
1905
1906     if (isInt<32>(ImmSh))
1907       Imm = ImmSh;
1908     else {
1909       Remainder = Imm;
1910       Shift = 32;
1911       Imm >>= 32;
1912     }
1913   }
1914
1915   // Handle the high-order 32 bits (if shifted) or the whole 32 bits
1916   // (if not shifted).
1917   unsigned TmpReg1 = PPCMaterialize32BitInt(Imm, RC);
1918   if (!Shift)
1919     return TmpReg1;
1920
1921   // If upper 32 bits were not zero, we've built them and need to shift
1922   // them into place.
1923   unsigned TmpReg2;
1924   if (Imm) {
1925     TmpReg2 = createResultReg(RC);
1926     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::RLDICR),
1927             TmpReg2).addReg(TmpReg1).addImm(Shift).addImm(63 - Shift);
1928   } else
1929     TmpReg2 = TmpReg1;
1930
1931   unsigned TmpReg3, Hi, Lo;
1932   if ((Hi = (Remainder >> 16) & 0xFFFF)) {
1933     TmpReg3 = createResultReg(RC);
1934     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ORIS8),
1935             TmpReg3).addReg(TmpReg2).addImm(Hi);
1936   } else
1937     TmpReg3 = TmpReg2;
1938
1939   if ((Lo = Remainder & 0xFFFF)) {
1940     unsigned ResultReg = createResultReg(RC);
1941     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ORI8),
1942             ResultReg).addReg(TmpReg3).addImm(Lo);
1943     return ResultReg;
1944   }
1945
1946   return TmpReg3;
1947 }
1948
1949
1950 // Materialize an integer constant into a register, and return
1951 // the register number (or zero if we failed to handle it).
1952 unsigned PPCFastISel::PPCMaterializeInt(const Constant *C, MVT VT) {
1953
1954   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
1955       VT != MVT::i8 && VT != MVT::i1) 
1956     return 0;
1957
1958   const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
1959                                    &PPC::GPRCRegClass);
1960
1961   // If the constant is in range, use a load-immediate.
1962   const ConstantInt *CI = cast<ConstantInt>(C);
1963   if (isInt<16>(CI->getSExtValue())) {
1964     unsigned Opc = (VT == MVT::i64) ? PPC::LI8 : PPC::LI;
1965     unsigned ImmReg = createResultReg(RC);
1966     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ImmReg)
1967       .addImm(CI->getSExtValue());
1968     return ImmReg;
1969   }
1970
1971   // Construct the constant piecewise.
1972   int64_t Imm = CI->getZExtValue();
1973
1974   if (VT == MVT::i64)
1975     return PPCMaterialize64BitInt(Imm, RC);
1976   else if (VT == MVT::i32)
1977     return PPCMaterialize32BitInt(Imm, RC);
1978
1979   return 0;
1980 }
1981
1982 // Materialize a constant into a register, and return the register
1983 // number (or zero if we failed to handle it).
1984 unsigned PPCFastISel::TargetMaterializeConstant(const Constant *C) {
1985   EVT CEVT = TLI.getValueType(C->getType(), true);
1986
1987   // Only handle simple types.
1988   if (!CEVT.isSimple()) return 0;
1989   MVT VT = CEVT.getSimpleVT();
1990
1991   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1992     return PPCMaterializeFP(CFP, VT);
1993   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1994     return PPCMaterializeGV(GV, VT);
1995   else if (isa<ConstantInt>(C))
1996     return PPCMaterializeInt(C, VT);
1997   // TBD: Global values.
1998
1999   return 0;
2000 }
2001
2002 // Materialize the address created by an alloca into a register, and
2003 // return the register number (or zero if we failed to handle it).  TBD.
2004 unsigned PPCFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
2005   return AI && 0;
2006 }
2007
2008 // Fold loads into extends when possible.
2009 // FIXME: We can have multiple redundant extend/trunc instructions
2010 // following a load.  The folding only picks up one.  Extend this
2011 // to check subsequent instructions for the same pattern and remove
2012 // them.  Thus ResultReg should be the def reg for the last redundant
2013 // instruction in a chain, and all intervening instructions can be
2014 // removed from parent.  Change test/CodeGen/PowerPC/fast-isel-fold.ll
2015 // to add ELF64-NOT: rldicl to the appropriate tests when this works.
2016 bool PPCFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2017                                       const LoadInst *LI) {
2018   // Verify we have a legal type before going any further.
2019   MVT VT;
2020   if (!isLoadTypeLegal(LI->getType(), VT))
2021     return false;
2022
2023   // Combine load followed by zero- or sign-extend.
2024   bool IsZExt = false;
2025   switch(MI->getOpcode()) {
2026     default:
2027       return false;
2028
2029     case PPC::RLDICL:
2030     case PPC::RLDICL_32_64: {
2031       IsZExt = true;
2032       unsigned MB = MI->getOperand(3).getImm();
2033       if ((VT == MVT::i8 && MB <= 56) ||
2034           (VT == MVT::i16 && MB <= 48) ||
2035           (VT == MVT::i32 && MB <= 32))
2036         break;
2037       return false;
2038     }
2039
2040     case PPC::RLWINM:
2041     case PPC::RLWINM8: {
2042       IsZExt = true;
2043       unsigned MB = MI->getOperand(3).getImm();
2044       if ((VT == MVT::i8 && MB <= 24) ||
2045           (VT == MVT::i16 && MB <= 16))
2046         break;
2047       return false;
2048     }
2049
2050     case PPC::EXTSB:
2051     case PPC::EXTSB8:
2052     case PPC::EXTSB8_32_64:
2053       /* There is no sign-extending load-byte instruction. */
2054       return false;
2055
2056     case PPC::EXTSH:
2057     case PPC::EXTSH8:
2058     case PPC::EXTSH8_32_64: {
2059       if (VT != MVT::i16 && VT != MVT::i8)
2060         return false;
2061       break;
2062     }
2063
2064     case PPC::EXTSW:
2065     case PPC::EXTSW_32_64: {
2066       if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8)
2067         return false;
2068       break;
2069     }
2070   }
2071
2072   // See if we can handle this address.
2073   Address Addr;
2074   if (!PPCComputeAddress(LI->getOperand(0), Addr))
2075     return false;
2076
2077   unsigned ResultReg = MI->getOperand(0).getReg();
2078
2079   if (!PPCEmitLoad(VT, ResultReg, Addr, 0, IsZExt))
2080     return false;
2081
2082   MI->eraseFromParent();
2083   return true;
2084 }
2085
2086 // Attempt to lower call arguments in a faster way than done by
2087 // the selection DAG code.
2088 bool PPCFastISel::FastLowerArguments() {
2089   // Defer to normal argument lowering for now.  It's reasonably
2090   // efficient.  Consider doing something like ARM to handle the
2091   // case where all args fit in registers, no varargs, no float
2092   // or vector args.
2093   return false;
2094 }
2095
2096 // Handle materializing integer constants into a register.  This is not
2097 // automatically generated for PowerPC, so must be explicitly created here.
2098 unsigned PPCFastISel::FastEmit_i(MVT Ty, MVT VT, unsigned Opc, uint64_t Imm) {
2099   
2100   if (Opc != ISD::Constant)
2101     return 0;
2102
2103   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2104       VT != MVT::i8 && VT != MVT::i1) 
2105     return 0;
2106
2107   const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2108                                    &PPC::GPRCRegClass);
2109   if (VT == MVT::i64)
2110     return PPCMaterialize64BitInt(Imm, RC);
2111   else
2112     return PPCMaterialize32BitInt(Imm, RC);
2113 }
2114
2115 // Override for ADDI and ADDI8 to set the correct register class
2116 // on RHS operand 0.  The automatic infrastructure naively assumes
2117 // GPRC for i32 and G8RC for i64; the concept of "no R0" is lost
2118 // for these cases.  At the moment, none of the other automatically
2119 // generated RI instructions require special treatment.  However, once
2120 // SelectSelect is implemented, "isel" requires similar handling.
2121 //
2122 // Also be conservative about the output register class.  Avoid
2123 // assigning R0 or X0 to the output register for GPRC and G8RC
2124 // register classes, as any such result could be used in ADDI, etc.,
2125 // where those regs have another meaning.
2126 unsigned PPCFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
2127                                       const TargetRegisterClass *RC,
2128                                       unsigned Op0, bool Op0IsKill,
2129                                       uint64_t Imm) {
2130   if (MachineInstOpcode == PPC::ADDI)
2131     MRI.setRegClass(Op0, &PPC::GPRC_and_GPRC_NOR0RegClass);
2132   else if (MachineInstOpcode == PPC::ADDI8)
2133     MRI.setRegClass(Op0, &PPC::G8RC_and_G8RC_NOX0RegClass);
2134
2135   const TargetRegisterClass *UseRC =
2136     (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2137      (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2138
2139   return FastISel::FastEmitInst_ri(MachineInstOpcode, UseRC,
2140                                    Op0, Op0IsKill, Imm);
2141 }
2142
2143 // Override for instructions with one register operand to avoid use of
2144 // R0/X0.  The automatic infrastructure isn't aware of the context so
2145 // we must be conservative.
2146 unsigned PPCFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
2147                                      const TargetRegisterClass* RC,
2148                                      unsigned Op0, bool Op0IsKill) {
2149   const TargetRegisterClass *UseRC =
2150     (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2151      (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2152
2153   return FastISel::FastEmitInst_r(MachineInstOpcode, UseRC, Op0, Op0IsKill);
2154 }
2155
2156 // Override for instructions with two register operands to avoid use
2157 // of R0/X0.  The automatic infrastructure isn't aware of the context
2158 // so we must be conservative.
2159 unsigned PPCFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
2160                                       const TargetRegisterClass* RC,
2161                                       unsigned Op0, bool Op0IsKill,
2162                                       unsigned Op1, bool Op1IsKill) {
2163   const TargetRegisterClass *UseRC =
2164     (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2165      (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2166
2167   return FastISel::FastEmitInst_rr(MachineInstOpcode, UseRC, Op0, Op0IsKill,
2168                                    Op1, Op1IsKill);
2169 }
2170
2171 namespace llvm {
2172   // Create the fast instruction selector for PowerPC64 ELF.
2173   FastISel *PPC::createFastISel(FunctionLoweringInfo &FuncInfo,
2174                                 const TargetLibraryInfo *LibInfo) {
2175     const TargetMachine &TM = FuncInfo.MF->getTarget();
2176
2177     // Only available on 64-bit ELF for now.
2178     const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
2179     if (Subtarget->isPPC64() && Subtarget->isSVR4ABI())
2180       return new PPCFastISel(FuncInfo, LibInfo);
2181
2182     return 0;
2183   }
2184 }