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