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