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 (canFoldAddIntoGEP(U, Op)) {
340 // A compatible add with a constant operand. Fold the constant.
342 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
343 TmpOffset += CI->getSExtValue() * S;
344 // Iterate on the other operand.
345 Op = cast<AddOperator>(Op)->getOperand(0);
349 goto unsupported_gep;
354 // Try to grab the base operand now.
355 Addr.Offset = TmpOffset;
356 if (PPCComputeAddress(U->getOperand(0), Addr)) return true;
358 // We failed, restore everything and try the other options.
364 case Instruction::Alloca: {
365 const AllocaInst *AI = cast<AllocaInst>(Obj);
366 DenseMap<const AllocaInst*, int>::iterator SI =
367 FuncInfo.StaticAllocaMap.find(AI);
368 if (SI != FuncInfo.StaticAllocaMap.end()) {
369 Addr.BaseType = Address::FrameIndexBase;
370 Addr.Base.FI = SI->second;
377 // FIXME: References to parameters fall through to the behavior
378 // below. They should be able to reference a frame index since
379 // they are stored to the stack, so we can get "ld rx, offset(r1)"
380 // instead of "addi ry, r1, offset / ld rx, 0(ry)". Obj will
381 // just contain the parameter. Try to handle this with a FI.
383 // Try to get this in a register if nothing else has worked.
384 if (Addr.Base.Reg == 0)
385 Addr.Base.Reg = getRegForValue(Obj);
387 // Prevent assignment of base register to X0, which is inappropriate
388 // for loads and stores alike.
389 if (Addr.Base.Reg != 0)
390 MRI.setRegClass(Addr.Base.Reg, &PPC::G8RC_and_G8RC_NOX0RegClass);
392 return Addr.Base.Reg != 0;
395 // Fix up some addresses that can't be used directly. For example, if
396 // an offset won't fit in an instruction field, we may need to move it
397 // into an index register.
398 void PPCFastISel::PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
399 unsigned &IndexReg) {
401 // Check whether the offset fits in the instruction field.
402 if (!isInt<16>(Addr.Offset))
405 // If this is a stack pointer and the offset needs to be simplified then
406 // put the alloca address into a register, set the base type back to
407 // register and continue. This should almost never happen.
408 if (!UseOffset && Addr.BaseType == Address::FrameIndexBase) {
409 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
410 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDI8),
411 ResultReg).addFrameIndex(Addr.Base.FI).addImm(0);
412 Addr.Base.Reg = ResultReg;
413 Addr.BaseType = Address::RegBase;
417 IntegerType *OffsetTy = ((VT == MVT::i32) ? Type::getInt32Ty(*Context)
418 : Type::getInt64Ty(*Context));
419 const ConstantInt *Offset =
420 ConstantInt::getSigned(OffsetTy, (int64_t)(Addr.Offset));
421 IndexReg = PPCMaterializeInt(Offset, MVT::i64);
422 assert(IndexReg && "Unexpected error in PPCMaterializeInt!");
426 // Emit a load instruction if possible, returning true if we succeeded,
427 // otherwise false. See commentary below for how the register class of
428 // the load is determined.
429 bool PPCFastISel::PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
430 const TargetRegisterClass *RC,
431 bool IsZExt, unsigned FP64LoadOpc) {
433 bool UseOffset = true;
435 // If ResultReg is given, it determines the register class of the load.
436 // Otherwise, RC is the register class to use. If the result of the
437 // load isn't anticipated in this block, both may be zero, in which
438 // case we must make a conservative guess. In particular, don't assign
439 // R0 or X0 to the result register, as the result may be used in a load,
440 // store, add-immediate, or isel that won't permit this. (Though
441 // perhaps the spill and reload of live-exit values would handle this?)
442 const TargetRegisterClass *UseRC =
443 (ResultReg ? MRI.getRegClass(ResultReg) :
445 (VT == MVT::f64 ? &PPC::F8RCRegClass :
446 (VT == MVT::f32 ? &PPC::F4RCRegClass :
447 (VT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
448 &PPC::GPRC_and_GPRC_NOR0RegClass)))));
450 bool Is32BitInt = UseRC->hasSuperClassEq(&PPC::GPRCRegClass);
452 switch (VT.SimpleTy) {
453 default: // e.g., vector types not handled
456 Opc = Is32BitInt ? PPC::LBZ : PPC::LBZ8;
460 (Is32BitInt ? PPC::LHZ : PPC::LHZ8) :
461 (Is32BitInt ? PPC::LHA : PPC::LHA8));
465 (Is32BitInt ? PPC::LWZ : PPC::LWZ8) :
466 (Is32BitInt ? PPC::LWA_32 : PPC::LWA));
467 if ((Opc == PPC::LWA || Opc == PPC::LWA_32) && ((Addr.Offset & 3) != 0))
472 assert(UseRC->hasSuperClassEq(&PPC::G8RCRegClass) &&
473 "64-bit load with 32-bit target??");
474 UseOffset = ((Addr.Offset & 3) == 0);
484 // If necessary, materialize the offset into a register and use
485 // the indexed form. Also handle stack pointers with special needs.
486 unsigned IndexReg = 0;
487 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
489 ResultReg = createResultReg(UseRC);
491 // Note: If we still have a frame index here, we know the offset is
492 // in range, as otherwise PPCSimplifyAddress would have converted it
494 if (Addr.BaseType == Address::FrameIndexBase) {
496 MachineMemOperand *MMO =
497 FuncInfo.MF->getMachineMemOperand(
498 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
499 MachineMemOperand::MOLoad, MFI.getObjectSize(Addr.Base.FI),
500 MFI.getObjectAlignment(Addr.Base.FI));
502 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
503 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
505 // Base reg with offset in range.
506 } else if (UseOffset) {
508 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
509 .addImm(Addr.Offset).addReg(Addr.Base.Reg);
513 // Get the RR opcode corresponding to the RI one. FIXME: It would be
514 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
515 // is hard to get at.
517 default: llvm_unreachable("Unexpected opcode!");
518 case PPC::LBZ: Opc = PPC::LBZX; break;
519 case PPC::LBZ8: Opc = PPC::LBZX8; break;
520 case PPC::LHZ: Opc = PPC::LHZX; break;
521 case PPC::LHZ8: Opc = PPC::LHZX8; break;
522 case PPC::LHA: Opc = PPC::LHAX; break;
523 case PPC::LHA8: Opc = PPC::LHAX8; break;
524 case PPC::LWZ: Opc = PPC::LWZX; break;
525 case PPC::LWZ8: Opc = PPC::LWZX8; break;
526 case PPC::LWA: Opc = PPC::LWAX; break;
527 case PPC::LWA_32: Opc = PPC::LWAX_32; break;
528 case PPC::LD: Opc = PPC::LDX; break;
529 case PPC::LFS: Opc = PPC::LFSX; break;
530 case PPC::LFD: Opc = PPC::LFDX; break;
532 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
533 .addReg(Addr.Base.Reg).addReg(IndexReg);
539 // Attempt to fast-select a load instruction.
540 bool PPCFastISel::SelectLoad(const Instruction *I) {
541 // FIXME: No atomic loads are supported.
542 if (cast<LoadInst>(I)->isAtomic())
545 // Verify we have a legal type before going any further.
547 if (!isLoadTypeLegal(I->getType(), VT))
550 // See if we can handle this address.
552 if (!PPCComputeAddress(I->getOperand(0), Addr))
555 // Look at the currently assigned register for this instruction
556 // to determine the required register class. This is necessary
557 // to constrain RA from using R0/X0 when this is not legal.
558 unsigned AssignedReg = FuncInfo.ValueMap[I];
559 const TargetRegisterClass *RC =
560 AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
562 unsigned ResultReg = 0;
563 if (!PPCEmitLoad(VT, ResultReg, Addr, RC))
565 UpdateValueMap(I, ResultReg);
569 // Emit a store instruction to store SrcReg at Addr.
570 bool PPCFastISel::PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr) {
571 assert(SrcReg && "Nothing to store!");
573 bool UseOffset = true;
575 const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
576 bool Is32BitInt = RC->hasSuperClassEq(&PPC::GPRCRegClass);
578 switch (VT.SimpleTy) {
579 default: // e.g., vector types not handled
582 Opc = Is32BitInt ? PPC::STB : PPC::STB8;
585 Opc = Is32BitInt ? PPC::STH : PPC::STH8;
588 assert(Is32BitInt && "Not GPRC for i32??");
593 UseOffset = ((Addr.Offset & 3) == 0);
603 // If necessary, materialize the offset into a register and use
604 // the indexed form. Also handle stack pointers with special needs.
605 unsigned IndexReg = 0;
606 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
608 // Note: If we still have a frame index here, we know the offset is
609 // in range, as otherwise PPCSimplifyAddress would have converted it
611 if (Addr.BaseType == Address::FrameIndexBase) {
612 MachineMemOperand *MMO =
613 FuncInfo.MF->getMachineMemOperand(
614 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
615 MachineMemOperand::MOStore, MFI.getObjectSize(Addr.Base.FI),
616 MFI.getObjectAlignment(Addr.Base.FI));
618 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc)).addReg(SrcReg)
619 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
621 // Base reg with offset in range.
622 } else if (UseOffset)
623 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
624 .addReg(SrcReg).addImm(Addr.Offset).addReg(Addr.Base.Reg);
628 // Get the RR opcode corresponding to the RI one. FIXME: It would be
629 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
630 // is hard to get at.
632 default: llvm_unreachable("Unexpected opcode!");
633 case PPC::STB: Opc = PPC::STBX; break;
634 case PPC::STH : Opc = PPC::STHX; break;
635 case PPC::STW : Opc = PPC::STWX; break;
636 case PPC::STB8: Opc = PPC::STBX8; break;
637 case PPC::STH8: Opc = PPC::STHX8; break;
638 case PPC::STW8: Opc = PPC::STWX8; break;
639 case PPC::STD: Opc = PPC::STDX; break;
640 case PPC::STFS: Opc = PPC::STFSX; break;
641 case PPC::STFD: Opc = PPC::STFDX; break;
643 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
644 .addReg(SrcReg).addReg(Addr.Base.Reg).addReg(IndexReg);
650 // Attempt to fast-select a store instruction.
651 bool PPCFastISel::SelectStore(const Instruction *I) {
652 Value *Op0 = I->getOperand(0);
655 // FIXME: No atomics loads are supported.
656 if (cast<StoreInst>(I)->isAtomic())
659 // Verify we have a legal type before going any further.
661 if (!isLoadTypeLegal(Op0->getType(), VT))
664 // Get the value to be stored into a register.
665 SrcReg = getRegForValue(Op0);
669 // See if we can handle this address.
671 if (!PPCComputeAddress(I->getOperand(1), Addr))
674 if (!PPCEmitStore(VT, SrcReg, Addr))
680 // Attempt to fast-select a branch instruction.
681 bool PPCFastISel::SelectBranch(const Instruction *I) {
682 const BranchInst *BI = cast<BranchInst>(I);
683 MachineBasicBlock *BrBB = FuncInfo.MBB;
684 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
685 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
687 // For now, just try the simplest case where it's fed by a compare.
688 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
689 Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
693 PPC::Predicate PPCPred = OptPPCPred.getValue();
695 // Take advantage of fall-through opportunities.
696 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
698 PPCPred = PPC::InvertPredicate(PPCPred);
701 unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
703 if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
707 BuildMI(*BrBB, FuncInfo.InsertPt, DL, TII.get(PPC::BCC))
708 .addImm(PPCPred).addReg(CondReg).addMBB(TBB);
709 FastEmitBranch(FBB, DL);
710 FuncInfo.MBB->addSuccessor(TBB);
713 } else if (const ConstantInt *CI =
714 dyn_cast<ConstantInt>(BI->getCondition())) {
715 uint64_t Imm = CI->getZExtValue();
716 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
717 FastEmitBranch(Target, DL);
721 // FIXME: ARM looks for a case where the block containing the compare
722 // has been split from the block containing the branch. If this happens,
723 // there is a vreg available containing the result of the compare. I'm
724 // not sure we can do much, as we've lost the predicate information with
725 // the compare instruction -- we have a 4-bit CR but don't know which bit
730 // Attempt to emit a compare of the two source values. Signed and unsigned
731 // comparisons are supported. Return false if we can't handle it.
732 bool PPCFastISel::PPCEmitCmp(const Value *SrcValue1, const Value *SrcValue2,
733 bool IsZExt, unsigned DestReg) {
734 Type *Ty = SrcValue1->getType();
735 EVT SrcEVT = TLI.getValueType(Ty, true);
736 if (!SrcEVT.isSimple())
738 MVT SrcVT = SrcEVT.getSimpleVT();
740 // See if operand 2 is an immediate encodeable in the compare.
741 // FIXME: Operands are not in canonical order at -O0, so an immediate
742 // operand in position 1 is a lost opportunity for now. We are
743 // similar to ARM in this regard.
747 // Only 16-bit integer constants can be represented in compares for
748 // PowerPC. Others will be materialized into a register.
749 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(SrcValue2)) {
750 if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
751 SrcVT == MVT::i8 || SrcVT == MVT::i1) {
752 const APInt &CIVal = ConstInt->getValue();
753 Imm = (IsZExt) ? (long)CIVal.getZExtValue() : (long)CIVal.getSExtValue();
754 if ((IsZExt && isUInt<16>(Imm)) || (!IsZExt && isInt<16>(Imm)))
760 bool NeedsExt = false;
761 switch (SrcVT.SimpleTy) {
762 default: return false;
764 CmpOpc = PPC::FCMPUS;
767 CmpOpc = PPC::FCMPUD;
773 // Intentional fall-through.
776 CmpOpc = IsZExt ? PPC::CMPLW : PPC::CMPW;
778 CmpOpc = IsZExt ? PPC::CMPLWI : PPC::CMPWI;
782 CmpOpc = IsZExt ? PPC::CMPLD : PPC::CMPD;
784 CmpOpc = IsZExt ? PPC::CMPLDI : PPC::CMPDI;
788 unsigned SrcReg1 = getRegForValue(SrcValue1);
792 unsigned SrcReg2 = 0;
794 SrcReg2 = getRegForValue(SrcValue2);
800 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
801 if (!PPCEmitIntExt(SrcVT, SrcReg1, MVT::i32, ExtReg, IsZExt))
806 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
807 if (!PPCEmitIntExt(SrcVT, SrcReg2, MVT::i32, ExtReg, IsZExt))
814 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc), DestReg)
815 .addReg(SrcReg1).addReg(SrcReg2);
817 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc), DestReg)
818 .addReg(SrcReg1).addImm(Imm);
823 // Attempt to fast-select a floating-point extend instruction.
824 bool PPCFastISel::SelectFPExt(const Instruction *I) {
825 Value *Src = I->getOperand(0);
826 EVT SrcVT = TLI.getValueType(Src->getType(), true);
827 EVT DestVT = TLI.getValueType(I->getType(), true);
829 if (SrcVT != MVT::f32 || DestVT != MVT::f64)
832 unsigned SrcReg = getRegForValue(Src);
836 // No code is generated for a FP extend.
837 UpdateValueMap(I, SrcReg);
841 // Attempt to fast-select a floating-point truncate instruction.
842 bool PPCFastISel::SelectFPTrunc(const Instruction *I) {
843 Value *Src = I->getOperand(0);
844 EVT SrcVT = TLI.getValueType(Src->getType(), true);
845 EVT DestVT = TLI.getValueType(I->getType(), true);
847 if (SrcVT != MVT::f64 || DestVT != MVT::f32)
850 unsigned SrcReg = getRegForValue(Src);
854 // Round the result to single precision.
855 unsigned DestReg = createResultReg(&PPC::F4RCRegClass);
856 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::FRSP), DestReg)
859 UpdateValueMap(I, DestReg);
863 // Move an i32 or i64 value in a GPR to an f64 value in an FPR.
864 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
865 // those should be used instead of moving via a stack slot when the
866 // subtarget permits.
867 // FIXME: The code here is sloppy for the 4-byte case. Can use a 4-byte
868 // stack slot and 4-byte store/load sequence. Or just sext the 4-byte
869 // case to 8 bytes which produces tighter code but wastes stack space.
870 unsigned PPCFastISel::PPCMoveToFPReg(MVT SrcVT, unsigned SrcReg,
873 // If necessary, extend 32-bit int to 64-bit.
874 if (SrcVT == MVT::i32) {
875 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
876 if (!PPCEmitIntExt(MVT::i32, SrcReg, MVT::i64, TmpReg, !IsSigned))
881 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
883 Addr.BaseType = Address::FrameIndexBase;
884 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
886 // Store the value from the GPR.
887 if (!PPCEmitStore(MVT::i64, SrcReg, Addr))
890 // Load the integer value into an FPR. The kind of load used depends
891 // on a number of conditions.
892 unsigned LoadOpc = PPC::LFD;
894 if (SrcVT == MVT::i32) {
896 LoadOpc = PPC::LFIWZX;
898 } else if (PPCSubTarget.hasLFIWAX()) {
899 LoadOpc = PPC::LFIWAX;
904 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
905 unsigned ResultReg = 0;
906 if (!PPCEmitLoad(MVT::f64, ResultReg, Addr, RC, !IsSigned, LoadOpc))
912 // Attempt to fast-select an integer-to-floating-point conversion.
913 bool PPCFastISel::SelectIToFP(const Instruction *I, bool IsSigned) {
915 Type *DstTy = I->getType();
916 if (!isTypeLegal(DstTy, DstVT))
919 if (DstVT != MVT::f32 && DstVT != MVT::f64)
922 Value *Src = I->getOperand(0);
923 EVT SrcEVT = TLI.getValueType(Src->getType(), true);
924 if (!SrcEVT.isSimple())
927 MVT SrcVT = SrcEVT.getSimpleVT();
929 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 &&
930 SrcVT != MVT::i32 && SrcVT != MVT::i64)
933 unsigned SrcReg = getRegForValue(Src);
937 // We can only lower an unsigned convert if we have the newer
938 // floating-point conversion operations.
939 if (!IsSigned && !PPCSubTarget.hasFPCVT())
942 // FIXME: For now we require the newer floating-point conversion operations
943 // (which are present only on P7 and A2 server models) when converting
944 // to single-precision float. Otherwise we have to generate a lot of
945 // fiddly code to avoid double rounding. If necessary, the fiddly code
946 // can be found in PPCTargetLowering::LowerINT_TO_FP().
947 if (DstVT == MVT::f32 && !PPCSubTarget.hasFPCVT())
950 // Extend the input if necessary.
951 if (SrcVT == MVT::i8 || SrcVT == MVT::i16) {
952 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
953 if (!PPCEmitIntExt(SrcVT, SrcReg, MVT::i64, TmpReg, !IsSigned))
959 // Move the integer value to an FPR.
960 unsigned FPReg = PPCMoveToFPReg(SrcVT, SrcReg, IsSigned);
964 // Determine the opcode for the conversion.
965 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
966 unsigned DestReg = createResultReg(RC);
969 if (DstVT == MVT::f32)
970 Opc = IsSigned ? PPC::FCFIDS : PPC::FCFIDUS;
972 Opc = IsSigned ? PPC::FCFID : PPC::FCFIDU;
974 // Generate the convert.
975 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
978 UpdateValueMap(I, DestReg);
982 // Move the floating-point value in SrcReg into an integer destination
983 // register, and return the register (or zero if we can't handle it).
984 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
985 // those should be used instead of moving via a stack slot when the
986 // subtarget permits.
987 unsigned PPCFastISel::PPCMoveToIntReg(const Instruction *I, MVT VT,
988 unsigned SrcReg, bool IsSigned) {
989 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
990 // Note that if have STFIWX available, we could use a 4-byte stack
991 // slot for i32, but this being fast-isel we'll just go with the
992 // easiest code gen possible.
994 Addr.BaseType = Address::FrameIndexBase;
995 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
997 // Store the value from the FPR.
998 if (!PPCEmitStore(MVT::f64, SrcReg, Addr))
1001 // Reload it into a GPR. If we want an i32, modify the address
1002 // to have a 4-byte offset so we load from the right place.
1006 // Look at the currently assigned register for this instruction
1007 // to determine the required register class.
1008 unsigned AssignedReg = FuncInfo.ValueMap[I];
1009 const TargetRegisterClass *RC =
1010 AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
1012 unsigned ResultReg = 0;
1013 if (!PPCEmitLoad(VT, ResultReg, Addr, RC, !IsSigned))
1019 // Attempt to fast-select a floating-point-to-integer conversion.
1020 bool PPCFastISel::SelectFPToI(const Instruction *I, bool IsSigned) {
1022 Type *DstTy = I->getType();
1023 if (!isTypeLegal(DstTy, DstVT))
1026 if (DstVT != MVT::i32 && DstVT != MVT::i64)
1029 Value *Src = I->getOperand(0);
1030 Type *SrcTy = Src->getType();
1031 if (!isTypeLegal(SrcTy, SrcVT))
1034 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
1037 unsigned SrcReg = getRegForValue(Src);
1041 // Convert f32 to f64 if necessary. This is just a meaningless copy
1042 // to get the register class right. COPY_TO_REGCLASS is needed since
1043 // a COPY from F4RC to F8RC is converted to a F4RC-F4RC copy downstream.
1044 const TargetRegisterClass *InRC = MRI.getRegClass(SrcReg);
1045 if (InRC == &PPC::F4RCRegClass) {
1046 unsigned TmpReg = createResultReg(&PPC::F8RCRegClass);
1047 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1048 TII.get(TargetOpcode::COPY_TO_REGCLASS), TmpReg)
1049 .addReg(SrcReg).addImm(PPC::F8RCRegClassID);
1053 // Determine the opcode for the conversion, which takes place
1054 // entirely within FPRs.
1055 unsigned DestReg = createResultReg(&PPC::F8RCRegClass);
1058 if (DstVT == MVT::i32)
1062 Opc = PPCSubTarget.hasFPCVT() ? PPC::FCTIWUZ : PPC::FCTIDZ;
1064 Opc = IsSigned ? PPC::FCTIDZ : PPC::FCTIDUZ;
1066 // Generate the convert.
1067 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1070 // Now move the integer value from a float register to an integer register.
1071 unsigned IntReg = PPCMoveToIntReg(I, DstVT, DestReg, IsSigned);
1075 UpdateValueMap(I, IntReg);
1079 // Attempt to fast-select a binary integer operation that isn't already
1080 // handled automatically.
1081 bool PPCFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1082 EVT DestVT = TLI.getValueType(I->getType(), true);
1084 // We can get here in the case when we have a binary operation on a non-legal
1085 // type and the target independent selector doesn't know how to handle it.
1086 if (DestVT != MVT::i16 && DestVT != MVT::i8)
1089 // Look at the currently assigned register for this instruction
1090 // to determine the required register class. If there is no register,
1091 // make a conservative choice (don't assign R0).
1092 unsigned AssignedReg = FuncInfo.ValueMap[I];
1093 const TargetRegisterClass *RC =
1094 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1095 &PPC::GPRC_and_GPRC_NOR0RegClass);
1096 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1099 switch (ISDOpcode) {
1100 default: return false;
1102 Opc = IsGPRC ? PPC::ADD4 : PPC::ADD8;
1105 Opc = IsGPRC ? PPC::OR : PPC::OR8;
1108 Opc = IsGPRC ? PPC::SUBF : PPC::SUBF8;
1112 unsigned ResultReg = createResultReg(RC ? RC : &PPC::G8RCRegClass);
1113 unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1114 if (SrcReg1 == 0) return false;
1116 // Handle case of small immediate operand.
1117 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(1))) {
1118 const APInt &CIVal = ConstInt->getValue();
1119 int Imm = (int)CIVal.getSExtValue();
1121 if (isInt<16>(Imm)) {
1124 llvm_unreachable("Missing case!");
1127 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1131 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1144 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1153 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1160 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1161 .addReg(SrcReg1).addImm(Imm);
1162 UpdateValueMap(I, ResultReg);
1169 unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1170 if (SrcReg2 == 0) return false;
1172 // Reverse operands for subtract-from.
1173 if (ISDOpcode == ISD::SUB)
1174 std::swap(SrcReg1, SrcReg2);
1176 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1177 .addReg(SrcReg1).addReg(SrcReg2);
1178 UpdateValueMap(I, ResultReg);
1182 // Handle arguments to a call that we're attempting to fast-select.
1183 // Return false if the arguments are too complex for us at the moment.
1184 bool PPCFastISel::processCallArgs(SmallVectorImpl<Value*> &Args,
1185 SmallVectorImpl<unsigned> &ArgRegs,
1186 SmallVectorImpl<MVT> &ArgVTs,
1187 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1188 SmallVectorImpl<unsigned> &RegArgs,
1192 SmallVector<CCValAssign, 16> ArgLocs;
1193 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, ArgLocs, *Context);
1194 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_PPC64_ELF_FIS);
1196 // Bail out if we can't handle any of the arguments.
1197 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1198 CCValAssign &VA = ArgLocs[I];
1199 MVT ArgVT = ArgVTs[VA.getValNo()];
1201 // Skip vector arguments for now, as well as long double and
1202 // uint128_t, and anything that isn't passed in a register.
1203 if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64 ||
1204 !VA.isRegLoc() || VA.needsCustom())
1207 // Skip bit-converted arguments for now.
1208 if (VA.getLocInfo() == CCValAssign::BCvt)
1212 // Get a count of how many bytes are to be pushed onto the stack.
1213 NumBytes = CCInfo.getNextStackOffset();
1215 // Issue CALLSEQ_START.
1216 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1217 TII.get(TII.getCallFrameSetupOpcode()))
1220 // Prepare to assign register arguments. Every argument uses up a
1221 // GPR protocol register even if it's passed in a floating-point
1223 unsigned NextGPR = PPC::X3;
1224 unsigned NextFPR = PPC::F1;
1226 // Process arguments.
1227 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1228 CCValAssign &VA = ArgLocs[I];
1229 unsigned Arg = ArgRegs[VA.getValNo()];
1230 MVT ArgVT = ArgVTs[VA.getValNo()];
1232 // Handle argument promotion and bitcasts.
1233 switch (VA.getLocInfo()) {
1235 llvm_unreachable("Unknown loc info!");
1236 case CCValAssign::Full:
1238 case CCValAssign::SExt: {
1239 MVT DestVT = VA.getLocVT();
1240 const TargetRegisterClass *RC =
1241 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1242 unsigned TmpReg = createResultReg(RC);
1243 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/false))
1244 llvm_unreachable("Failed to emit a sext!");
1249 case CCValAssign::AExt:
1250 case CCValAssign::ZExt: {
1251 MVT DestVT = VA.getLocVT();
1252 const TargetRegisterClass *RC =
1253 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1254 unsigned TmpReg = createResultReg(RC);
1255 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/true))
1256 llvm_unreachable("Failed to emit a zext!");
1261 case CCValAssign::BCvt: {
1262 // FIXME: Not yet handled.
1263 llvm_unreachable("Should have bailed before getting here!");
1268 // Copy this argument to the appropriate register.
1270 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) {
1276 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1277 ArgReg).addReg(Arg);
1278 RegArgs.push_back(ArgReg);
1284 // For a call that we've determined we can fast-select, finish the
1285 // call sequence and generate a copy to obtain the return value (if any).
1286 void PPCFastISel::finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1287 const Instruction *I, CallingConv::ID CC,
1288 unsigned &NumBytes, bool IsVarArg) {
1289 // Issue CallSEQ_END.
1290 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1291 TII.get(TII.getCallFrameDestroyOpcode()))
1292 .addImm(NumBytes).addImm(0);
1294 // Next, generate a copy to obtain the return value.
1295 // FIXME: No multi-register return values yet, though I don't foresee
1296 // any real difficulties there.
1297 if (RetVT != MVT::isVoid) {
1298 SmallVector<CCValAssign, 16> RVLocs;
1299 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
1300 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1301 CCValAssign &VA = RVLocs[0];
1302 assert(RVLocs.size() == 1 && "No support for multi-reg return values!");
1303 assert(VA.isRegLoc() && "Can only return in registers!");
1305 MVT DestVT = VA.getValVT();
1306 MVT CopyVT = DestVT;
1308 // Ints smaller than a register still arrive in a full 64-bit
1309 // register, so make sure we recognize this.
1310 if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32)
1313 unsigned SourcePhysReg = VA.getLocReg();
1314 unsigned ResultReg = 0;
1316 if (RetVT == CopyVT) {
1317 const TargetRegisterClass *CpyRC = TLI.getRegClassFor(CopyVT);
1318 ResultReg = createResultReg(CpyRC);
1320 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1321 TII.get(TargetOpcode::COPY), ResultReg)
1322 .addReg(SourcePhysReg);
1324 // If necessary, round the floating result to single precision.
1325 } else if (CopyVT == MVT::f64) {
1326 ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1327 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::FRSP),
1328 ResultReg).addReg(SourcePhysReg);
1330 // If only the low half of a general register is needed, generate
1331 // a GPRC copy instead of a G8RC copy. (EXTRACT_SUBREG can't be
1332 // used along the fast-isel path (not lowered), and downstream logic
1333 // also doesn't like a direct subreg copy on a physical reg.)
1334 } else if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32) {
1335 ResultReg = createResultReg(&PPC::GPRCRegClass);
1336 // Convert physical register from G8RC to GPRC.
1337 SourcePhysReg -= PPC::X0 - PPC::R0;
1338 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1339 TII.get(TargetOpcode::COPY), ResultReg)
1340 .addReg(SourcePhysReg);
1343 assert(ResultReg && "ResultReg unset!");
1344 UsedRegs.push_back(SourcePhysReg);
1345 UpdateValueMap(I, ResultReg);
1349 // Attempt to fast-select a call instruction.
1350 bool PPCFastISel::SelectCall(const Instruction *I) {
1351 const CallInst *CI = cast<CallInst>(I);
1352 const Value *Callee = CI->getCalledValue();
1354 // Can't handle inline asm.
1355 if (isa<InlineAsm>(Callee))
1358 // Allow SelectionDAG isel to handle tail calls.
1359 if (CI->isTailCall())
1362 // Obtain calling convention.
1363 ImmutableCallSite CS(CI);
1364 CallingConv::ID CC = CS.getCallingConv();
1366 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1367 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1368 bool IsVarArg = FTy->isVarArg();
1370 // Not ready for varargs yet.
1374 // Handle simple calls for now, with legal return types and
1375 // those that can be extended.
1376 Type *RetTy = I->getType();
1378 if (RetTy->isVoidTy())
1379 RetVT = MVT::isVoid;
1380 else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
1384 // FIXME: No multi-register return values yet.
1385 if (RetVT != MVT::isVoid && RetVT != MVT::i8 && RetVT != MVT::i16 &&
1386 RetVT != MVT::i32 && RetVT != MVT::i64 && RetVT != MVT::f32 &&
1387 RetVT != MVT::f64) {
1388 SmallVector<CCValAssign, 16> RVLocs;
1389 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
1390 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1391 if (RVLocs.size() > 1)
1395 // Bail early if more than 8 arguments, as we only currently
1396 // handle arguments passed in registers.
1397 unsigned NumArgs = CS.arg_size();
1401 // Set up the argument vectors.
1402 SmallVector<Value*, 8> Args;
1403 SmallVector<unsigned, 8> ArgRegs;
1404 SmallVector<MVT, 8> ArgVTs;
1405 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1407 Args.reserve(NumArgs);
1408 ArgRegs.reserve(NumArgs);
1409 ArgVTs.reserve(NumArgs);
1410 ArgFlags.reserve(NumArgs);
1412 for (ImmutableCallSite::arg_iterator II = CS.arg_begin(), IE = CS.arg_end();
1414 // FIXME: ARM does something for intrinsic calls here, check into that.
1416 unsigned AttrIdx = II - CS.arg_begin() + 1;
1418 // Only handle easy calls for now. It would be reasonably easy
1419 // to handle <= 8-byte structures passed ByVal in registers, but we
1420 // have to ensure they are right-justified in the register.
1421 if (CS.paramHasAttr(AttrIdx, Attribute::InReg) ||
1422 CS.paramHasAttr(AttrIdx, Attribute::StructRet) ||
1423 CS.paramHasAttr(AttrIdx, Attribute::Nest) ||
1424 CS.paramHasAttr(AttrIdx, Attribute::ByVal))
1427 ISD::ArgFlagsTy Flags;
1428 if (CS.paramHasAttr(AttrIdx, Attribute::SExt))
1430 if (CS.paramHasAttr(AttrIdx, Attribute::ZExt))
1433 Type *ArgTy = (*II)->getType();
1435 if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8)
1438 if (ArgVT.isVector())
1441 unsigned Arg = getRegForValue(*II);
1445 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1446 Flags.setOrigAlign(OriginalAlignment);
1448 Args.push_back(*II);
1449 ArgRegs.push_back(Arg);
1450 ArgVTs.push_back(ArgVT);
1451 ArgFlags.push_back(Flags);
1454 // Process the arguments.
1455 SmallVector<unsigned, 8> RegArgs;
1458 if (!processCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
1459 RegArgs, CC, NumBytes, IsVarArg))
1462 // FIXME: No handling for function pointers yet. This requires
1463 // implementing the function descriptor (OPD) setup.
1464 const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1468 // Build direct call with NOP for TOC restore.
1469 // FIXME: We can and should optimize away the NOP for local calls.
1470 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1471 TII.get(PPC::BL8_NOP));
1473 MIB.addGlobalAddress(GV);
1475 // Add implicit physical register uses to the call.
1476 for (unsigned II = 0, IE = RegArgs.size(); II != IE; ++II)
1477 MIB.addReg(RegArgs[II], RegState::Implicit);
1479 // Add a register mask with the call-preserved registers. Proper
1480 // defs for return values will be added by setPhysRegsDeadExcept().
1481 MIB.addRegMask(TRI.getCallPreservedMask(CC));
1483 // Finish off the call including any return values.
1484 SmallVector<unsigned, 4> UsedRegs;
1485 finishCall(RetVT, UsedRegs, I, CC, NumBytes, IsVarArg);
1487 // Set all unused physregs defs as dead.
1488 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1493 // Attempt to fast-select a return instruction.
1494 bool PPCFastISel::SelectRet(const Instruction *I) {
1496 if (!FuncInfo.CanLowerReturn)
1499 const ReturnInst *Ret = cast<ReturnInst>(I);
1500 const Function &F = *I->getParent()->getParent();
1502 // Build a list of return value registers.
1503 SmallVector<unsigned, 4> RetRegs;
1504 CallingConv::ID CC = F.getCallingConv();
1506 if (Ret->getNumOperands() > 0) {
1507 SmallVector<ISD::OutputArg, 4> Outs;
1508 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1510 // Analyze operands of the call, assigning locations to each operand.
1511 SmallVector<CCValAssign, 16> ValLocs;
1512 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs, *Context);
1513 CCInfo.AnalyzeReturn(Outs, RetCC_PPC64_ELF_FIS);
1514 const Value *RV = Ret->getOperand(0);
1516 // FIXME: Only one output register for now.
1517 if (ValLocs.size() > 1)
1520 // Special case for returning a constant integer of any size.
1521 // Materialize the constant as an i64 and copy it to the return
1522 // register. This avoids an unnecessary extend or truncate.
1523 if (isa<ConstantInt>(*RV)) {
1524 const Constant *C = cast<Constant>(RV);
1525 unsigned SrcReg = PPCMaterializeInt(C, MVT::i64);
1526 unsigned RetReg = ValLocs[0].getLocReg();
1527 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1528 RetReg).addReg(SrcReg);
1529 RetRegs.push_back(RetReg);
1532 unsigned Reg = getRegForValue(RV);
1537 // Copy the result values into the output registers.
1538 for (unsigned i = 0; i < ValLocs.size(); ++i) {
1540 CCValAssign &VA = ValLocs[i];
1541 assert(VA.isRegLoc() && "Can only return in registers!");
1542 RetRegs.push_back(VA.getLocReg());
1543 unsigned SrcReg = Reg + VA.getValNo();
1545 EVT RVEVT = TLI.getValueType(RV->getType());
1546 if (!RVEVT.isSimple())
1548 MVT RVVT = RVEVT.getSimpleVT();
1549 MVT DestVT = VA.getLocVT();
1551 if (RVVT != DestVT && RVVT != MVT::i8 &&
1552 RVVT != MVT::i16 && RVVT != MVT::i32)
1555 if (RVVT != DestVT) {
1556 switch (VA.getLocInfo()) {
1558 llvm_unreachable("Unknown loc info!");
1559 case CCValAssign::Full:
1560 llvm_unreachable("Full value assign but types don't match?");
1561 case CCValAssign::AExt:
1562 case CCValAssign::ZExt: {
1563 const TargetRegisterClass *RC =
1564 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1565 unsigned TmpReg = createResultReg(RC);
1566 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, true))
1571 case CCValAssign::SExt: {
1572 const TargetRegisterClass *RC =
1573 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1574 unsigned TmpReg = createResultReg(RC);
1575 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, false))
1583 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1584 TII.get(TargetOpcode::COPY), RetRegs[i])
1590 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1593 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1594 MIB.addReg(RetRegs[i], RegState::Implicit);
1599 // Attempt to emit an integer extend of SrcReg into DestReg. Both
1600 // signed and zero extensions are supported. Return false if we
1602 bool PPCFastISel::PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1603 unsigned DestReg, bool IsZExt) {
1604 if (DestVT != MVT::i32 && DestVT != MVT::i64)
1606 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 && SrcVT != MVT::i32)
1609 // Signed extensions use EXTSB, EXTSH, EXTSW.
1612 if (SrcVT == MVT::i8)
1613 Opc = (DestVT == MVT::i32) ? PPC::EXTSB : PPC::EXTSB8_32_64;
1614 else if (SrcVT == MVT::i16)
1615 Opc = (DestVT == MVT::i32) ? PPC::EXTSH : PPC::EXTSH8_32_64;
1617 assert(DestVT == MVT::i64 && "Signed extend from i32 to i32??");
1618 Opc = PPC::EXTSW_32_64;
1620 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1623 // Unsigned 32-bit extensions use RLWINM.
1624 } else if (DestVT == MVT::i32) {
1626 if (SrcVT == MVT::i8)
1629 assert(SrcVT == MVT::i16 && "Unsigned extend from i32 to i32??");
1632 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::RLWINM),
1634 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB).addImm(/*ME=*/31);
1636 // Unsigned 64-bit extensions use RLDICL (with a 32-bit source).
1639 if (SrcVT == MVT::i8)
1641 else if (SrcVT == MVT::i16)
1645 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1646 TII.get(PPC::RLDICL_32_64), DestReg)
1647 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB);
1653 // Attempt to fast-select an indirect branch instruction.
1654 bool PPCFastISel::SelectIndirectBr(const Instruction *I) {
1655 unsigned AddrReg = getRegForValue(I->getOperand(0));
1659 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::MTCTR8))
1661 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::BCTR8));
1663 const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1664 for (unsigned i = 0, e = IB->getNumSuccessors(); i != e; ++i)
1665 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[IB->getSuccessor(i)]);
1670 // Attempt to fast-select an integer truncate instruction.
1671 bool PPCFastISel::SelectTrunc(const Instruction *I) {
1672 Value *Src = I->getOperand(0);
1673 EVT SrcVT = TLI.getValueType(Src->getType(), true);
1674 EVT DestVT = TLI.getValueType(I->getType(), true);
1676 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16)
1679 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8)
1682 unsigned SrcReg = getRegForValue(Src);
1686 // The only interesting case is when we need to switch register classes.
1687 if (SrcVT == MVT::i64) {
1688 unsigned ResultReg = createResultReg(&PPC::GPRCRegClass);
1689 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1690 ResultReg).addReg(SrcReg, 0, PPC::sub_32);
1694 UpdateValueMap(I, SrcReg);
1698 // Attempt to fast-select an integer extend instruction.
1699 bool PPCFastISel::SelectIntExt(const Instruction *I) {
1700 Type *DestTy = I->getType();
1701 Value *Src = I->getOperand(0);
1702 Type *SrcTy = Src->getType();
1704 bool IsZExt = isa<ZExtInst>(I);
1705 unsigned SrcReg = getRegForValue(Src);
1706 if (!SrcReg) return false;
1708 EVT SrcEVT, DestEVT;
1709 SrcEVT = TLI.getValueType(SrcTy, true);
1710 DestEVT = TLI.getValueType(DestTy, true);
1711 if (!SrcEVT.isSimple())
1713 if (!DestEVT.isSimple())
1716 MVT SrcVT = SrcEVT.getSimpleVT();
1717 MVT DestVT = DestEVT.getSimpleVT();
1719 // If we know the register class needed for the result of this
1720 // instruction, use it. Otherwise pick the register class of the
1721 // correct size that does not contain X0/R0, since we don't know
1722 // whether downstream uses permit that assignment.
1723 unsigned AssignedReg = FuncInfo.ValueMap[I];
1724 const TargetRegisterClass *RC =
1725 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1726 (DestVT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
1727 &PPC::GPRC_and_GPRC_NOR0RegClass));
1728 unsigned ResultReg = createResultReg(RC);
1730 if (!PPCEmitIntExt(SrcVT, SrcReg, DestVT, ResultReg, IsZExt))
1733 UpdateValueMap(I, ResultReg);
1737 // Attempt to fast-select an instruction that wasn't handled by
1738 // the table-generated machinery.
1739 bool PPCFastISel::TargetSelectInstruction(const Instruction *I) {
1741 switch (I->getOpcode()) {
1742 case Instruction::Load:
1743 return SelectLoad(I);
1744 case Instruction::Store:
1745 return SelectStore(I);
1746 case Instruction::Br:
1747 return SelectBranch(I);
1748 case Instruction::IndirectBr:
1749 return SelectIndirectBr(I);
1750 case Instruction::FPExt:
1751 return SelectFPExt(I);
1752 case Instruction::FPTrunc:
1753 return SelectFPTrunc(I);
1754 case Instruction::SIToFP:
1755 return SelectIToFP(I, /*IsSigned*/ true);
1756 case Instruction::UIToFP:
1757 return SelectIToFP(I, /*IsSigned*/ false);
1758 case Instruction::FPToSI:
1759 return SelectFPToI(I, /*IsSigned*/ true);
1760 case Instruction::FPToUI:
1761 return SelectFPToI(I, /*IsSigned*/ false);
1762 case Instruction::Add:
1763 return SelectBinaryIntOp(I, ISD::ADD);
1764 case Instruction::Or:
1765 return SelectBinaryIntOp(I, ISD::OR);
1766 case Instruction::Sub:
1767 return SelectBinaryIntOp(I, ISD::SUB);
1768 case Instruction::Call:
1769 if (dyn_cast<IntrinsicInst>(I))
1771 return SelectCall(I);
1772 case Instruction::Ret:
1773 return SelectRet(I);
1774 case Instruction::Trunc:
1775 return SelectTrunc(I);
1776 case Instruction::ZExt:
1777 case Instruction::SExt:
1778 return SelectIntExt(I);
1779 // Here add other flavors of Instruction::XXX that automated
1780 // cases don't catch. For example, switches are terminators
1781 // that aren't yet handled.
1788 // Materialize a floating-point constant into a register, and return
1789 // the register number (or zero if we failed to handle it).
1790 unsigned PPCFastISel::PPCMaterializeFP(const ConstantFP *CFP, MVT VT) {
1791 // No plans to handle long double here.
1792 if (VT != MVT::f32 && VT != MVT::f64)
1795 // All FP constants are loaded from the constant pool.
1796 unsigned Align = TD.getPrefTypeAlignment(CFP->getType());
1797 assert(Align > 0 && "Unexpectedly missing alignment information!");
1798 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
1799 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
1800 CodeModel::Model CModel = TM.getCodeModel();
1802 MachineMemOperand *MMO =
1803 FuncInfo.MF->getMachineMemOperand(
1804 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
1805 (VT == MVT::f32) ? 4 : 8, Align);
1807 unsigned Opc = (VT == MVT::f32) ? PPC::LFS : PPC::LFD;
1808 unsigned TmpReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1810 // For small code model, generate a LF[SD](0, LDtocCPT(Idx, X2)).
1811 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault) {
1812 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocCPT),
1814 .addConstantPoolIndex(Idx).addReg(PPC::X2);
1815 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1816 .addImm(0).addReg(TmpReg).addMemOperand(MMO);
1818 // Otherwise we generate LF[SD](Idx[lo], ADDIStocHA(X2, Idx)).
1819 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDIStocHA),
1820 TmpReg).addReg(PPC::X2).addConstantPoolIndex(Idx);
1821 // But for large code model, we must generate a LDtocL followed
1823 if (CModel == CodeModel::Large) {
1824 unsigned TmpReg2 = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1825 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocL),
1826 TmpReg2).addConstantPoolIndex(Idx).addReg(TmpReg);
1827 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1828 .addImm(0).addReg(TmpReg2);
1830 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1831 .addConstantPoolIndex(Idx, 0, PPCII::MO_TOC_LO)
1833 .addMemOperand(MMO);
1839 // Materialize the address of a global value into a register, and return
1840 // the register number (or zero if we failed to handle it).
1841 unsigned PPCFastISel::PPCMaterializeGV(const GlobalValue *GV, MVT VT) {
1842 assert(VT == MVT::i64 && "Non-address!");
1843 const TargetRegisterClass *RC = &PPC::G8RC_and_G8RC_NOX0RegClass;
1844 unsigned DestReg = createResultReg(RC);
1846 // Global values may be plain old object addresses, TLS object
1847 // addresses, constant pool entries, or jump tables. How we generate
1848 // code for these may depend on small, medium, or large code model.
1849 CodeModel::Model CModel = TM.getCodeModel();
1851 // FIXME: Jump tables are not yet required because fast-isel doesn't
1852 // handle switches; if that changes, we need them as well. For now,
1853 // what follows assumes everything's a generic (or TLS) global address.
1854 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1856 // If GV is an alias, use the aliasee for determining thread-locality.
1857 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1858 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
1861 // FIXME: We don't yet handle the complexity of TLS.
1862 bool IsTLS = GVar && GVar->isThreadLocal();
1866 // For small code model, generate a simple TOC load.
1867 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault)
1868 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtoc), DestReg)
1869 .addGlobalAddress(GV).addReg(PPC::X2);
1871 // If the address is an externally defined symbol, a symbol with
1872 // common or externally available linkage, a function address, or a
1873 // jump table address (not yet needed), or if we are generating code
1874 // for large code model, we generate:
1875 // LDtocL(GV, ADDIStocHA(%X2, GV))
1876 // Otherwise we generate:
1877 // ADDItocL(ADDIStocHA(%X2, GV), GV)
1878 // Either way, start with the ADDIStocHA:
1879 unsigned HighPartReg = createResultReg(RC);
1880 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDIStocHA),
1881 HighPartReg).addReg(PPC::X2).addGlobalAddress(GV);
1883 // !GVar implies a function address. An external variable is one
1884 // without an initializer.
1885 // If/when switches are implemented, jump tables should be handled
1886 // on the "if" path here.
1887 if (CModel == CodeModel::Large || !GVar || !GVar->hasInitializer() ||
1888 GVar->hasCommonLinkage() || GVar->hasAvailableExternallyLinkage())
1889 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocL),
1890 DestReg).addGlobalAddress(GV).addReg(HighPartReg);
1892 // Otherwise generate the ADDItocL.
1893 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDItocL),
1894 DestReg).addReg(HighPartReg).addGlobalAddress(GV);
1900 // Materialize a 32-bit integer constant into a register, and return
1901 // the register number (or zero if we failed to handle it).
1902 unsigned PPCFastISel::PPCMaterialize32BitInt(int64_t Imm,
1903 const TargetRegisterClass *RC) {
1904 unsigned Lo = Imm & 0xFFFF;
1905 unsigned Hi = (Imm >> 16) & 0xFFFF;
1907 unsigned ResultReg = createResultReg(RC);
1908 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1911 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1912 TII.get(IsGPRC ? PPC::LI : PPC::LI8), ResultReg)
1915 // Both Lo and Hi have nonzero bits.
1916 unsigned TmpReg = createResultReg(RC);
1917 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1918 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), TmpReg)
1920 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1921 TII.get(IsGPRC ? PPC::ORI : PPC::ORI8), ResultReg)
1922 .addReg(TmpReg).addImm(Lo);
1925 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1926 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), ResultReg)
1932 // Materialize a 64-bit integer constant into a register, and return
1933 // the register number (or zero if we failed to handle it).
1934 unsigned PPCFastISel::PPCMaterialize64BitInt(int64_t Imm,
1935 const TargetRegisterClass *RC) {
1936 unsigned Remainder = 0;
1939 // If the value doesn't fit in 32 bits, see if we can shift it
1940 // so that it fits in 32 bits.
1941 if (!isInt<32>(Imm)) {
1942 Shift = countTrailingZeros<uint64_t>(Imm);
1943 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
1945 if (isInt<32>(ImmSh))
1954 // Handle the high-order 32 bits (if shifted) or the whole 32 bits
1955 // (if not shifted).
1956 unsigned TmpReg1 = PPCMaterialize32BitInt(Imm, RC);
1960 // If upper 32 bits were not zero, we've built them and need to shift
1964 TmpReg2 = createResultReg(RC);
1965 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::RLDICR),
1966 TmpReg2).addReg(TmpReg1).addImm(Shift).addImm(63 - Shift);
1970 unsigned TmpReg3, Hi, Lo;
1971 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
1972 TmpReg3 = createResultReg(RC);
1973 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ORIS8),
1974 TmpReg3).addReg(TmpReg2).addImm(Hi);
1978 if ((Lo = Remainder & 0xFFFF)) {
1979 unsigned ResultReg = createResultReg(RC);
1980 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ORI8),
1981 ResultReg).addReg(TmpReg3).addImm(Lo);
1989 // Materialize an integer constant into a register, and return
1990 // the register number (or zero if we failed to handle it).
1991 unsigned PPCFastISel::PPCMaterializeInt(const Constant *C, MVT VT) {
1993 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
1994 VT != MVT::i8 && VT != MVT::i1)
1997 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
1998 &PPC::GPRCRegClass);
2000 // If the constant is in range, use a load-immediate.
2001 const ConstantInt *CI = cast<ConstantInt>(C);
2002 if (isInt<16>(CI->getSExtValue())) {
2003 unsigned Opc = (VT == MVT::i64) ? PPC::LI8 : PPC::LI;
2004 unsigned ImmReg = createResultReg(RC);
2005 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ImmReg)
2006 .addImm(CI->getSExtValue());
2010 // Construct the constant piecewise.
2011 int64_t Imm = CI->getZExtValue();
2014 return PPCMaterialize64BitInt(Imm, RC);
2015 else if (VT == MVT::i32)
2016 return PPCMaterialize32BitInt(Imm, RC);
2021 // Materialize a constant into a register, and return the register
2022 // number (or zero if we failed to handle it).
2023 unsigned PPCFastISel::TargetMaterializeConstant(const Constant *C) {
2024 EVT CEVT = TLI.getValueType(C->getType(), true);
2026 // Only handle simple types.
2027 if (!CEVT.isSimple()) return 0;
2028 MVT VT = CEVT.getSimpleVT();
2030 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
2031 return PPCMaterializeFP(CFP, VT);
2032 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
2033 return PPCMaterializeGV(GV, VT);
2034 else if (isa<ConstantInt>(C))
2035 return PPCMaterializeInt(C, VT);
2040 // Materialize the address created by an alloca into a register, and
2041 // return the register number (or zero if we failed to handle it).
2042 unsigned PPCFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
2043 // Don't handle dynamic allocas.
2044 if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
2047 if (!isLoadTypeLegal(AI->getType(), VT)) return 0;
2049 DenseMap<const AllocaInst*, int>::iterator SI =
2050 FuncInfo.StaticAllocaMap.find(AI);
2052 if (SI != FuncInfo.StaticAllocaMap.end()) {
2053 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
2054 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDI8),
2055 ResultReg).addFrameIndex(SI->second).addImm(0);
2062 // Fold loads into extends when possible.
2063 // FIXME: We can have multiple redundant extend/trunc instructions
2064 // following a load. The folding only picks up one. Extend this
2065 // to check subsequent instructions for the same pattern and remove
2066 // them. Thus ResultReg should be the def reg for the last redundant
2067 // instruction in a chain, and all intervening instructions can be
2068 // removed from parent. Change test/CodeGen/PowerPC/fast-isel-fold.ll
2069 // to add ELF64-NOT: rldicl to the appropriate tests when this works.
2070 bool PPCFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2071 const LoadInst *LI) {
2072 // Verify we have a legal type before going any further.
2074 if (!isLoadTypeLegal(LI->getType(), VT))
2077 // Combine load followed by zero- or sign-extend.
2078 bool IsZExt = false;
2079 switch(MI->getOpcode()) {
2084 case PPC::RLDICL_32_64: {
2086 unsigned MB = MI->getOperand(3).getImm();
2087 if ((VT == MVT::i8 && MB <= 56) ||
2088 (VT == MVT::i16 && MB <= 48) ||
2089 (VT == MVT::i32 && MB <= 32))
2095 case PPC::RLWINM8: {
2097 unsigned MB = MI->getOperand(3).getImm();
2098 if ((VT == MVT::i8 && MB <= 24) ||
2099 (VT == MVT::i16 && MB <= 16))
2106 case PPC::EXTSB8_32_64:
2107 /* There is no sign-extending load-byte instruction. */
2112 case PPC::EXTSH8_32_64: {
2113 if (VT != MVT::i16 && VT != MVT::i8)
2119 case PPC::EXTSW_32_64: {
2120 if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8)
2126 // See if we can handle this address.
2128 if (!PPCComputeAddress(LI->getOperand(0), Addr))
2131 unsigned ResultReg = MI->getOperand(0).getReg();
2133 if (!PPCEmitLoad(VT, ResultReg, Addr, 0, IsZExt))
2136 MI->eraseFromParent();
2140 // Attempt to lower call arguments in a faster way than done by
2141 // the selection DAG code.
2142 bool PPCFastISel::FastLowerArguments() {
2143 // Defer to normal argument lowering for now. It's reasonably
2144 // efficient. Consider doing something like ARM to handle the
2145 // case where all args fit in registers, no varargs, no float
2150 // Handle materializing integer constants into a register. This is not
2151 // automatically generated for PowerPC, so must be explicitly created here.
2152 unsigned PPCFastISel::FastEmit_i(MVT Ty, MVT VT, unsigned Opc, uint64_t Imm) {
2154 if (Opc != ISD::Constant)
2157 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2158 VT != MVT::i8 && VT != MVT::i1)
2161 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2162 &PPC::GPRCRegClass);
2164 return PPCMaterialize64BitInt(Imm, RC);
2166 return PPCMaterialize32BitInt(Imm, RC);
2169 // Override for ADDI and ADDI8 to set the correct register class
2170 // on RHS operand 0. The automatic infrastructure naively assumes
2171 // GPRC for i32 and G8RC for i64; the concept of "no R0" is lost
2172 // for these cases. At the moment, none of the other automatically
2173 // generated RI instructions require special treatment. However, once
2174 // SelectSelect is implemented, "isel" requires similar handling.
2176 // Also be conservative about the output register class. Avoid
2177 // assigning R0 or X0 to the output register for GPRC and G8RC
2178 // register classes, as any such result could be used in ADDI, etc.,
2179 // where those regs have another meaning.
2180 unsigned PPCFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
2181 const TargetRegisterClass *RC,
2182 unsigned Op0, bool Op0IsKill,
2184 if (MachineInstOpcode == PPC::ADDI)
2185 MRI.setRegClass(Op0, &PPC::GPRC_and_GPRC_NOR0RegClass);
2186 else if (MachineInstOpcode == PPC::ADDI8)
2187 MRI.setRegClass(Op0, &PPC::G8RC_and_G8RC_NOX0RegClass);
2189 const TargetRegisterClass *UseRC =
2190 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2191 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2193 return FastISel::FastEmitInst_ri(MachineInstOpcode, UseRC,
2194 Op0, Op0IsKill, Imm);
2197 // Override for instructions with one register operand to avoid use of
2198 // R0/X0. The automatic infrastructure isn't aware of the context so
2199 // we must be conservative.
2200 unsigned PPCFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
2201 const TargetRegisterClass* RC,
2202 unsigned Op0, bool Op0IsKill) {
2203 const TargetRegisterClass *UseRC =
2204 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2205 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2207 return FastISel::FastEmitInst_r(MachineInstOpcode, UseRC, Op0, Op0IsKill);
2210 // Override for instructions with two register operands to avoid use
2211 // of R0/X0. The automatic infrastructure isn't aware of the context
2212 // so we must be conservative.
2213 unsigned PPCFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
2214 const TargetRegisterClass* RC,
2215 unsigned Op0, bool Op0IsKill,
2216 unsigned Op1, bool Op1IsKill) {
2217 const TargetRegisterClass *UseRC =
2218 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2219 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2221 return FastISel::FastEmitInst_rr(MachineInstOpcode, UseRC, Op0, Op0IsKill,
2226 // Create the fast instruction selector for PowerPC64 ELF.
2227 FastISel *PPC::createFastISel(FunctionLoweringInfo &FuncInfo,
2228 const TargetLibraryInfo *LibInfo) {
2229 const TargetMachine &TM = FuncInfo.MF->getTarget();
2231 // Only available on 64-bit ELF for now.
2232 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
2233 if (Subtarget->isPPC64() && Subtarget->isSVR4ABI())
2234 return new PPCFastISel(FuncInfo, LibInfo);