1 //===-- PPCFastISel.cpp - PowerPC FastISel implementation -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "ppcfastisel"
18 #include "PPCISelLowering.h"
19 #include "PPCSubtarget.h"
20 #include "PPCTargetMachine.h"
21 #include "MCTargetDesc/PPCPredicates.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/FastISel.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetMachine.h"
40 //===----------------------------------------------------------------------===//
43 // FastLowerArguments: Handle simple cases.
44 // PPCMaterializeGV: Handle TLS.
45 // SelectCall: Handle function pointers.
46 // SelectCall: Handle multi-register return values.
47 // SelectCall: Optimize away nops for local calls.
48 // processCallArgs: Handle bit-converted arguments.
49 // finishCall: Handle multi-register return values.
50 // PPCComputeAddress: Handle parameter references as FrameIndex's.
51 // PPCEmitCmp: Handle immediate as operand 1.
52 // SelectCall: Handle small byval arguments.
53 // SelectIntrinsicCall: Implement.
54 // SelectSelect: Implement.
55 // Consider factoring isTypeLegal into the base class.
56 // Implement switches and jump tables.
58 //===----------------------------------------------------------------------===//
63 typedef struct Address {
76 // Innocuous defaults for our address.
78 : BaseType(RegBase), Offset(0) {
83 class PPCFastISel : public FastISel {
85 const TargetMachine &TM;
86 const TargetInstrInfo &TII;
87 const TargetLowering &TLI;
88 const PPCSubtarget &PPCSubTarget;
92 explicit PPCFastISel(FunctionLoweringInfo &FuncInfo,
93 const TargetLibraryInfo *LibInfo)
94 : FastISel(FuncInfo, LibInfo),
95 TM(FuncInfo.MF->getTarget()),
96 TII(*TM.getInstrInfo()),
97 TLI(*TM.getTargetLowering()),
99 *((static_cast<const PPCTargetMachine *>(&TM))->getSubtargetImpl())
101 Context(&FuncInfo.Fn->getContext()) { }
103 // Backend specific FastISel code.
105 virtual bool TargetSelectInstruction(const Instruction *I);
106 virtual unsigned TargetMaterializeConstant(const Constant *C);
107 virtual unsigned TargetMaterializeAlloca(const AllocaInst *AI);
108 virtual bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
110 virtual bool FastLowerArguments();
111 virtual unsigned FastEmit_i(MVT Ty, MVT RetTy, unsigned Opc, uint64_t Imm);
112 virtual unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
113 const TargetRegisterClass *RC,
114 unsigned Op0, bool Op0IsKill,
116 virtual unsigned FastEmitInst_r(unsigned MachineInstOpcode,
117 const TargetRegisterClass *RC,
118 unsigned Op0, bool Op0IsKill);
119 virtual unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
120 const TargetRegisterClass *RC,
121 unsigned Op0, bool Op0IsKill,
122 unsigned Op1, bool Op1IsKill);
124 // Instruction selection routines.
126 bool SelectLoad(const Instruction *I);
127 bool SelectStore(const Instruction *I);
128 bool SelectBranch(const Instruction *I);
129 bool SelectIndirectBr(const Instruction *I);
130 bool SelectCmp(const Instruction *I);
131 bool SelectFPExt(const Instruction *I);
132 bool SelectFPTrunc(const Instruction *I);
133 bool SelectIToFP(const Instruction *I, bool IsSigned);
134 bool SelectFPToI(const Instruction *I, bool IsSigned);
135 bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
136 bool SelectCall(const Instruction *I);
137 bool SelectRet(const Instruction *I);
138 bool SelectTrunc(const Instruction *I);
139 bool SelectIntExt(const Instruction *I);
143 bool isTypeLegal(Type *Ty, MVT &VT);
144 bool isLoadTypeLegal(Type *Ty, MVT &VT);
145 bool PPCEmitCmp(const Value *Src1Value, const Value *Src2Value,
146 bool isZExt, unsigned DestReg);
147 bool PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
148 const TargetRegisterClass *RC, bool IsZExt = true,
149 unsigned FP64LoadOpc = PPC::LFD);
150 bool PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr);
151 bool PPCComputeAddress(const Value *Obj, Address &Addr);
152 void PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
154 bool PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
155 unsigned DestReg, bool IsZExt);
156 unsigned PPCMaterializeFP(const ConstantFP *CFP, MVT VT);
157 unsigned PPCMaterializeGV(const GlobalValue *GV, MVT VT);
158 unsigned PPCMaterializeInt(const Constant *C, MVT VT);
159 unsigned PPCMaterialize32BitInt(int64_t Imm,
160 const TargetRegisterClass *RC);
161 unsigned PPCMaterialize64BitInt(int64_t Imm,
162 const TargetRegisterClass *RC);
163 unsigned PPCMoveToIntReg(const Instruction *I, MVT VT,
164 unsigned SrcReg, bool IsSigned);
165 unsigned PPCMoveToFPReg(MVT VT, unsigned SrcReg, bool IsSigned);
167 // Call handling routines.
169 bool processCallArgs(SmallVectorImpl<Value*> &Args,
170 SmallVectorImpl<unsigned> &ArgRegs,
171 SmallVectorImpl<MVT> &ArgVTs,
172 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
173 SmallVectorImpl<unsigned> &RegArgs,
177 void finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
178 const Instruction *I, CallingConv::ID CC,
179 unsigned &NumBytes, bool IsVarArg);
180 CCAssignFn *usePPC32CCs(unsigned Flag);
183 #include "PPCGenFastISel.inc"
187 } // end anonymous namespace
189 #include "PPCGenCallingConv.inc"
191 // Function whose sole purpose is to kill compiler warnings
192 // stemming from unused functions included from PPCGenCallingConv.inc.
193 CCAssignFn *PPCFastISel::usePPC32CCs(unsigned Flag) {
195 return CC_PPC32_SVR4;
197 return CC_PPC32_SVR4_ByVal;
199 return CC_PPC32_SVR4_VarArg;
204 static Optional<PPC::Predicate> getComparePred(CmpInst::Predicate Pred) {
206 // These are not representable with any single compare.
207 case CmpInst::FCMP_FALSE:
208 case CmpInst::FCMP_UEQ:
209 case CmpInst::FCMP_UGT:
210 case CmpInst::FCMP_UGE:
211 case CmpInst::FCMP_ULT:
212 case CmpInst::FCMP_ULE:
213 case CmpInst::FCMP_UNE:
214 case CmpInst::FCMP_TRUE:
216 return Optional<PPC::Predicate>();
218 case CmpInst::FCMP_OEQ:
219 case CmpInst::ICMP_EQ:
222 case CmpInst::FCMP_OGT:
223 case CmpInst::ICMP_UGT:
224 case CmpInst::ICMP_SGT:
227 case CmpInst::FCMP_OGE:
228 case CmpInst::ICMP_UGE:
229 case CmpInst::ICMP_SGE:
232 case CmpInst::FCMP_OLT:
233 case CmpInst::ICMP_ULT:
234 case CmpInst::ICMP_SLT:
237 case CmpInst::FCMP_OLE:
238 case CmpInst::ICMP_ULE:
239 case CmpInst::ICMP_SLE:
242 case CmpInst::FCMP_ONE:
243 case CmpInst::ICMP_NE:
246 case CmpInst::FCMP_ORD:
249 case CmpInst::FCMP_UNO:
254 // Determine whether the type Ty is simple enough to be handled by
255 // fast-isel, and return its equivalent machine type in VT.
256 // FIXME: Copied directly from ARM -- factor into base class?
257 bool PPCFastISel::isTypeLegal(Type *Ty, MVT &VT) {
258 EVT Evt = TLI.getValueType(Ty, true);
260 // Only handle simple types.
261 if (Evt == MVT::Other || !Evt.isSimple()) return false;
262 VT = Evt.getSimpleVT();
264 // Handle all legal types, i.e. a register that will directly hold this
266 return TLI.isTypeLegal(VT);
269 // Determine whether the type Ty is simple enough to be handled by
270 // fast-isel as a load target, and return its equivalent machine type in VT.
271 bool PPCFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
272 if (isTypeLegal(Ty, VT)) return true;
274 // If this is a type than can be sign or zero-extended to a basic operation
275 // go ahead and accept it now.
276 if (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) {
283 // Given a value Obj, create an Address object Addr that represents its
284 // address. Return false if we can't handle it.
285 bool PPCFastISel::PPCComputeAddress(const Value *Obj, Address &Addr) {
286 const User *U = NULL;
287 unsigned Opcode = Instruction::UserOp1;
288 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
289 // Don't walk into other basic blocks unless the object is an alloca from
290 // another block, otherwise it may not have a virtual register assigned.
291 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
292 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
293 Opcode = I->getOpcode();
296 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
297 Opcode = C->getOpcode();
304 case Instruction::BitCast:
305 // Look through bitcasts.
306 return PPCComputeAddress(U->getOperand(0), Addr);
307 case Instruction::IntToPtr:
308 // Look past no-op inttoptrs.
309 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
310 return PPCComputeAddress(U->getOperand(0), Addr);
312 case Instruction::PtrToInt:
313 // Look past no-op ptrtoints.
314 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
315 return PPCComputeAddress(U->getOperand(0), Addr);
317 case Instruction::GetElementPtr: {
318 Address SavedAddr = Addr;
319 long TmpOffset = Addr.Offset;
321 // Iterate through the GEP folding the constants into offsets where
323 gep_type_iterator GTI = gep_type_begin(U);
324 for (User::const_op_iterator II = U->op_begin() + 1, IE = U->op_end();
325 II != IE; ++II, ++GTI) {
326 const Value *Op = *II;
327 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
328 const StructLayout *SL = TD.getStructLayout(STy);
329 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
330 TmpOffset += SL->getElementOffset(Idx);
332 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
334 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
335 // Constant-offset addressing.
336 TmpOffset += CI->getSExtValue() * S;
339 if (isa<AddOperator>(Op) &&
340 (!isa<Instruction>(Op) ||
341 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
343 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
344 // An add (in the same block) with a constant operand. Fold the
347 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
348 TmpOffset += CI->getSExtValue() * S;
349 // Iterate on the other operand.
350 Op = cast<AddOperator>(Op)->getOperand(0);
354 goto unsupported_gep;
359 // Try to grab the base operand now.
360 Addr.Offset = TmpOffset;
361 if (PPCComputeAddress(U->getOperand(0), Addr)) return true;
363 // We failed, restore everything and try the other options.
369 case Instruction::Alloca: {
370 const AllocaInst *AI = cast<AllocaInst>(Obj);
371 DenseMap<const AllocaInst*, int>::iterator SI =
372 FuncInfo.StaticAllocaMap.find(AI);
373 if (SI != FuncInfo.StaticAllocaMap.end()) {
374 Addr.BaseType = Address::FrameIndexBase;
375 Addr.Base.FI = SI->second;
382 // FIXME: References to parameters fall through to the behavior
383 // below. They should be able to reference a frame index since
384 // they are stored to the stack, so we can get "ld rx, offset(r1)"
385 // instead of "addi ry, r1, offset / ld rx, 0(ry)". Obj will
386 // just contain the parameter. Try to handle this with a FI.
388 // Try to get this in a register if nothing else has worked.
389 if (Addr.Base.Reg == 0)
390 Addr.Base.Reg = getRegForValue(Obj);
392 // Prevent assignment of base register to X0, which is inappropriate
393 // for loads and stores alike.
394 if (Addr.Base.Reg != 0)
395 MRI.setRegClass(Addr.Base.Reg, &PPC::G8RC_and_G8RC_NOX0RegClass);
397 return Addr.Base.Reg != 0;
400 // Fix up some addresses that can't be used directly. For example, if
401 // an offset won't fit in an instruction field, we may need to move it
402 // into an index register.
403 void PPCFastISel::PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
404 unsigned &IndexReg) {
406 // Check whether the offset fits in the instruction field.
407 if (!isInt<16>(Addr.Offset))
410 // If this is a stack pointer and the offset needs to be simplified then
411 // put the alloca address into a register, set the base type back to
412 // register and continue. This should almost never happen.
413 if (!UseOffset && Addr.BaseType == Address::FrameIndexBase) {
414 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
415 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDI8),
416 ResultReg).addFrameIndex(Addr.Base.FI).addImm(0);
417 Addr.Base.Reg = ResultReg;
418 Addr.BaseType = Address::RegBase;
422 IntegerType *OffsetTy = ((VT == MVT::i32) ? Type::getInt32Ty(*Context)
423 : Type::getInt64Ty(*Context));
424 const ConstantInt *Offset =
425 ConstantInt::getSigned(OffsetTy, (int64_t)(Addr.Offset));
426 IndexReg = PPCMaterializeInt(Offset, MVT::i64);
427 assert(IndexReg && "Unexpected error in PPCMaterializeInt!");
431 // Emit a load instruction if possible, returning true if we succeeded,
432 // otherwise false. See commentary below for how the register class of
433 // the load is determined.
434 bool PPCFastISel::PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
435 const TargetRegisterClass *RC,
436 bool IsZExt, unsigned FP64LoadOpc) {
438 bool UseOffset = true;
440 // If ResultReg is given, it determines the register class of the load.
441 // Otherwise, RC is the register class to use. If the result of the
442 // load isn't anticipated in this block, both may be zero, in which
443 // case we must make a conservative guess. In particular, don't assign
444 // R0 or X0 to the result register, as the result may be used in a load,
445 // store, add-immediate, or isel that won't permit this. (Though
446 // perhaps the spill and reload of live-exit values would handle this?)
447 const TargetRegisterClass *UseRC =
448 (ResultReg ? MRI.getRegClass(ResultReg) :
450 (VT == MVT::f64 ? &PPC::F8RCRegClass :
451 (VT == MVT::f32 ? &PPC::F4RCRegClass :
452 (VT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
453 &PPC::GPRC_and_GPRC_NOR0RegClass)))));
455 bool Is32BitInt = UseRC->hasSuperClassEq(&PPC::GPRCRegClass);
457 switch (VT.SimpleTy) {
458 default: // e.g., vector types not handled
461 Opc = Is32BitInt ? PPC::LBZ : PPC::LBZ8;
465 (Is32BitInt ? PPC::LHZ : PPC::LHZ8) :
466 (Is32BitInt ? PPC::LHA : PPC::LHA8));
470 (Is32BitInt ? PPC::LWZ : PPC::LWZ8) :
471 (Is32BitInt ? PPC::LWA_32 : PPC::LWA));
472 if ((Opc == PPC::LWA || Opc == PPC::LWA_32) && ((Addr.Offset & 3) != 0))
477 assert(UseRC->hasSuperClassEq(&PPC::G8RCRegClass) &&
478 "64-bit load with 32-bit target??");
479 UseOffset = ((Addr.Offset & 3) == 0);
489 // If necessary, materialize the offset into a register and use
490 // the indexed form. Also handle stack pointers with special needs.
491 unsigned IndexReg = 0;
492 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
494 ResultReg = createResultReg(UseRC);
496 // Note: If we still have a frame index here, we know the offset is
497 // in range, as otherwise PPCSimplifyAddress would have converted it
499 if (Addr.BaseType == Address::FrameIndexBase) {
501 MachineMemOperand *MMO =
502 FuncInfo.MF->getMachineMemOperand(
503 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
504 MachineMemOperand::MOLoad, MFI.getObjectSize(Addr.Base.FI),
505 MFI.getObjectAlignment(Addr.Base.FI));
507 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
508 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
510 // Base reg with offset in range.
511 } else if (UseOffset) {
513 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
514 .addImm(Addr.Offset).addReg(Addr.Base.Reg);
518 // Get the RR opcode corresponding to the RI one. FIXME: It would be
519 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
520 // is hard to get at.
522 default: llvm_unreachable("Unexpected opcode!");
523 case PPC::LBZ: Opc = PPC::LBZX; break;
524 case PPC::LBZ8: Opc = PPC::LBZX8; break;
525 case PPC::LHZ: Opc = PPC::LHZX; break;
526 case PPC::LHZ8: Opc = PPC::LHZX8; break;
527 case PPC::LHA: Opc = PPC::LHAX; break;
528 case PPC::LHA8: Opc = PPC::LHAX8; break;
529 case PPC::LWZ: Opc = PPC::LWZX; break;
530 case PPC::LWZ8: Opc = PPC::LWZX8; break;
531 case PPC::LWA: Opc = PPC::LWAX; break;
532 case PPC::LWA_32: Opc = PPC::LWAX_32; break;
533 case PPC::LD: Opc = PPC::LDX; break;
534 case PPC::LFS: Opc = PPC::LFSX; break;
535 case PPC::LFD: Opc = PPC::LFDX; break;
537 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
538 .addReg(Addr.Base.Reg).addReg(IndexReg);
544 // Attempt to fast-select a load instruction.
545 bool PPCFastISel::SelectLoad(const Instruction *I) {
546 // FIXME: No atomic loads are supported.
547 if (cast<LoadInst>(I)->isAtomic())
550 // Verify we have a legal type before going any further.
552 if (!isLoadTypeLegal(I->getType(), VT))
555 // See if we can handle this address.
557 if (!PPCComputeAddress(I->getOperand(0), Addr))
560 // Look at the currently assigned register for this instruction
561 // to determine the required register class. This is necessary
562 // to constrain RA from using R0/X0 when this is not legal.
563 unsigned AssignedReg = FuncInfo.ValueMap[I];
564 const TargetRegisterClass *RC =
565 AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
567 unsigned ResultReg = 0;
568 if (!PPCEmitLoad(VT, ResultReg, Addr, RC))
570 UpdateValueMap(I, ResultReg);
574 // Emit a store instruction to store SrcReg at Addr.
575 bool PPCFastISel::PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr) {
576 assert(SrcReg && "Nothing to store!");
578 bool UseOffset = true;
580 const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
581 bool Is32BitInt = RC->hasSuperClassEq(&PPC::GPRCRegClass);
583 switch (VT.SimpleTy) {
584 default: // e.g., vector types not handled
587 Opc = Is32BitInt ? PPC::STB : PPC::STB8;
590 Opc = Is32BitInt ? PPC::STH : PPC::STH8;
593 assert(Is32BitInt && "Not GPRC for i32??");
598 UseOffset = ((Addr.Offset & 3) == 0);
608 // If necessary, materialize the offset into a register and use
609 // the indexed form. Also handle stack pointers with special needs.
610 unsigned IndexReg = 0;
611 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
613 // Note: If we still have a frame index here, we know the offset is
614 // in range, as otherwise PPCSimplifyAddress would have converted it
616 if (Addr.BaseType == Address::FrameIndexBase) {
617 MachineMemOperand *MMO =
618 FuncInfo.MF->getMachineMemOperand(
619 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
620 MachineMemOperand::MOStore, MFI.getObjectSize(Addr.Base.FI),
621 MFI.getObjectAlignment(Addr.Base.FI));
623 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc)).addReg(SrcReg)
624 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
626 // Base reg with offset in range.
627 } else if (UseOffset)
628 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
629 .addReg(SrcReg).addImm(Addr.Offset).addReg(Addr.Base.Reg);
633 // Get the RR opcode corresponding to the RI one. FIXME: It would be
634 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
635 // is hard to get at.
637 default: llvm_unreachable("Unexpected opcode!");
638 case PPC::STB: Opc = PPC::STBX; break;
639 case PPC::STH : Opc = PPC::STHX; break;
640 case PPC::STW : Opc = PPC::STWX; break;
641 case PPC::STB8: Opc = PPC::STBX8; break;
642 case PPC::STH8: Opc = PPC::STHX8; break;
643 case PPC::STW8: Opc = PPC::STWX8; break;
644 case PPC::STD: Opc = PPC::STDX; break;
645 case PPC::STFS: Opc = PPC::STFSX; break;
646 case PPC::STFD: Opc = PPC::STFDX; break;
648 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
649 .addReg(SrcReg).addReg(Addr.Base.Reg).addReg(IndexReg);
655 // Attempt to fast-select a store instruction.
656 bool PPCFastISel::SelectStore(const Instruction *I) {
657 Value *Op0 = I->getOperand(0);
660 // FIXME: No atomics loads are supported.
661 if (cast<StoreInst>(I)->isAtomic())
664 // Verify we have a legal type before going any further.
666 if (!isLoadTypeLegal(Op0->getType(), VT))
669 // Get the value to be stored into a register.
670 SrcReg = getRegForValue(Op0);
674 // See if we can handle this address.
676 if (!PPCComputeAddress(I->getOperand(1), Addr))
679 if (!PPCEmitStore(VT, SrcReg, Addr))
685 // Attempt to fast-select a branch instruction.
686 bool PPCFastISel::SelectBranch(const Instruction *I) {
687 const BranchInst *BI = cast<BranchInst>(I);
688 MachineBasicBlock *BrBB = FuncInfo.MBB;
689 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
690 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
692 // For now, just try the simplest case where it's fed by a compare.
693 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
694 Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
698 PPC::Predicate PPCPred = OptPPCPred.getValue();
700 // Take advantage of fall-through opportunities.
701 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
703 PPCPred = PPC::InvertPredicate(PPCPred);
706 unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
708 if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
712 BuildMI(*BrBB, FuncInfo.InsertPt, DL, TII.get(PPC::BCC))
713 .addImm(PPCPred).addReg(CondReg).addMBB(TBB);
714 FastEmitBranch(FBB, DL);
715 FuncInfo.MBB->addSuccessor(TBB);
718 } else if (const ConstantInt *CI =
719 dyn_cast<ConstantInt>(BI->getCondition())) {
720 uint64_t Imm = CI->getZExtValue();
721 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
722 FastEmitBranch(Target, DL);
726 // FIXME: ARM looks for a case where the block containing the compare
727 // has been split from the block containing the branch. If this happens,
728 // there is a vreg available containing the result of the compare. I'm
729 // not sure we can do much, as we've lost the predicate information with
730 // the compare instruction -- we have a 4-bit CR but don't know which bit
735 // Attempt to emit a compare of the two source values. Signed and unsigned
736 // comparisons are supported. Return false if we can't handle it.
737 bool PPCFastISel::PPCEmitCmp(const Value *SrcValue1, const Value *SrcValue2,
738 bool IsZExt, unsigned DestReg) {
739 Type *Ty = SrcValue1->getType();
740 EVT SrcEVT = TLI.getValueType(Ty, true);
741 if (!SrcEVT.isSimple())
743 MVT SrcVT = SrcEVT.getSimpleVT();
745 // See if operand 2 is an immediate encodeable in the compare.
746 // FIXME: Operands are not in canonical order at -O0, so an immediate
747 // operand in position 1 is a lost opportunity for now. We are
748 // similar to ARM in this regard.
752 // Only 16-bit integer constants can be represented in compares for
753 // PowerPC. Others will be materialized into a register.
754 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(SrcValue2)) {
755 if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
756 SrcVT == MVT::i8 || SrcVT == MVT::i1) {
757 const APInt &CIVal = ConstInt->getValue();
758 Imm = (IsZExt) ? (long)CIVal.getZExtValue() : (long)CIVal.getSExtValue();
759 if ((IsZExt && isUInt<16>(Imm)) || (!IsZExt && isInt<16>(Imm)))
765 bool NeedsExt = false;
766 switch (SrcVT.SimpleTy) {
767 default: return false;
769 CmpOpc = PPC::FCMPUS;
772 CmpOpc = PPC::FCMPUD;
778 // Intentional fall-through.
781 CmpOpc = IsZExt ? PPC::CMPLW : PPC::CMPW;
783 CmpOpc = IsZExt ? PPC::CMPLWI : PPC::CMPWI;
787 CmpOpc = IsZExt ? PPC::CMPLD : PPC::CMPD;
789 CmpOpc = IsZExt ? PPC::CMPLDI : PPC::CMPDI;
793 unsigned SrcReg1 = getRegForValue(SrcValue1);
797 unsigned SrcReg2 = 0;
799 SrcReg2 = getRegForValue(SrcValue2);
805 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
806 if (!PPCEmitIntExt(SrcVT, SrcReg1, MVT::i32, ExtReg, IsZExt))
811 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
812 if (!PPCEmitIntExt(SrcVT, SrcReg2, MVT::i32, ExtReg, IsZExt))
819 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc), DestReg)
820 .addReg(SrcReg1).addReg(SrcReg2);
822 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc), DestReg)
823 .addReg(SrcReg1).addImm(Imm);
828 // Attempt to fast-select a floating-point extend instruction.
829 bool PPCFastISel::SelectFPExt(const Instruction *I) {
830 Value *Src = I->getOperand(0);
831 EVT SrcVT = TLI.getValueType(Src->getType(), true);
832 EVT DestVT = TLI.getValueType(I->getType(), true);
834 if (SrcVT != MVT::f32 || DestVT != MVT::f64)
837 unsigned SrcReg = getRegForValue(Src);
841 // No code is generated for a FP extend.
842 UpdateValueMap(I, SrcReg);
846 // Attempt to fast-select a floating-point truncate instruction.
847 bool PPCFastISel::SelectFPTrunc(const Instruction *I) {
848 Value *Src = I->getOperand(0);
849 EVT SrcVT = TLI.getValueType(Src->getType(), true);
850 EVT DestVT = TLI.getValueType(I->getType(), true);
852 if (SrcVT != MVT::f64 || DestVT != MVT::f32)
855 unsigned SrcReg = getRegForValue(Src);
859 // Round the result to single precision.
860 unsigned DestReg = createResultReg(&PPC::F4RCRegClass);
861 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::FRSP), DestReg)
864 UpdateValueMap(I, DestReg);
868 // Move an i32 or i64 value in a GPR to an f64 value in an FPR.
869 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
870 // those should be used instead of moving via a stack slot when the
871 // subtarget permits.
872 // FIXME: The code here is sloppy for the 4-byte case. Can use a 4-byte
873 // stack slot and 4-byte store/load sequence. Or just sext the 4-byte
874 // case to 8 bytes which produces tighter code but wastes stack space.
875 unsigned PPCFastISel::PPCMoveToFPReg(MVT SrcVT, unsigned SrcReg,
878 // If necessary, extend 32-bit int to 64-bit.
879 if (SrcVT == MVT::i32) {
880 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
881 if (!PPCEmitIntExt(MVT::i32, SrcReg, MVT::i64, TmpReg, !IsSigned))
886 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
888 Addr.BaseType = Address::FrameIndexBase;
889 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
891 // Store the value from the GPR.
892 if (!PPCEmitStore(MVT::i64, SrcReg, Addr))
895 // Load the integer value into an FPR. The kind of load used depends
896 // on a number of conditions.
897 unsigned LoadOpc = PPC::LFD;
899 if (SrcVT == MVT::i32) {
902 LoadOpc = PPC::LFIWZX;
903 else if (PPCSubTarget.hasLFIWAX())
904 LoadOpc = PPC::LFIWAX;
907 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
908 unsigned ResultReg = 0;
909 if (!PPCEmitLoad(MVT::f64, ResultReg, Addr, RC, !IsSigned, LoadOpc))
915 // Attempt to fast-select an integer-to-floating-point conversion.
916 bool PPCFastISel::SelectIToFP(const Instruction *I, bool IsSigned) {
918 Type *DstTy = I->getType();
919 if (!isTypeLegal(DstTy, DstVT))
922 if (DstVT != MVT::f32 && DstVT != MVT::f64)
925 Value *Src = I->getOperand(0);
926 EVT SrcEVT = TLI.getValueType(Src->getType(), true);
927 if (!SrcEVT.isSimple())
930 MVT SrcVT = SrcEVT.getSimpleVT();
932 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 &&
933 SrcVT != MVT::i32 && SrcVT != MVT::i64)
936 unsigned SrcReg = getRegForValue(Src);
940 // We can only lower an unsigned convert if we have the newer
941 // floating-point conversion operations.
942 if (!IsSigned && !PPCSubTarget.hasFPCVT())
945 // FIXME: For now we require the newer floating-point conversion operations
946 // (which are present only on P7 and A2 server models) when converting
947 // to single-precision float. Otherwise we have to generate a lot of
948 // fiddly code to avoid double rounding. If necessary, the fiddly code
949 // can be found in PPCTargetLowering::LowerINT_TO_FP().
950 if (DstVT == MVT::f32 && !PPCSubTarget.hasFPCVT())
953 // Extend the input if necessary.
954 if (SrcVT == MVT::i8 || SrcVT == MVT::i16) {
955 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
956 if (!PPCEmitIntExt(SrcVT, SrcReg, MVT::i64, TmpReg, !IsSigned))
962 // Move the integer value to an FPR.
963 unsigned FPReg = PPCMoveToFPReg(SrcVT, SrcReg, IsSigned);
967 // Determine the opcode for the conversion.
968 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
969 unsigned DestReg = createResultReg(RC);
972 if (DstVT == MVT::f32)
973 Opc = IsSigned ? PPC::FCFIDS : PPC::FCFIDUS;
975 Opc = IsSigned ? PPC::FCFID : PPC::FCFIDU;
977 // Generate the convert.
978 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
981 UpdateValueMap(I, DestReg);
985 // Move the floating-point value in SrcReg into an integer destination
986 // register, and return the register (or zero if we can't handle it).
987 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
988 // those should be used instead of moving via a stack slot when the
989 // subtarget permits.
990 unsigned PPCFastISel::PPCMoveToIntReg(const Instruction *I, MVT VT,
991 unsigned SrcReg, bool IsSigned) {
992 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
993 // Note that if have STFIWX available, we could use a 4-byte stack
994 // slot for i32, but this being fast-isel we'll just go with the
995 // easiest code gen possible.
997 Addr.BaseType = Address::FrameIndexBase;
998 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
1000 // Store the value from the FPR.
1001 if (!PPCEmitStore(MVT::f64, SrcReg, Addr))
1004 // Reload it into a GPR. If we want an i32, modify the address
1005 // to have a 4-byte offset so we load from the right place.
1009 // Look at the currently assigned register for this instruction
1010 // to determine the required register class.
1011 unsigned AssignedReg = FuncInfo.ValueMap[I];
1012 const TargetRegisterClass *RC =
1013 AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
1015 unsigned ResultReg = 0;
1016 if (!PPCEmitLoad(VT, ResultReg, Addr, RC, !IsSigned))
1022 // Attempt to fast-select a floating-point-to-integer conversion.
1023 bool PPCFastISel::SelectFPToI(const Instruction *I, bool IsSigned) {
1025 Type *DstTy = I->getType();
1026 if (!isTypeLegal(DstTy, DstVT))
1029 if (DstVT != MVT::i32 && DstVT != MVT::i64)
1032 Value *Src = I->getOperand(0);
1033 Type *SrcTy = Src->getType();
1034 if (!isTypeLegal(SrcTy, SrcVT))
1037 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
1040 unsigned SrcReg = getRegForValue(Src);
1044 // Convert f32 to f64 if necessary. This is just a meaningless copy
1045 // to get the register class right. COPY_TO_REGCLASS is needed since
1046 // a COPY from F4RC to F8RC is converted to a F4RC-F4RC copy downstream.
1047 const TargetRegisterClass *InRC = MRI.getRegClass(SrcReg);
1048 if (InRC == &PPC::F4RCRegClass) {
1049 unsigned TmpReg = createResultReg(&PPC::F8RCRegClass);
1050 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1051 TII.get(TargetOpcode::COPY_TO_REGCLASS), TmpReg)
1052 .addReg(SrcReg).addImm(PPC::F8RCRegClassID);
1056 // Determine the opcode for the conversion, which takes place
1057 // entirely within FPRs.
1058 unsigned DestReg = createResultReg(&PPC::F8RCRegClass);
1061 if (DstVT == MVT::i32)
1065 Opc = PPCSubTarget.hasFPCVT() ? PPC::FCTIWUZ : PPC::FCTIDZ;
1067 Opc = IsSigned ? PPC::FCTIDZ : PPC::FCTIDUZ;
1069 // Generate the convert.
1070 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1073 // Now move the integer value from a float register to an integer register.
1074 unsigned IntReg = PPCMoveToIntReg(I, DstVT, DestReg, IsSigned);
1078 UpdateValueMap(I, IntReg);
1082 // Attempt to fast-select a binary integer operation that isn't already
1083 // handled automatically.
1084 bool PPCFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1085 EVT DestVT = TLI.getValueType(I->getType(), true);
1087 // We can get here in the case when we have a binary operation on a non-legal
1088 // type and the target independent selector doesn't know how to handle it.
1089 if (DestVT != MVT::i16 && DestVT != MVT::i8)
1092 // Look at the currently assigned register for this instruction
1093 // to determine the required register class. If there is no register,
1094 // make a conservative choice (don't assign R0).
1095 unsigned AssignedReg = FuncInfo.ValueMap[I];
1096 const TargetRegisterClass *RC =
1097 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1098 &PPC::GPRC_and_GPRC_NOR0RegClass);
1099 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1102 switch (ISDOpcode) {
1103 default: return false;
1105 Opc = IsGPRC ? PPC::ADD4 : PPC::ADD8;
1108 Opc = IsGPRC ? PPC::OR : PPC::OR8;
1111 Opc = IsGPRC ? PPC::SUBF : PPC::SUBF8;
1115 unsigned ResultReg = createResultReg(RC ? RC : &PPC::G8RCRegClass);
1116 unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1117 if (SrcReg1 == 0) return false;
1119 // Handle case of small immediate operand.
1120 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(1))) {
1121 const APInt &CIVal = ConstInt->getValue();
1122 int Imm = (int)CIVal.getSExtValue();
1124 if (isInt<16>(Imm)) {
1127 llvm_unreachable("Missing case!");
1130 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1134 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1147 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1156 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1163 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1164 .addReg(SrcReg1).addImm(Imm);
1165 UpdateValueMap(I, ResultReg);
1172 unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1173 if (SrcReg2 == 0) return false;
1175 // Reverse operands for subtract-from.
1176 if (ISDOpcode == ISD::SUB)
1177 std::swap(SrcReg1, SrcReg2);
1179 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1180 .addReg(SrcReg1).addReg(SrcReg2);
1181 UpdateValueMap(I, ResultReg);
1185 // Handle arguments to a call that we're attempting to fast-select.
1186 // Return false if the arguments are too complex for us at the moment.
1187 bool PPCFastISel::processCallArgs(SmallVectorImpl<Value*> &Args,
1188 SmallVectorImpl<unsigned> &ArgRegs,
1189 SmallVectorImpl<MVT> &ArgVTs,
1190 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1191 SmallVectorImpl<unsigned> &RegArgs,
1195 SmallVector<CCValAssign, 16> ArgLocs;
1196 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, ArgLocs, *Context);
1197 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_PPC64_ELF_FIS);
1199 // Bail out if we can't handle any of the arguments.
1200 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1201 CCValAssign &VA = ArgLocs[I];
1202 MVT ArgVT = ArgVTs[VA.getValNo()];
1204 // Skip vector arguments for now, as well as long double and
1205 // uint128_t, and anything that isn't passed in a register.
1206 if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64 ||
1207 !VA.isRegLoc() || VA.needsCustom())
1210 // Skip bit-converted arguments for now.
1211 if (VA.getLocInfo() == CCValAssign::BCvt)
1215 // Get a count of how many bytes are to be pushed onto the stack.
1216 NumBytes = CCInfo.getNextStackOffset();
1218 // Issue CALLSEQ_START.
1219 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1220 TII.get(TII.getCallFrameSetupOpcode()))
1223 // Prepare to assign register arguments. Every argument uses up a
1224 // GPR protocol register even if it's passed in a floating-point
1226 unsigned NextGPR = PPC::X3;
1227 unsigned NextFPR = PPC::F1;
1229 // Process arguments.
1230 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1231 CCValAssign &VA = ArgLocs[I];
1232 unsigned Arg = ArgRegs[VA.getValNo()];
1233 MVT ArgVT = ArgVTs[VA.getValNo()];
1235 // Handle argument promotion and bitcasts.
1236 switch (VA.getLocInfo()) {
1238 llvm_unreachable("Unknown loc info!");
1239 case CCValAssign::Full:
1241 case CCValAssign::SExt: {
1242 MVT DestVT = VA.getLocVT();
1243 const TargetRegisterClass *RC =
1244 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1245 unsigned TmpReg = createResultReg(RC);
1246 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/false))
1247 llvm_unreachable("Failed to emit a sext!");
1252 case CCValAssign::AExt:
1253 case CCValAssign::ZExt: {
1254 MVT DestVT = VA.getLocVT();
1255 const TargetRegisterClass *RC =
1256 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1257 unsigned TmpReg = createResultReg(RC);
1258 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/true))
1259 llvm_unreachable("Failed to emit a zext!");
1264 case CCValAssign::BCvt: {
1265 // FIXME: Not yet handled.
1266 llvm_unreachable("Should have bailed before getting here!");
1271 // Copy this argument to the appropriate register.
1273 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) {
1279 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1280 ArgReg).addReg(Arg);
1281 RegArgs.push_back(ArgReg);
1287 // For a call that we've determined we can fast-select, finish the
1288 // call sequence and generate a copy to obtain the return value (if any).
1289 void PPCFastISel::finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1290 const Instruction *I, CallingConv::ID CC,
1291 unsigned &NumBytes, bool IsVarArg) {
1292 // Issue CallSEQ_END.
1293 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1294 TII.get(TII.getCallFrameDestroyOpcode()))
1295 .addImm(NumBytes).addImm(0);
1297 // Next, generate a copy to obtain the return value.
1298 // FIXME: No multi-register return values yet, though I don't foresee
1299 // any real difficulties there.
1300 if (RetVT != MVT::isVoid) {
1301 SmallVector<CCValAssign, 16> RVLocs;
1302 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
1303 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1304 CCValAssign &VA = RVLocs[0];
1305 assert(RVLocs.size() == 1 && "No support for multi-reg return values!");
1306 assert(VA.isRegLoc() && "Can only return in registers!");
1308 MVT DestVT = VA.getValVT();
1309 MVT CopyVT = DestVT;
1311 // Ints smaller than a register still arrive in a full 64-bit
1312 // register, so make sure we recognize this.
1313 if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32)
1316 unsigned SourcePhysReg = VA.getLocReg();
1317 unsigned ResultReg = 0;
1319 if (RetVT == CopyVT) {
1320 const TargetRegisterClass *CpyRC = TLI.getRegClassFor(CopyVT);
1321 ResultReg = createResultReg(CpyRC);
1323 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1324 TII.get(TargetOpcode::COPY), ResultReg)
1325 .addReg(SourcePhysReg);
1327 // If necessary, round the floating result to single precision.
1328 } else if (CopyVT == MVT::f64) {
1329 ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1330 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::FRSP),
1331 ResultReg).addReg(SourcePhysReg);
1333 // If only the low half of a general register is needed, generate
1334 // a GPRC copy instead of a G8RC copy. (EXTRACT_SUBREG can't be
1335 // used along the fast-isel path (not lowered), and downstream logic
1336 // also doesn't like a direct subreg copy on a physical reg.)
1337 } else if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32) {
1338 ResultReg = createResultReg(&PPC::GPRCRegClass);
1339 // Convert physical register from G8RC to GPRC.
1340 SourcePhysReg -= PPC::X0 - PPC::R0;
1341 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1342 TII.get(TargetOpcode::COPY), ResultReg)
1343 .addReg(SourcePhysReg);
1346 assert(ResultReg && "ResultReg unset!");
1347 UsedRegs.push_back(SourcePhysReg);
1348 UpdateValueMap(I, ResultReg);
1352 // Attempt to fast-select a call instruction.
1353 bool PPCFastISel::SelectCall(const Instruction *I) {
1354 const CallInst *CI = cast<CallInst>(I);
1355 const Value *Callee = CI->getCalledValue();
1357 // Can't handle inline asm.
1358 if (isa<InlineAsm>(Callee))
1361 // Allow SelectionDAG isel to handle tail calls.
1362 if (CI->isTailCall())
1365 // Obtain calling convention.
1366 ImmutableCallSite CS(CI);
1367 CallingConv::ID CC = CS.getCallingConv();
1369 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1370 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1371 bool IsVarArg = FTy->isVarArg();
1373 // Not ready for varargs yet.
1377 // Handle simple calls for now, with legal return types and
1378 // those that can be extended.
1379 Type *RetTy = I->getType();
1381 if (RetTy->isVoidTy())
1382 RetVT = MVT::isVoid;
1383 else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
1387 // FIXME: No multi-register return values yet.
1388 if (RetVT != MVT::isVoid && RetVT != MVT::i8 && RetVT != MVT::i16 &&
1389 RetVT != MVT::i32 && RetVT != MVT::i64 && RetVT != MVT::f32 &&
1390 RetVT != MVT::f64) {
1391 SmallVector<CCValAssign, 16> RVLocs;
1392 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
1393 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1394 if (RVLocs.size() > 1)
1398 // Bail early if more than 8 arguments, as we only currently
1399 // handle arguments passed in registers.
1400 unsigned NumArgs = CS.arg_size();
1404 // Set up the argument vectors.
1405 SmallVector<Value*, 8> Args;
1406 SmallVector<unsigned, 8> ArgRegs;
1407 SmallVector<MVT, 8> ArgVTs;
1408 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1410 Args.reserve(NumArgs);
1411 ArgRegs.reserve(NumArgs);
1412 ArgVTs.reserve(NumArgs);
1413 ArgFlags.reserve(NumArgs);
1415 for (ImmutableCallSite::arg_iterator II = CS.arg_begin(), IE = CS.arg_end();
1417 // FIXME: ARM does something for intrinsic calls here, check into that.
1419 unsigned AttrIdx = II - CS.arg_begin() + 1;
1421 // Only handle easy calls for now. It would be reasonably easy
1422 // to handle <= 8-byte structures passed ByVal in registers, but we
1423 // have to ensure they are right-justified in the register.
1424 if (CS.paramHasAttr(AttrIdx, Attribute::InReg) ||
1425 CS.paramHasAttr(AttrIdx, Attribute::StructRet) ||
1426 CS.paramHasAttr(AttrIdx, Attribute::Nest) ||
1427 CS.paramHasAttr(AttrIdx, Attribute::ByVal))
1430 ISD::ArgFlagsTy Flags;
1431 if (CS.paramHasAttr(AttrIdx, Attribute::SExt))
1433 if (CS.paramHasAttr(AttrIdx, Attribute::ZExt))
1436 Type *ArgTy = (*II)->getType();
1438 if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8)
1441 if (ArgVT.isVector())
1444 unsigned Arg = getRegForValue(*II);
1448 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1449 Flags.setOrigAlign(OriginalAlignment);
1451 Args.push_back(*II);
1452 ArgRegs.push_back(Arg);
1453 ArgVTs.push_back(ArgVT);
1454 ArgFlags.push_back(Flags);
1457 // Process the arguments.
1458 SmallVector<unsigned, 8> RegArgs;
1461 if (!processCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
1462 RegArgs, CC, NumBytes, IsVarArg))
1465 // FIXME: No handling for function pointers yet. This requires
1466 // implementing the function descriptor (OPD) setup.
1467 const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1471 // Build direct call with NOP for TOC restore.
1472 // FIXME: We can and should optimize away the NOP for local calls.
1473 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1474 TII.get(PPC::BL8_NOP));
1476 MIB.addGlobalAddress(GV);
1478 // Add implicit physical register uses to the call.
1479 for (unsigned II = 0, IE = RegArgs.size(); II != IE; ++II)
1480 MIB.addReg(RegArgs[II], RegState::Implicit);
1482 // Add a register mask with the call-preserved registers. Proper
1483 // defs for return values will be added by setPhysRegsDeadExcept().
1484 MIB.addRegMask(TRI.getCallPreservedMask(CC));
1486 // Finish off the call including any return values.
1487 SmallVector<unsigned, 4> UsedRegs;
1488 finishCall(RetVT, UsedRegs, I, CC, NumBytes, IsVarArg);
1490 // Set all unused physregs defs as dead.
1491 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1496 // Attempt to fast-select a return instruction.
1497 bool PPCFastISel::SelectRet(const Instruction *I) {
1499 if (!FuncInfo.CanLowerReturn)
1502 const ReturnInst *Ret = cast<ReturnInst>(I);
1503 const Function &F = *I->getParent()->getParent();
1505 // Build a list of return value registers.
1506 SmallVector<unsigned, 4> RetRegs;
1507 CallingConv::ID CC = F.getCallingConv();
1509 if (Ret->getNumOperands() > 0) {
1510 SmallVector<ISD::OutputArg, 4> Outs;
1511 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1513 // Analyze operands of the call, assigning locations to each operand.
1514 SmallVector<CCValAssign, 16> ValLocs;
1515 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs, *Context);
1516 CCInfo.AnalyzeReturn(Outs, RetCC_PPC64_ELF_FIS);
1517 const Value *RV = Ret->getOperand(0);
1519 // FIXME: Only one output register for now.
1520 if (ValLocs.size() > 1)
1523 // Special case for returning a constant integer of any size.
1524 // Materialize the constant as an i64 and copy it to the return
1525 // register. This avoids an unnecessary extend or truncate.
1526 if (isa<ConstantInt>(*RV)) {
1527 const Constant *C = cast<Constant>(RV);
1528 unsigned SrcReg = PPCMaterializeInt(C, MVT::i64);
1529 unsigned RetReg = ValLocs[0].getLocReg();
1530 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1531 RetReg).addReg(SrcReg);
1532 RetRegs.push_back(RetReg);
1535 unsigned Reg = getRegForValue(RV);
1540 // Copy the result values into the output registers.
1541 for (unsigned i = 0; i < ValLocs.size(); ++i) {
1543 CCValAssign &VA = ValLocs[i];
1544 assert(VA.isRegLoc() && "Can only return in registers!");
1545 RetRegs.push_back(VA.getLocReg());
1546 unsigned SrcReg = Reg + VA.getValNo();
1548 EVT RVEVT = TLI.getValueType(RV->getType());
1549 if (!RVEVT.isSimple())
1551 MVT RVVT = RVEVT.getSimpleVT();
1552 MVT DestVT = VA.getLocVT();
1554 if (RVVT != DestVT && RVVT != MVT::i8 &&
1555 RVVT != MVT::i16 && RVVT != MVT::i32)
1558 if (RVVT != DestVT) {
1559 switch (VA.getLocInfo()) {
1561 llvm_unreachable("Unknown loc info!");
1562 case CCValAssign::Full:
1563 llvm_unreachable("Full value assign but types don't match?");
1564 case CCValAssign::AExt:
1565 case CCValAssign::ZExt: {
1566 const TargetRegisterClass *RC =
1567 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1568 unsigned TmpReg = createResultReg(RC);
1569 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, true))
1574 case CCValAssign::SExt: {
1575 const TargetRegisterClass *RC =
1576 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1577 unsigned TmpReg = createResultReg(RC);
1578 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, false))
1586 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1587 TII.get(TargetOpcode::COPY), RetRegs[i])
1593 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1596 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1597 MIB.addReg(RetRegs[i], RegState::Implicit);
1602 // Attempt to emit an integer extend of SrcReg into DestReg. Both
1603 // signed and zero extensions are supported. Return false if we
1605 bool PPCFastISel::PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1606 unsigned DestReg, bool IsZExt) {
1607 if (DestVT != MVT::i32 && DestVT != MVT::i64)
1609 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 && SrcVT != MVT::i32)
1612 // Signed extensions use EXTSB, EXTSH, EXTSW.
1615 if (SrcVT == MVT::i8)
1616 Opc = (DestVT == MVT::i32) ? PPC::EXTSB : PPC::EXTSB8_32_64;
1617 else if (SrcVT == MVT::i16)
1618 Opc = (DestVT == MVT::i32) ? PPC::EXTSH : PPC::EXTSH8_32_64;
1620 assert(DestVT == MVT::i64 && "Signed extend from i32 to i32??");
1621 Opc = PPC::EXTSW_32_64;
1623 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1626 // Unsigned 32-bit extensions use RLWINM.
1627 } else if (DestVT == MVT::i32) {
1629 if (SrcVT == MVT::i8)
1632 assert(SrcVT == MVT::i16 && "Unsigned extend from i32 to i32??");
1635 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::RLWINM),
1637 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB).addImm(/*ME=*/31);
1639 // Unsigned 64-bit extensions use RLDICL (with a 32-bit source).
1642 if (SrcVT == MVT::i8)
1644 else if (SrcVT == MVT::i16)
1648 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1649 TII.get(PPC::RLDICL_32_64), DestReg)
1650 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB);
1656 // Attempt to fast-select an indirect branch instruction.
1657 bool PPCFastISel::SelectIndirectBr(const Instruction *I) {
1658 unsigned AddrReg = getRegForValue(I->getOperand(0));
1662 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::MTCTR8))
1664 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::BCTR8));
1666 const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1667 for (unsigned i = 0, e = IB->getNumSuccessors(); i != e; ++i)
1668 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[IB->getSuccessor(i)]);
1673 // Attempt to fast-select an integer truncate instruction.
1674 bool PPCFastISel::SelectTrunc(const Instruction *I) {
1675 Value *Src = I->getOperand(0);
1676 EVT SrcVT = TLI.getValueType(Src->getType(), true);
1677 EVT DestVT = TLI.getValueType(I->getType(), true);
1679 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16)
1682 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8)
1685 unsigned SrcReg = getRegForValue(Src);
1689 // The only interesting case is when we need to switch register classes.
1690 if (SrcVT == MVT::i64) {
1691 unsigned ResultReg = createResultReg(&PPC::GPRCRegClass);
1692 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1693 ResultReg).addReg(SrcReg, 0, PPC::sub_32);
1697 UpdateValueMap(I, SrcReg);
1701 // Attempt to fast-select an integer extend instruction.
1702 bool PPCFastISel::SelectIntExt(const Instruction *I) {
1703 Type *DestTy = I->getType();
1704 Value *Src = I->getOperand(0);
1705 Type *SrcTy = Src->getType();
1707 bool IsZExt = isa<ZExtInst>(I);
1708 unsigned SrcReg = getRegForValue(Src);
1709 if (!SrcReg) return false;
1711 EVT SrcEVT, DestEVT;
1712 SrcEVT = TLI.getValueType(SrcTy, true);
1713 DestEVT = TLI.getValueType(DestTy, true);
1714 if (!SrcEVT.isSimple())
1716 if (!DestEVT.isSimple())
1719 MVT SrcVT = SrcEVT.getSimpleVT();
1720 MVT DestVT = DestEVT.getSimpleVT();
1722 // If we know the register class needed for the result of this
1723 // instruction, use it. Otherwise pick the register class of the
1724 // correct size that does not contain X0/R0, since we don't know
1725 // whether downstream uses permit that assignment.
1726 unsigned AssignedReg = FuncInfo.ValueMap[I];
1727 const TargetRegisterClass *RC =
1728 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1729 (DestVT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
1730 &PPC::GPRC_and_GPRC_NOR0RegClass));
1731 unsigned ResultReg = createResultReg(RC);
1733 if (!PPCEmitIntExt(SrcVT, SrcReg, DestVT, ResultReg, IsZExt))
1736 UpdateValueMap(I, ResultReg);
1740 // Attempt to fast-select an instruction that wasn't handled by
1741 // the table-generated machinery.
1742 bool PPCFastISel::TargetSelectInstruction(const Instruction *I) {
1744 switch (I->getOpcode()) {
1745 case Instruction::Load:
1746 return SelectLoad(I);
1747 case Instruction::Store:
1748 return SelectStore(I);
1749 case Instruction::Br:
1750 return SelectBranch(I);
1751 case Instruction::IndirectBr:
1752 return SelectIndirectBr(I);
1753 case Instruction::FPExt:
1754 return SelectFPExt(I);
1755 case Instruction::FPTrunc:
1756 return SelectFPTrunc(I);
1757 case Instruction::SIToFP:
1758 return SelectIToFP(I, /*IsSigned*/ true);
1759 case Instruction::UIToFP:
1760 return SelectIToFP(I, /*IsSigned*/ false);
1761 case Instruction::FPToSI:
1762 return SelectFPToI(I, /*IsSigned*/ true);
1763 case Instruction::FPToUI:
1764 return SelectFPToI(I, /*IsSigned*/ false);
1765 case Instruction::Add:
1766 return SelectBinaryIntOp(I, ISD::ADD);
1767 case Instruction::Or:
1768 return SelectBinaryIntOp(I, ISD::OR);
1769 case Instruction::Sub:
1770 return SelectBinaryIntOp(I, ISD::SUB);
1771 case Instruction::Call:
1772 if (dyn_cast<IntrinsicInst>(I))
1774 return SelectCall(I);
1775 case Instruction::Ret:
1776 return SelectRet(I);
1777 case Instruction::Trunc:
1778 return SelectTrunc(I);
1779 case Instruction::ZExt:
1780 case Instruction::SExt:
1781 return SelectIntExt(I);
1782 // Here add other flavors of Instruction::XXX that automated
1783 // cases don't catch. For example, switches are terminators
1784 // that aren't yet handled.
1791 // Materialize a floating-point constant into a register, and return
1792 // the register number (or zero if we failed to handle it).
1793 unsigned PPCFastISel::PPCMaterializeFP(const ConstantFP *CFP, MVT VT) {
1794 // No plans to handle long double here.
1795 if (VT != MVT::f32 && VT != MVT::f64)
1798 // All FP constants are loaded from the constant pool.
1799 unsigned Align = TD.getPrefTypeAlignment(CFP->getType());
1800 assert(Align > 0 && "Unexpectedly missing alignment information!");
1801 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
1802 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
1803 CodeModel::Model CModel = TM.getCodeModel();
1805 MachineMemOperand *MMO =
1806 FuncInfo.MF->getMachineMemOperand(
1807 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
1808 (VT == MVT::f32) ? 4 : 8, Align);
1810 unsigned Opc = (VT == MVT::f32) ? PPC::LFS : PPC::LFD;
1811 unsigned TmpReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1813 // For small code model, generate a LF[SD](0, LDtocCPT(Idx, X2)).
1814 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault) {
1815 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocCPT),
1817 .addConstantPoolIndex(Idx).addReg(PPC::X2);
1818 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1819 .addImm(0).addReg(TmpReg).addMemOperand(MMO);
1821 // Otherwise we generate LF[SD](Idx[lo], ADDIStocHA(X2, Idx)).
1822 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDIStocHA),
1823 TmpReg).addReg(PPC::X2).addConstantPoolIndex(Idx);
1824 // But for large code model, we must generate a LDtocL followed
1826 if (CModel == CodeModel::Large) {
1827 unsigned TmpReg2 = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1828 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocL),
1829 TmpReg2).addConstantPoolIndex(Idx).addReg(TmpReg);
1830 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1831 .addImm(0).addReg(TmpReg2);
1833 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1834 .addConstantPoolIndex(Idx, 0, PPCII::MO_TOC_LO)
1836 .addMemOperand(MMO);
1842 // Materialize the address of a global value into a register, and return
1843 // the register number (or zero if we failed to handle it).
1844 unsigned PPCFastISel::PPCMaterializeGV(const GlobalValue *GV, MVT VT) {
1845 assert(VT == MVT::i64 && "Non-address!");
1846 const TargetRegisterClass *RC = &PPC::G8RC_and_G8RC_NOX0RegClass;
1847 unsigned DestReg = createResultReg(RC);
1849 // Global values may be plain old object addresses, TLS object
1850 // addresses, constant pool entries, or jump tables. How we generate
1851 // code for these may depend on small, medium, or large code model.
1852 CodeModel::Model CModel = TM.getCodeModel();
1854 // FIXME: Jump tables are not yet required because fast-isel doesn't
1855 // handle switches; if that changes, we need them as well. For now,
1856 // what follows assumes everything's a generic (or TLS) global address.
1857 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1859 // If GV is an alias, use the aliasee for determining thread-locality.
1860 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1861 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
1864 // FIXME: We don't yet handle the complexity of TLS.
1865 bool IsTLS = GVar && GVar->isThreadLocal();
1869 // For small code model, generate a simple TOC load.
1870 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault)
1871 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtoc), DestReg)
1872 .addGlobalAddress(GV).addReg(PPC::X2);
1874 // If the address is an externally defined symbol, a symbol with
1875 // common or externally available linkage, a function address, or a
1876 // jump table address (not yet needed), or if we are generating code
1877 // for large code model, we generate:
1878 // LDtocL(GV, ADDIStocHA(%X2, GV))
1879 // Otherwise we generate:
1880 // ADDItocL(ADDIStocHA(%X2, GV), GV)
1881 // Either way, start with the ADDIStocHA:
1882 unsigned HighPartReg = createResultReg(RC);
1883 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDIStocHA),
1884 HighPartReg).addReg(PPC::X2).addGlobalAddress(GV);
1886 // !GVar implies a function address. An external variable is one
1887 // without an initializer.
1888 // If/when switches are implemented, jump tables should be handled
1889 // on the "if" path here.
1890 if (CModel == CodeModel::Large || !GVar || !GVar->hasInitializer() ||
1891 GVar->hasCommonLinkage() || GVar->hasAvailableExternallyLinkage())
1892 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocL),
1893 DestReg).addGlobalAddress(GV).addReg(HighPartReg);
1895 // Otherwise generate the ADDItocL.
1896 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDItocL),
1897 DestReg).addReg(HighPartReg).addGlobalAddress(GV);
1903 // Materialize a 32-bit integer constant into a register, and return
1904 // the register number (or zero if we failed to handle it).
1905 unsigned PPCFastISel::PPCMaterialize32BitInt(int64_t Imm,
1906 const TargetRegisterClass *RC) {
1907 unsigned Lo = Imm & 0xFFFF;
1908 unsigned Hi = (Imm >> 16) & 0xFFFF;
1910 unsigned ResultReg = createResultReg(RC);
1911 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1914 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1915 TII.get(IsGPRC ? PPC::LI : PPC::LI8), ResultReg)
1918 // Both Lo and Hi have nonzero bits.
1919 unsigned TmpReg = createResultReg(RC);
1920 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1921 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), TmpReg)
1923 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1924 TII.get(IsGPRC ? PPC::ORI : PPC::ORI8), ResultReg)
1925 .addReg(TmpReg).addImm(Lo);
1928 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1929 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), ResultReg)
1935 // Materialize a 64-bit integer constant into a register, and return
1936 // the register number (or zero if we failed to handle it).
1937 unsigned PPCFastISel::PPCMaterialize64BitInt(int64_t Imm,
1938 const TargetRegisterClass *RC) {
1939 unsigned Remainder = 0;
1942 // If the value doesn't fit in 32 bits, see if we can shift it
1943 // so that it fits in 32 bits.
1944 if (!isInt<32>(Imm)) {
1945 Shift = countTrailingZeros<uint64_t>(Imm);
1946 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
1948 if (isInt<32>(ImmSh))
1957 // Handle the high-order 32 bits (if shifted) or the whole 32 bits
1958 // (if not shifted).
1959 unsigned TmpReg1 = PPCMaterialize32BitInt(Imm, RC);
1963 // If upper 32 bits were not zero, we've built them and need to shift
1967 TmpReg2 = createResultReg(RC);
1968 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::RLDICR),
1969 TmpReg2).addReg(TmpReg1).addImm(Shift).addImm(63 - Shift);
1973 unsigned TmpReg3, Hi, Lo;
1974 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
1975 TmpReg3 = createResultReg(RC);
1976 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ORIS8),
1977 TmpReg3).addReg(TmpReg2).addImm(Hi);
1981 if ((Lo = Remainder & 0xFFFF)) {
1982 unsigned ResultReg = createResultReg(RC);
1983 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ORI8),
1984 ResultReg).addReg(TmpReg3).addImm(Lo);
1992 // Materialize an integer constant into a register, and return
1993 // the register number (or zero if we failed to handle it).
1994 unsigned PPCFastISel::PPCMaterializeInt(const Constant *C, MVT VT) {
1996 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
1997 VT != MVT::i8 && VT != MVT::i1)
2000 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2001 &PPC::GPRCRegClass);
2003 // If the constant is in range, use a load-immediate.
2004 const ConstantInt *CI = cast<ConstantInt>(C);
2005 if (isInt<16>(CI->getSExtValue())) {
2006 unsigned Opc = (VT == MVT::i64) ? PPC::LI8 : PPC::LI;
2007 unsigned ImmReg = createResultReg(RC);
2008 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ImmReg)
2009 .addImm(CI->getSExtValue());
2013 // Construct the constant piecewise.
2014 int64_t Imm = CI->getZExtValue();
2017 return PPCMaterialize64BitInt(Imm, RC);
2018 else if (VT == MVT::i32)
2019 return PPCMaterialize32BitInt(Imm, RC);
2024 // Materialize a constant into a register, and return the register
2025 // number (or zero if we failed to handle it).
2026 unsigned PPCFastISel::TargetMaterializeConstant(const Constant *C) {
2027 EVT CEVT = TLI.getValueType(C->getType(), true);
2029 // Only handle simple types.
2030 if (!CEVT.isSimple()) return 0;
2031 MVT VT = CEVT.getSimpleVT();
2033 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
2034 return PPCMaterializeFP(CFP, VT);
2035 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
2036 return PPCMaterializeGV(GV, VT);
2037 else if (isa<ConstantInt>(C))
2038 return PPCMaterializeInt(C, VT);
2043 // Materialize the address created by an alloca into a register, and
2044 // return the register number (or zero if we failed to handle it).
2045 unsigned PPCFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
2046 // Don't handle dynamic allocas.
2047 if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
2050 if (!isLoadTypeLegal(AI->getType(), VT)) return 0;
2052 DenseMap<const AllocaInst*, int>::iterator SI =
2053 FuncInfo.StaticAllocaMap.find(AI);
2055 if (SI != FuncInfo.StaticAllocaMap.end()) {
2056 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
2057 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDI8),
2058 ResultReg).addFrameIndex(SI->second).addImm(0);
2065 // Fold loads into extends when possible.
2066 // FIXME: We can have multiple redundant extend/trunc instructions
2067 // following a load. The folding only picks up one. Extend this
2068 // to check subsequent instructions for the same pattern and remove
2069 // them. Thus ResultReg should be the def reg for the last redundant
2070 // instruction in a chain, and all intervening instructions can be
2071 // removed from parent. Change test/CodeGen/PowerPC/fast-isel-fold.ll
2072 // to add ELF64-NOT: rldicl to the appropriate tests when this works.
2073 bool PPCFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2074 const LoadInst *LI) {
2075 // Verify we have a legal type before going any further.
2077 if (!isLoadTypeLegal(LI->getType(), VT))
2080 // Combine load followed by zero- or sign-extend.
2081 bool IsZExt = false;
2082 switch(MI->getOpcode()) {
2087 case PPC::RLDICL_32_64: {
2089 unsigned MB = MI->getOperand(3).getImm();
2090 if ((VT == MVT::i8 && MB <= 56) ||
2091 (VT == MVT::i16 && MB <= 48) ||
2092 (VT == MVT::i32 && MB <= 32))
2098 case PPC::RLWINM8: {
2100 unsigned MB = MI->getOperand(3).getImm();
2101 if ((VT == MVT::i8 && MB <= 24) ||
2102 (VT == MVT::i16 && MB <= 16))
2109 case PPC::EXTSB8_32_64:
2110 /* There is no sign-extending load-byte instruction. */
2115 case PPC::EXTSH8_32_64: {
2116 if (VT != MVT::i16 && VT != MVT::i8)
2122 case PPC::EXTSW_32_64: {
2123 if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8)
2129 // See if we can handle this address.
2131 if (!PPCComputeAddress(LI->getOperand(0), Addr))
2134 unsigned ResultReg = MI->getOperand(0).getReg();
2136 if (!PPCEmitLoad(VT, ResultReg, Addr, 0, IsZExt))
2139 MI->eraseFromParent();
2143 // Attempt to lower call arguments in a faster way than done by
2144 // the selection DAG code.
2145 bool PPCFastISel::FastLowerArguments() {
2146 // Defer to normal argument lowering for now. It's reasonably
2147 // efficient. Consider doing something like ARM to handle the
2148 // case where all args fit in registers, no varargs, no float
2153 // Handle materializing integer constants into a register. This is not
2154 // automatically generated for PowerPC, so must be explicitly created here.
2155 unsigned PPCFastISel::FastEmit_i(MVT Ty, MVT VT, unsigned Opc, uint64_t Imm) {
2157 if (Opc != ISD::Constant)
2160 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2161 VT != MVT::i8 && VT != MVT::i1)
2164 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2165 &PPC::GPRCRegClass);
2167 return PPCMaterialize64BitInt(Imm, RC);
2169 return PPCMaterialize32BitInt(Imm, RC);
2172 // Override for ADDI and ADDI8 to set the correct register class
2173 // on RHS operand 0. The automatic infrastructure naively assumes
2174 // GPRC for i32 and G8RC for i64; the concept of "no R0" is lost
2175 // for these cases. At the moment, none of the other automatically
2176 // generated RI instructions require special treatment. However, once
2177 // SelectSelect is implemented, "isel" requires similar handling.
2179 // Also be conservative about the output register class. Avoid
2180 // assigning R0 or X0 to the output register for GPRC and G8RC
2181 // register classes, as any such result could be used in ADDI, etc.,
2182 // where those regs have another meaning.
2183 unsigned PPCFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
2184 const TargetRegisterClass *RC,
2185 unsigned Op0, bool Op0IsKill,
2187 if (MachineInstOpcode == PPC::ADDI)
2188 MRI.setRegClass(Op0, &PPC::GPRC_and_GPRC_NOR0RegClass);
2189 else if (MachineInstOpcode == PPC::ADDI8)
2190 MRI.setRegClass(Op0, &PPC::G8RC_and_G8RC_NOX0RegClass);
2192 const TargetRegisterClass *UseRC =
2193 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2194 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2196 return FastISel::FastEmitInst_ri(MachineInstOpcode, UseRC,
2197 Op0, Op0IsKill, Imm);
2200 // Override for instructions with one register operand to avoid use of
2201 // R0/X0. The automatic infrastructure isn't aware of the context so
2202 // we must be conservative.
2203 unsigned PPCFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
2204 const TargetRegisterClass* RC,
2205 unsigned Op0, bool Op0IsKill) {
2206 const TargetRegisterClass *UseRC =
2207 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2208 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2210 return FastISel::FastEmitInst_r(MachineInstOpcode, UseRC, Op0, Op0IsKill);
2213 // Override for instructions with two register operands to avoid use
2214 // of R0/X0. The automatic infrastructure isn't aware of the context
2215 // so we must be conservative.
2216 unsigned PPCFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
2217 const TargetRegisterClass* RC,
2218 unsigned Op0, bool Op0IsKill,
2219 unsigned Op1, bool Op1IsKill) {
2220 const TargetRegisterClass *UseRC =
2221 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2222 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2224 return FastISel::FastEmitInst_rr(MachineInstOpcode, UseRC, Op0, Op0IsKill,
2229 // Create the fast instruction selector for PowerPC64 ELF.
2230 FastISel *PPC::createFastISel(FunctionLoweringInfo &FuncInfo,
2231 const TargetLibraryInfo *LibInfo) {
2232 const TargetMachine &TM = FuncInfo.MF->getTarget();
2234 // Only available on 64-bit ELF for now.
2235 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
2236 if (Subtarget->isPPC64() && Subtarget->isSVR4ABI())
2237 return new PPCFastISel(FuncInfo, LibInfo);