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