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"
44 typedef struct Address {
57 // Innocuous defaults for our address.
59 : BaseType(RegBase), Offset(0) {
64 class PPCFastISel : public FastISel {
66 const TargetMachine &TM;
67 const TargetInstrInfo &TII;
68 const TargetLowering &TLI;
69 const PPCSubtarget &PPCSubTarget;
73 explicit PPCFastISel(FunctionLoweringInfo &FuncInfo,
74 const TargetLibraryInfo *LibInfo)
75 : FastISel(FuncInfo, LibInfo),
76 TM(FuncInfo.MF->getTarget()),
77 TII(*TM.getInstrInfo()),
78 TLI(*TM.getTargetLowering()),
80 *((static_cast<const PPCTargetMachine *>(&TM))->getSubtargetImpl())
82 Context(&FuncInfo.Fn->getContext()) { }
84 // Backend specific FastISel code.
86 virtual bool TargetSelectInstruction(const Instruction *I);
87 virtual unsigned TargetMaterializeConstant(const Constant *C);
88 virtual unsigned TargetMaterializeAlloca(const AllocaInst *AI);
89 virtual bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
91 virtual bool FastLowerArguments();
92 virtual unsigned FastEmit_i(MVT Ty, MVT RetTy, unsigned Opc, uint64_t Imm);
93 virtual unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
94 const TargetRegisterClass *RC,
95 unsigned Op0, bool Op0IsKill,
97 virtual unsigned FastEmitInst_r(unsigned MachineInstOpcode,
98 const TargetRegisterClass *RC,
99 unsigned Op0, bool Op0IsKill);
100 virtual unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
101 const TargetRegisterClass *RC,
102 unsigned Op0, bool Op0IsKill,
103 unsigned Op1, bool Op1IsKill);
105 // Instruction selection routines.
107 bool SelectLoad(const Instruction *I);
108 bool SelectStore(const Instruction *I);
109 bool SelectBranch(const Instruction *I);
110 bool SelectIndirectBr(const Instruction *I);
111 bool SelectCmp(const Instruction *I);
112 bool SelectFPExt(const Instruction *I);
113 bool SelectFPTrunc(const Instruction *I);
114 bool SelectIToFP(const Instruction *I, bool IsSigned);
115 bool SelectFPToI(const Instruction *I, bool IsSigned);
116 bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
117 bool SelectCall(const Instruction *I);
118 bool SelectRet(const Instruction *I);
119 bool SelectIntExt(const Instruction *I);
123 bool isTypeLegal(Type *Ty, MVT &VT);
124 bool isLoadTypeLegal(Type *Ty, MVT &VT);
125 bool PPCEmitCmp(const Value *Src1Value, const Value *Src2Value,
126 bool isZExt, unsigned DestReg);
127 bool PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
128 const TargetRegisterClass *RC, bool IsZExt = true,
129 unsigned FP64LoadOpc = PPC::LFD);
130 bool PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr);
131 bool PPCComputeAddress(const Value *Obj, Address &Addr);
132 void PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
134 bool PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
135 unsigned DestReg, bool IsZExt);
136 unsigned PPCMaterializeFP(const ConstantFP *CFP, MVT VT);
137 unsigned PPCMaterializeGV(const GlobalValue *GV, MVT VT);
138 unsigned PPCMaterializeInt(const Constant *C, MVT VT);
139 unsigned PPCMaterialize32BitInt(int64_t Imm,
140 const TargetRegisterClass *RC);
141 unsigned PPCMaterialize64BitInt(int64_t Imm,
142 const TargetRegisterClass *RC);
143 unsigned PPCMoveToIntReg(const Instruction *I, MVT VT,
144 unsigned SrcReg, bool IsSigned);
145 unsigned PPCMoveToFPReg(MVT VT, unsigned SrcReg, bool IsSigned);
147 // Call handling routines.
149 bool processCallArgs(SmallVectorImpl<Value*> &Args,
150 SmallVectorImpl<unsigned> &ArgRegs,
151 SmallVectorImpl<MVT> &ArgVTs,
152 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
153 SmallVectorImpl<unsigned> &RegArgs,
157 void finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
158 const Instruction *I, CallingConv::ID CC,
159 unsigned &NumBytes, bool IsVarArg);
160 CCAssignFn *usePPC32CCs(unsigned Flag);
163 #include "PPCGenFastISel.inc"
167 } // end anonymous namespace
169 #include "PPCGenCallingConv.inc"
171 // Function whose sole purpose is to kill compiler warnings
172 // stemming from unused functions included from PPCGenCallingConv.inc.
173 CCAssignFn *PPCFastISel::usePPC32CCs(unsigned Flag) {
175 return CC_PPC32_SVR4;
177 return CC_PPC32_SVR4_ByVal;
179 return CC_PPC32_SVR4_VarArg;
184 static Optional<PPC::Predicate> getComparePred(CmpInst::Predicate Pred) {
186 // These are not representable with any single compare.
187 case CmpInst::FCMP_FALSE:
188 case CmpInst::FCMP_UEQ:
189 case CmpInst::FCMP_UGT:
190 case CmpInst::FCMP_UGE:
191 case CmpInst::FCMP_ULT:
192 case CmpInst::FCMP_ULE:
193 case CmpInst::FCMP_UNE:
194 case CmpInst::FCMP_TRUE:
196 return Optional<PPC::Predicate>();
198 case CmpInst::FCMP_OEQ:
199 case CmpInst::ICMP_EQ:
202 case CmpInst::FCMP_OGT:
203 case CmpInst::ICMP_UGT:
204 case CmpInst::ICMP_SGT:
207 case CmpInst::FCMP_OGE:
208 case CmpInst::ICMP_UGE:
209 case CmpInst::ICMP_SGE:
212 case CmpInst::FCMP_OLT:
213 case CmpInst::ICMP_ULT:
214 case CmpInst::ICMP_SLT:
217 case CmpInst::FCMP_OLE:
218 case CmpInst::ICMP_ULE:
219 case CmpInst::ICMP_SLE:
222 case CmpInst::FCMP_ONE:
223 case CmpInst::ICMP_NE:
226 case CmpInst::FCMP_ORD:
229 case CmpInst::FCMP_UNO:
234 // Determine whether the type Ty is simple enough to be handled by
235 // fast-isel, and return its equivalent machine type in VT.
236 // FIXME: Copied directly from ARM -- factor into base class?
237 bool PPCFastISel::isTypeLegal(Type *Ty, MVT &VT) {
238 EVT Evt = TLI.getValueType(Ty, true);
240 // Only handle simple types.
241 if (Evt == MVT::Other || !Evt.isSimple()) return false;
242 VT = Evt.getSimpleVT();
244 // Handle all legal types, i.e. a register that will directly hold this
246 return TLI.isTypeLegal(VT);
249 // Determine whether the type Ty is simple enough to be handled by
250 // fast-isel as a load target, and return its equivalent machine type in VT.
251 bool PPCFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
252 if (isTypeLegal(Ty, VT)) return true;
254 // If this is a type than can be sign or zero-extended to a basic operation
255 // go ahead and accept it now.
256 if (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) {
263 // Given a value Obj, create an Address object Addr that represents its
264 // address. Return false if we can't handle it.
265 bool PPCFastISel::PPCComputeAddress(const Value *Obj, Address &Addr) {
266 const User *U = NULL;
267 unsigned Opcode = Instruction::UserOp1;
268 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
269 // Don't walk into other basic blocks unless the object is an alloca from
270 // another block, otherwise it may not have a virtual register assigned.
271 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
272 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
273 Opcode = I->getOpcode();
276 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
277 Opcode = C->getOpcode();
284 case Instruction::BitCast:
285 // Look through bitcasts.
286 return PPCComputeAddress(U->getOperand(0), Addr);
287 case Instruction::IntToPtr:
288 // Look past no-op inttoptrs.
289 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
290 return PPCComputeAddress(U->getOperand(0), Addr);
292 case Instruction::PtrToInt:
293 // Look past no-op ptrtoints.
294 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
295 return PPCComputeAddress(U->getOperand(0), Addr);
297 case Instruction::GetElementPtr: {
298 Address SavedAddr = Addr;
299 long TmpOffset = Addr.Offset;
301 // Iterate through the GEP folding the constants into offsets where
303 gep_type_iterator GTI = gep_type_begin(U);
304 for (User::const_op_iterator II = U->op_begin() + 1, IE = U->op_end();
305 II != IE; ++II, ++GTI) {
306 const Value *Op = *II;
307 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
308 const StructLayout *SL = TD.getStructLayout(STy);
309 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
310 TmpOffset += SL->getElementOffset(Idx);
312 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
314 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
315 // Constant-offset addressing.
316 TmpOffset += CI->getSExtValue() * S;
319 if (isa<AddOperator>(Op) &&
320 (!isa<Instruction>(Op) ||
321 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
323 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
324 // An add (in the same block) with a constant operand. Fold the
327 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
328 TmpOffset += CI->getSExtValue() * S;
329 // Iterate on the other operand.
330 Op = cast<AddOperator>(Op)->getOperand(0);
334 goto unsupported_gep;
339 // Try to grab the base operand now.
340 Addr.Offset = TmpOffset;
341 if (PPCComputeAddress(U->getOperand(0), Addr)) return true;
343 // We failed, restore everything and try the other options.
349 case Instruction::Alloca: {
350 const AllocaInst *AI = cast<AllocaInst>(Obj);
351 DenseMap<const AllocaInst*, int>::iterator SI =
352 FuncInfo.StaticAllocaMap.find(AI);
353 if (SI != FuncInfo.StaticAllocaMap.end()) {
354 Addr.BaseType = Address::FrameIndexBase;
355 Addr.Base.FI = SI->second;
362 // FIXME: References to parameters fall through to the behavior
363 // below. They should be able to reference a frame index since
364 // they are stored to the stack, so we can get "ld rx, offset(r1)"
365 // instead of "addi ry, r1, offset / ld rx, 0(ry)". Obj will
366 // just contain the parameter. Try to handle this with a FI.
368 // Try to get this in a register if nothing else has worked.
369 if (Addr.Base.Reg == 0)
370 Addr.Base.Reg = getRegForValue(Obj);
372 // Prevent assignment of base register to X0, which is inappropriate
373 // for loads and stores alike.
374 if (Addr.Base.Reg != 0)
375 MRI.setRegClass(Addr.Base.Reg, &PPC::G8RC_and_G8RC_NOX0RegClass);
377 return Addr.Base.Reg != 0;
380 // Fix up some addresses that can't be used directly. For example, if
381 // an offset won't fit in an instruction field, we may need to move it
382 // into an index register.
383 void PPCFastISel::PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
384 unsigned &IndexReg) {
386 // Check whether the offset fits in the instruction field.
387 if (!isInt<16>(Addr.Offset))
390 // If this is a stack pointer and the offset needs to be simplified then
391 // put the alloca address into a register, set the base type back to
392 // register and continue. This should almost never happen.
393 if (!UseOffset && Addr.BaseType == Address::FrameIndexBase) {
394 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
395 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDI8),
396 ResultReg).addFrameIndex(Addr.Base.FI).addImm(0);
397 Addr.Base.Reg = ResultReg;
398 Addr.BaseType = Address::RegBase;
402 IntegerType *OffsetTy = ((VT == MVT::i32) ? Type::getInt32Ty(*Context)
403 : Type::getInt64Ty(*Context));
404 const ConstantInt *Offset =
405 ConstantInt::getSigned(OffsetTy, (int64_t)(Addr.Offset));
406 IndexReg = PPCMaterializeInt(Offset, MVT::i64);
407 assert(IndexReg && "Unexpected error in PPCMaterializeInt!");
411 // Emit a load instruction if possible, returning true if we succeeded,
412 // otherwise false. See commentary below for how the register class of
413 // the load is determined.
414 bool PPCFastISel::PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
415 const TargetRegisterClass *RC,
416 bool IsZExt, unsigned FP64LoadOpc) {
418 bool UseOffset = true;
420 // If ResultReg is given, it determines the register class of the load.
421 // Otherwise, RC is the register class to use. If the result of the
422 // load isn't anticipated in this block, both may be zero, in which
423 // case we must make a conservative guess. In particular, don't assign
424 // R0 or X0 to the result register, as the result may be used in a load,
425 // store, add-immediate, or isel that won't permit this. (Though
426 // perhaps the spill and reload of live-exit values would handle this?)
427 const TargetRegisterClass *UseRC =
428 (ResultReg ? MRI.getRegClass(ResultReg) :
430 (VT == MVT::f64 ? &PPC::F8RCRegClass :
431 (VT == MVT::f32 ? &PPC::F4RCRegClass :
432 (VT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
433 &PPC::GPRC_and_GPRC_NOR0RegClass)))));
435 bool Is32BitInt = UseRC->hasSuperClassEq(&PPC::GPRCRegClass);
437 switch (VT.SimpleTy) {
438 default: // e.g., vector types not handled
441 Opc = Is32BitInt ? PPC::LBZ : PPC::LBZ8;
445 (Is32BitInt ? PPC::LHZ : PPC::LHZ8) :
446 (Is32BitInt ? PPC::LHA : PPC::LHA8));
450 (Is32BitInt ? PPC::LWZ : PPC::LWZ8) :
451 (Is32BitInt ? PPC::LWA_32 : PPC::LWA));
452 if ((Opc == PPC::LWA || Opc == PPC::LWA_32) && ((Addr.Offset & 3) != 0))
457 assert(UseRC->hasSuperClassEq(&PPC::G8RCRegClass) &&
458 "64-bit load with 32-bit target??");
459 UseOffset = ((Addr.Offset & 3) == 0);
469 // If necessary, materialize the offset into a register and use
470 // the indexed form. Also handle stack pointers with special needs.
471 unsigned IndexReg = 0;
472 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
474 ResultReg = createResultReg(UseRC);
476 // Note: If we still have a frame index here, we know the offset is
477 // in range, as otherwise PPCSimplifyAddress would have converted it
479 if (Addr.BaseType == Address::FrameIndexBase) {
481 MachineMemOperand *MMO =
482 FuncInfo.MF->getMachineMemOperand(
483 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
484 MachineMemOperand::MOLoad, MFI.getObjectSize(Addr.Base.FI),
485 MFI.getObjectAlignment(Addr.Base.FI));
487 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
488 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
490 // Base reg with offset in range.
491 } else if (UseOffset) {
493 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
494 .addImm(Addr.Offset).addReg(Addr.Base.Reg);
498 // Get the RR opcode corresponding to the RI one. FIXME: It would be
499 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
500 // is hard to get at.
502 default: llvm_unreachable("Unexpected opcode!");
503 case PPC::LBZ: Opc = PPC::LBZX; break;
504 case PPC::LBZ8: Opc = PPC::LBZX8; break;
505 case PPC::LHZ: Opc = PPC::LHZX; break;
506 case PPC::LHZ8: Opc = PPC::LHZX8; break;
507 case PPC::LHA: Opc = PPC::LHAX; break;
508 case PPC::LHA8: Opc = PPC::LHAX8; break;
509 case PPC::LWZ: Opc = PPC::LWZX; break;
510 case PPC::LWZ8: Opc = PPC::LWZX8; break;
511 case PPC::LWA: Opc = PPC::LWAX; break;
512 case PPC::LWA_32: Opc = PPC::LWAX_32; break;
513 case PPC::LD: Opc = PPC::LDX; break;
514 case PPC::LFS: Opc = PPC::LFSX; break;
515 case PPC::LFD: Opc = PPC::LFDX; break;
517 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
518 .addReg(Addr.Base.Reg).addReg(IndexReg);
524 // Attempt to fast-select a load instruction.
525 bool PPCFastISel::SelectLoad(const Instruction *I) {
526 // FIXME: No atomic loads are supported.
527 if (cast<LoadInst>(I)->isAtomic())
530 // Verify we have a legal type before going any further.
532 if (!isLoadTypeLegal(I->getType(), VT))
535 // See if we can handle this address.
537 if (!PPCComputeAddress(I->getOperand(0), Addr))
540 // Look at the currently assigned register for this instruction
541 // to determine the required register class. This is necessary
542 // to constrain RA from using R0/X0 when this is not legal.
543 unsigned AssignedReg = FuncInfo.ValueMap[I];
544 const TargetRegisterClass *RC =
545 AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
547 unsigned ResultReg = 0;
548 if (!PPCEmitLoad(VT, ResultReg, Addr, RC))
550 UpdateValueMap(I, ResultReg);
554 // Emit a store instruction to store SrcReg at Addr.
555 bool PPCFastISel::PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr) {
556 assert(SrcReg && "Nothing to store!");
558 bool UseOffset = true;
560 const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
561 bool Is32BitInt = RC->hasSuperClassEq(&PPC::GPRCRegClass);
563 switch (VT.SimpleTy) {
564 default: // e.g., vector types not handled
567 Opc = Is32BitInt ? PPC::STB : PPC::STB8;
570 Opc = Is32BitInt ? PPC::STH : PPC::STH8;
573 assert(Is32BitInt && "Not GPRC for i32??");
578 UseOffset = ((Addr.Offset & 3) == 0);
588 // If necessary, materialize the offset into a register and use
589 // the indexed form. Also handle stack pointers with special needs.
590 unsigned IndexReg = 0;
591 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
593 // Note: If we still have a frame index here, we know the offset is
594 // in range, as otherwise PPCSimplifyAddress would have converted it
596 if (Addr.BaseType == Address::FrameIndexBase) {
597 MachineMemOperand *MMO =
598 FuncInfo.MF->getMachineMemOperand(
599 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
600 MachineMemOperand::MOStore, MFI.getObjectSize(Addr.Base.FI),
601 MFI.getObjectAlignment(Addr.Base.FI));
603 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc)).addReg(SrcReg)
604 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
606 // Base reg with offset in range.
607 } else if (UseOffset)
608 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
609 .addReg(SrcReg).addImm(Addr.Offset).addReg(Addr.Base.Reg);
613 // Get the RR opcode corresponding to the RI one. FIXME: It would be
614 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
615 // is hard to get at.
617 default: llvm_unreachable("Unexpected opcode!");
618 case PPC::STB: Opc = PPC::STBX; break;
619 case PPC::STH : Opc = PPC::STHX; break;
620 case PPC::STW : Opc = PPC::STWX; break;
621 case PPC::STB8: Opc = PPC::STBX8; break;
622 case PPC::STH8: Opc = PPC::STHX8; break;
623 case PPC::STW8: Opc = PPC::STWX8; break;
624 case PPC::STD: Opc = PPC::STDX; break;
625 case PPC::STFS: Opc = PPC::STFSX; break;
626 case PPC::STFD: Opc = PPC::STFDX; break;
628 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
629 .addReg(SrcReg).addReg(Addr.Base.Reg).addReg(IndexReg);
635 // Attempt to fast-select a store instruction.
636 bool PPCFastISel::SelectStore(const Instruction *I) {
637 Value *Op0 = I->getOperand(0);
640 // FIXME: No atomics loads are supported.
641 if (cast<StoreInst>(I)->isAtomic())
644 // Verify we have a legal type before going any further.
646 if (!isLoadTypeLegal(Op0->getType(), VT))
649 // Get the value to be stored into a register.
650 SrcReg = getRegForValue(Op0);
654 // See if we can handle this address.
656 if (!PPCComputeAddress(I->getOperand(1), Addr))
659 if (!PPCEmitStore(VT, SrcReg, Addr))
665 // Attempt to fast-select a branch instruction.
666 bool PPCFastISel::SelectBranch(const Instruction *I) {
667 const BranchInst *BI = cast<BranchInst>(I);
668 MachineBasicBlock *BrBB = FuncInfo.MBB;
669 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
670 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
672 // For now, just try the simplest case where it's fed by a compare.
673 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
674 Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
678 PPC::Predicate PPCPred = OptPPCPred.getValue();
680 // Take advantage of fall-through opportunities.
681 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
683 PPCPred = PPC::InvertPredicate(PPCPred);
686 unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
688 if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
692 BuildMI(*BrBB, FuncInfo.InsertPt, DL, TII.get(PPC::BCC))
693 .addImm(PPCPred).addReg(CondReg).addMBB(TBB);
694 FastEmitBranch(FBB, DL);
695 FuncInfo.MBB->addSuccessor(TBB);
698 } else if (const ConstantInt *CI =
699 dyn_cast<ConstantInt>(BI->getCondition())) {
700 uint64_t Imm = CI->getZExtValue();
701 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
702 FastEmitBranch(Target, DL);
706 // FIXME: ARM looks for a case where the block containing the compare
707 // has been split from the block containing the branch. If this happens,
708 // there is a vreg available containing the result of the compare. I'm
709 // not sure we can do much, as we've lost the predicate information with
710 // the compare instruction -- we have a 4-bit CR but don't know which bit
715 // Attempt to emit a compare of the two source values. Signed and unsigned
716 // comparisons are supported. Return false if we can't handle it.
717 bool PPCFastISel::PPCEmitCmp(const Value *SrcValue1, const Value *SrcValue2,
718 bool IsZExt, unsigned DestReg) {
719 Type *Ty = SrcValue1->getType();
720 EVT SrcEVT = TLI.getValueType(Ty, true);
721 if (!SrcEVT.isSimple())
723 MVT SrcVT = SrcEVT.getSimpleVT();
725 // See if operand 2 is an immediate encodeable in the compare.
726 // FIXME: Operands are not in canonical order at -O0, so an immediate
727 // operand in position 1 is a lost opportunity for now. We are
728 // similar to ARM in this regard.
732 // Only 16-bit integer constants can be represented in compares for
733 // PowerPC. Others will be materialized into a register.
734 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(SrcValue2)) {
735 if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
736 SrcVT == MVT::i8 || SrcVT == MVT::i1) {
737 const APInt &CIVal = ConstInt->getValue();
738 Imm = (IsZExt) ? (long)CIVal.getZExtValue() : (long)CIVal.getSExtValue();
739 if ((IsZExt && isUInt<16>(Imm)) || (!IsZExt && isInt<16>(Imm)))
745 bool NeedsExt = false;
746 switch (SrcVT.SimpleTy) {
747 default: return false;
749 CmpOpc = PPC::FCMPUS;
752 CmpOpc = PPC::FCMPUD;
758 // Intentional fall-through.
761 CmpOpc = IsZExt ? PPC::CMPLW : PPC::CMPW;
763 CmpOpc = IsZExt ? PPC::CMPLWI : PPC::CMPWI;
767 CmpOpc = IsZExt ? PPC::CMPLD : PPC::CMPD;
769 CmpOpc = IsZExt ? PPC::CMPLDI : PPC::CMPDI;
773 unsigned SrcReg1 = getRegForValue(SrcValue1);
777 unsigned SrcReg2 = 0;
779 SrcReg2 = getRegForValue(SrcValue2);
785 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
786 if (!PPCEmitIntExt(SrcVT, SrcReg1, MVT::i32, ExtReg, IsZExt))
791 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
792 if (!PPCEmitIntExt(SrcVT, SrcReg2, MVT::i32, ExtReg, IsZExt))
799 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc), DestReg)
800 .addReg(SrcReg1).addReg(SrcReg2);
802 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc), DestReg)
803 .addReg(SrcReg1).addImm(Imm);
808 // Attempt to fast-select a floating-point extend instruction.
809 bool PPCFastISel::SelectFPExt(const Instruction *I) {
810 Value *Src = I->getOperand(0);
811 EVT SrcVT = TLI.getValueType(Src->getType(), true);
812 EVT DestVT = TLI.getValueType(I->getType(), true);
814 if (SrcVT != MVT::f32 || DestVT != MVT::f64)
817 unsigned SrcReg = getRegForValue(Src);
821 // No code is generated for a FP extend.
822 UpdateValueMap(I, SrcReg);
826 // Attempt to fast-select a floating-point truncate instruction.
827 bool PPCFastISel::SelectFPTrunc(const Instruction *I) {
828 Value *Src = I->getOperand(0);
829 EVT SrcVT = TLI.getValueType(Src->getType(), true);
830 EVT DestVT = TLI.getValueType(I->getType(), true);
832 if (SrcVT != MVT::f64 || DestVT != MVT::f32)
835 unsigned SrcReg = getRegForValue(Src);
839 // Round the result to single precision.
840 unsigned DestReg = createResultReg(&PPC::F4RCRegClass);
841 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::FRSP), DestReg)
844 UpdateValueMap(I, DestReg);
848 // Move an i32 or i64 value in a GPR to an f64 value in an FPR.
849 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
850 // those should be used instead of moving via a stack slot when the
851 // subtarget permits.
852 // FIXME: The code here is sloppy for the 4-byte case. Can use a 4-byte
853 // stack slot and 4-byte store/load sequence. Or just sext the 4-byte
854 // case to 8 bytes which produces tighter code but wastes stack space.
855 unsigned PPCFastISel::PPCMoveToFPReg(MVT SrcVT, unsigned SrcReg,
858 // If necessary, extend 32-bit int to 64-bit.
859 if (SrcVT == MVT::i32) {
860 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
861 if (!PPCEmitIntExt(MVT::i32, SrcReg, MVT::i64, TmpReg, !IsSigned))
866 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
868 Addr.BaseType = Address::FrameIndexBase;
869 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
871 // Store the value from the GPR.
872 if (!PPCEmitStore(MVT::i64, SrcReg, Addr))
875 // Load the integer value into an FPR. The kind of load used depends
876 // on a number of conditions.
877 unsigned LoadOpc = PPC::LFD;
879 if (SrcVT == MVT::i32) {
882 LoadOpc = PPC::LFIWZX;
883 else if (PPCSubTarget.hasLFIWAX())
884 LoadOpc = PPC::LFIWAX;
887 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
888 unsigned ResultReg = 0;
889 if (!PPCEmitLoad(MVT::f64, ResultReg, Addr, RC, !IsSigned, LoadOpc))
895 // Attempt to fast-select an integer-to-floating-point conversion.
896 bool PPCFastISel::SelectIToFP(const Instruction *I, bool IsSigned) {
898 Type *DstTy = I->getType();
899 if (!isTypeLegal(DstTy, DstVT))
902 if (DstVT != MVT::f32 && DstVT != MVT::f64)
905 Value *Src = I->getOperand(0);
906 EVT SrcEVT = TLI.getValueType(Src->getType(), true);
907 if (!SrcEVT.isSimple())
910 MVT SrcVT = SrcEVT.getSimpleVT();
912 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 &&
913 SrcVT != MVT::i32 && SrcVT != MVT::i64)
916 unsigned SrcReg = getRegForValue(Src);
920 // We can only lower an unsigned convert if we have the newer
921 // floating-point conversion operations.
922 if (!IsSigned && !PPCSubTarget.hasFPCVT())
925 // FIXME: For now we require the newer floating-point conversion operations
926 // (which are present only on P7 and A2 server models) when converting
927 // to single-precision float. Otherwise we have to generate a lot of
928 // fiddly code to avoid double rounding. If necessary, the fiddly code
929 // can be found in PPCTargetLowering::LowerINT_TO_FP().
930 if (DstVT == MVT::f32 && !PPCSubTarget.hasFPCVT())
933 // Extend the input if necessary.
934 if (SrcVT == MVT::i8 || SrcVT == MVT::i16) {
935 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
936 if (!PPCEmitIntExt(SrcVT, SrcReg, MVT::i64, TmpReg, !IsSigned))
942 // Move the integer value to an FPR.
943 unsigned FPReg = PPCMoveToFPReg(SrcVT, SrcReg, IsSigned);
947 // Determine the opcode for the conversion.
948 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
949 unsigned DestReg = createResultReg(RC);
952 if (DstVT == MVT::f32)
953 Opc = IsSigned ? PPC::FCFIDS : PPC::FCFIDUS;
955 Opc = IsSigned ? PPC::FCFID : PPC::FCFIDU;
957 // Generate the convert.
958 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
961 UpdateValueMap(I, DestReg);
965 // Move the floating-point value in SrcReg into an integer destination
966 // register, and return the register (or zero if we can't handle it).
967 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
968 // those should be used instead of moving via a stack slot when the
969 // subtarget permits.
970 unsigned PPCFastISel::PPCMoveToIntReg(const Instruction *I, MVT VT,
971 unsigned SrcReg, bool IsSigned) {
972 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
973 // Note that if have STFIWX available, we could use a 4-byte stack
974 // slot for i32, but this being fast-isel we'll just go with the
975 // easiest code gen possible.
977 Addr.BaseType = Address::FrameIndexBase;
978 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
980 // Store the value from the FPR.
981 if (!PPCEmitStore(MVT::f64, SrcReg, Addr))
984 // Reload it into a GPR. If we want an i32, modify the address
985 // to have a 4-byte offset so we load from the right place.
989 // Look at the currently assigned register for this instruction
990 // to determine the required register class.
991 unsigned AssignedReg = FuncInfo.ValueMap[I];
992 const TargetRegisterClass *RC =
993 AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
995 unsigned ResultReg = 0;
996 if (!PPCEmitLoad(VT, ResultReg, Addr, RC, !IsSigned))
1002 // Attempt to fast-select a floating-point-to-integer conversion.
1003 bool PPCFastISel::SelectFPToI(const Instruction *I, bool IsSigned) {
1005 Type *DstTy = I->getType();
1006 if (!isTypeLegal(DstTy, DstVT))
1009 if (DstVT != MVT::i32 && DstVT != MVT::i64)
1012 Value *Src = I->getOperand(0);
1013 Type *SrcTy = Src->getType();
1014 if (!isTypeLegal(SrcTy, SrcVT))
1017 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
1020 unsigned SrcReg = getRegForValue(Src);
1024 // Convert f32 to f64 if necessary. This is just a meaningless copy
1025 // to get the register class right. COPY_TO_REGCLASS is needed since
1026 // a COPY from F4RC to F8RC is converted to a F4RC-F4RC copy downstream.
1027 const TargetRegisterClass *InRC = MRI.getRegClass(SrcReg);
1028 if (InRC == &PPC::F4RCRegClass) {
1029 unsigned TmpReg = createResultReg(&PPC::F8RCRegClass);
1030 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1031 TII.get(TargetOpcode::COPY_TO_REGCLASS), TmpReg)
1032 .addReg(SrcReg).addImm(PPC::F8RCRegClassID);
1036 // Determine the opcode for the conversion, which takes place
1037 // entirely within FPRs.
1038 unsigned DestReg = createResultReg(&PPC::F8RCRegClass);
1041 if (DstVT == MVT::i32)
1045 Opc = PPCSubTarget.hasFPCVT() ? PPC::FCTIWUZ : PPC::FCTIDZ;
1047 Opc = IsSigned ? PPC::FCTIDZ : PPC::FCTIDUZ;
1049 // Generate the convert.
1050 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1053 // Now move the integer value from a float register to an integer register.
1054 unsigned IntReg = PPCMoveToIntReg(I, DstVT, DestReg, IsSigned);
1058 UpdateValueMap(I, IntReg);
1062 // Attempt to fast-select a binary integer operation that isn't already
1063 // handled automatically.
1064 bool PPCFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1065 EVT DestVT = TLI.getValueType(I->getType(), true);
1067 // We can get here in the case when we have a binary operation on a non-legal
1068 // type and the target independent selector doesn't know how to handle it.
1069 if (DestVT != MVT::i16 && DestVT != MVT::i8)
1072 // Look at the currently assigned register for this instruction
1073 // to determine the required register class. If there is no register,
1074 // make a conservative choice (don't assign R0).
1075 unsigned AssignedReg = FuncInfo.ValueMap[I];
1076 const TargetRegisterClass *RC =
1077 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1078 &PPC::GPRC_and_GPRC_NOR0RegClass);
1079 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1082 switch (ISDOpcode) {
1083 default: return false;
1085 Opc = IsGPRC ? PPC::ADD4 : PPC::ADD8;
1088 Opc = IsGPRC ? PPC::OR : PPC::OR8;
1091 Opc = IsGPRC ? PPC::SUBF : PPC::SUBF8;
1095 unsigned ResultReg = createResultReg(RC ? RC : &PPC::G8RCRegClass);
1096 unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1097 if (SrcReg1 == 0) return false;
1099 // Handle case of small immediate operand.
1100 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(1))) {
1101 const APInt &CIVal = ConstInt->getValue();
1102 int Imm = (int)CIVal.getSExtValue();
1104 if (isInt<16>(Imm)) {
1107 llvm_unreachable("Missing case!");
1110 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1114 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1127 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1136 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1143 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1144 .addReg(SrcReg1).addImm(Imm);
1145 UpdateValueMap(I, ResultReg);
1152 unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1153 if (SrcReg2 == 0) return false;
1155 // Reverse operands for subtract-from.
1156 if (ISDOpcode == ISD::SUB)
1157 std::swap(SrcReg1, SrcReg2);
1159 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1160 .addReg(SrcReg1).addReg(SrcReg2);
1161 UpdateValueMap(I, ResultReg);
1165 // Handle arguments to a call that we're attempting to fast-select.
1166 // Return false if the arguments are too complex for us at the moment.
1167 bool PPCFastISel::processCallArgs(SmallVectorImpl<Value*> &Args,
1168 SmallVectorImpl<unsigned> &ArgRegs,
1169 SmallVectorImpl<MVT> &ArgVTs,
1170 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1171 SmallVectorImpl<unsigned> &RegArgs,
1175 SmallVector<CCValAssign, 16> ArgLocs;
1176 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, ArgLocs, *Context);
1177 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_PPC64_ELF_FIS);
1179 // Bail out if we can't handle any of the arguments.
1180 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1181 CCValAssign &VA = ArgLocs[I];
1182 MVT ArgVT = ArgVTs[VA.getValNo()];
1184 // Skip vector arguments for now, as well as long double and
1185 // uint128_t, and anything that isn't passed in a register.
1186 if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64 ||
1187 !VA.isRegLoc() || VA.needsCustom())
1190 // Skip bit-converted arguments for now.
1191 if (VA.getLocInfo() == CCValAssign::BCvt)
1195 // Get a count of how many bytes are to be pushed onto the stack.
1196 NumBytes = CCInfo.getNextStackOffset();
1198 // Issue CALLSEQ_START.
1199 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1200 TII.get(TII.getCallFrameSetupOpcode()))
1203 // Prepare to assign register arguments. Every argument uses up a
1204 // GPR protocol register even if it's passed in a floating-point
1206 unsigned NextGPR = PPC::X3;
1207 unsigned NextFPR = PPC::F1;
1209 // Process arguments.
1210 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1211 CCValAssign &VA = ArgLocs[I];
1212 unsigned Arg = ArgRegs[VA.getValNo()];
1213 MVT ArgVT = ArgVTs[VA.getValNo()];
1215 // Handle argument promotion and bitcasts.
1216 switch (VA.getLocInfo()) {
1218 llvm_unreachable("Unknown loc info!");
1219 case CCValAssign::Full:
1221 case CCValAssign::SExt: {
1222 MVT DestVT = VA.getLocVT();
1223 const TargetRegisterClass *RC =
1224 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1225 unsigned TmpReg = createResultReg(RC);
1226 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/false))
1227 llvm_unreachable("Failed to emit a sext!");
1232 case CCValAssign::AExt:
1233 case CCValAssign::ZExt: {
1234 MVT DestVT = VA.getLocVT();
1235 const TargetRegisterClass *RC =
1236 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1237 unsigned TmpReg = createResultReg(RC);
1238 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/true))
1239 llvm_unreachable("Failed to emit a zext!");
1244 case CCValAssign::BCvt: {
1245 // FIXME: Not yet handled.
1246 llvm_unreachable("Should have bailed before getting here!");
1251 // Copy this argument to the appropriate register.
1253 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) {
1259 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1260 ArgReg).addReg(Arg);
1261 RegArgs.push_back(ArgReg);
1267 // For a call that we've determined we can fast-select, finish the
1268 // call sequence and generate a copy to obtain the return value (if any).
1269 void PPCFastISel::finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1270 const Instruction *I, CallingConv::ID CC,
1271 unsigned &NumBytes, bool IsVarArg) {
1272 // Issue CallSEQ_END.
1273 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1274 TII.get(TII.getCallFrameDestroyOpcode()))
1275 .addImm(NumBytes).addImm(0);
1277 // Next, generate a copy to obtain the return value.
1278 // FIXME: No multi-register return values yet, though I don't foresee
1279 // any real difficulties there.
1280 if (RetVT != MVT::isVoid) {
1281 SmallVector<CCValAssign, 16> RVLocs;
1282 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
1283 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1284 CCValAssign &VA = RVLocs[0];
1285 assert(RVLocs.size() == 1 && "No support for multi-reg return values!");
1286 assert(VA.isRegLoc() && "Can only return in registers!");
1288 MVT DestVT = VA.getValVT();
1289 MVT CopyVT = DestVT;
1291 // Ints smaller than a register still arrive in a full 64-bit
1292 // register, so make sure we recognize this.
1293 if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32)
1296 unsigned SourcePhysReg = VA.getLocReg();
1297 unsigned ResultReg = 0;
1299 if (RetVT == CopyVT) {
1300 const TargetRegisterClass *CpyRC = TLI.getRegClassFor(CopyVT);
1301 ResultReg = createResultReg(CpyRC);
1303 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1304 TII.get(TargetOpcode::COPY), ResultReg)
1305 .addReg(SourcePhysReg);
1307 // If necessary, round the floating result to single precision.
1308 } else if (CopyVT == MVT::f64) {
1309 ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1310 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::FRSP),
1311 ResultReg).addReg(SourcePhysReg);
1313 // If only the low half of a general register is needed, generate
1314 // a GPRC copy instead of a G8RC copy. (EXTRACT_SUBREG can't be
1315 // used along the fast-isel path (not lowered), and downstream logic
1316 // also doesn't like a direct subreg copy on a physical reg.)
1317 } else if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32) {
1318 ResultReg = createResultReg(&PPC::GPRCRegClass);
1319 // Convert physical register from G8RC to GPRC.
1320 SourcePhysReg -= PPC::X0 - PPC::R0;
1321 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1322 TII.get(TargetOpcode::COPY), ResultReg)
1323 .addReg(SourcePhysReg);
1326 assert(ResultReg && "ResultReg unset!");
1327 UsedRegs.push_back(SourcePhysReg);
1328 UpdateValueMap(I, ResultReg);
1332 // Attempt to fast-select a call instruction.
1333 bool PPCFastISel::SelectCall(const Instruction *I) {
1334 const CallInst *CI = cast<CallInst>(I);
1335 const Value *Callee = CI->getCalledValue();
1337 // Can't handle inline asm.
1338 if (isa<InlineAsm>(Callee))
1341 // Allow SelectionDAG isel to handle tail calls.
1342 if (CI->isTailCall())
1345 // Obtain calling convention.
1346 ImmutableCallSite CS(CI);
1347 CallingConv::ID CC = CS.getCallingConv();
1349 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1350 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1351 bool IsVarArg = FTy->isVarArg();
1353 // Not ready for varargs yet.
1357 // Handle simple calls for now, with legal return types and
1358 // those that can be extended.
1359 Type *RetTy = I->getType();
1361 if (RetTy->isVoidTy())
1362 RetVT = MVT::isVoid;
1363 else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
1367 // FIXME: No multi-register return values yet.
1368 if (RetVT != MVT::isVoid && RetVT != MVT::i8 && RetVT != MVT::i16 &&
1369 RetVT != MVT::i32 && RetVT != MVT::i64 && RetVT != MVT::f32 &&
1370 RetVT != MVT::f64) {
1371 SmallVector<CCValAssign, 16> RVLocs;
1372 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
1373 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1374 if (RVLocs.size() > 1)
1378 // Bail early if more than 8 arguments, as we only currently
1379 // handle arguments passed in registers.
1380 unsigned NumArgs = CS.arg_size();
1384 // Set up the argument vectors.
1385 SmallVector<Value*, 8> Args;
1386 SmallVector<unsigned, 8> ArgRegs;
1387 SmallVector<MVT, 8> ArgVTs;
1388 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1390 Args.reserve(NumArgs);
1391 ArgRegs.reserve(NumArgs);
1392 ArgVTs.reserve(NumArgs);
1393 ArgFlags.reserve(NumArgs);
1395 for (ImmutableCallSite::arg_iterator II = CS.arg_begin(), IE = CS.arg_end();
1397 // FIXME: ARM does something for intrinsic calls here, check into that.
1399 unsigned AttrIdx = II - CS.arg_begin() + 1;
1401 // Only handle easy calls for now. It would be reasonably easy
1402 // to handle <= 8-byte structures passed ByVal in registers, but we
1403 // have to ensure they are right-justified in the register.
1404 if (CS.paramHasAttr(AttrIdx, Attribute::InReg) ||
1405 CS.paramHasAttr(AttrIdx, Attribute::StructRet) ||
1406 CS.paramHasAttr(AttrIdx, Attribute::Nest) ||
1407 CS.paramHasAttr(AttrIdx, Attribute::ByVal))
1410 ISD::ArgFlagsTy Flags;
1411 if (CS.paramHasAttr(AttrIdx, Attribute::SExt))
1413 if (CS.paramHasAttr(AttrIdx, Attribute::ZExt))
1416 Type *ArgTy = (*II)->getType();
1418 if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8)
1421 if (ArgVT.isVector())
1424 unsigned Arg = getRegForValue(*II);
1428 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1429 Flags.setOrigAlign(OriginalAlignment);
1431 Args.push_back(*II);
1432 ArgRegs.push_back(Arg);
1433 ArgVTs.push_back(ArgVT);
1434 ArgFlags.push_back(Flags);
1437 // Process the arguments.
1438 SmallVector<unsigned, 8> RegArgs;
1441 if (!processCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
1442 RegArgs, CC, NumBytes, IsVarArg))
1445 // FIXME: No handling for function pointers yet. This requires
1446 // implementing the function descriptor (OPD) setup.
1447 const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1451 // Build direct call with NOP for TOC restore.
1452 // FIXME: We can and should optimize away the NOP for local calls.
1453 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1454 TII.get(PPC::BL8_NOP));
1456 MIB.addGlobalAddress(GV);
1458 // Add implicit physical register uses to the call.
1459 for (unsigned II = 0, IE = RegArgs.size(); II != IE; ++II)
1460 MIB.addReg(RegArgs[II], RegState::Implicit);
1462 // Add a register mask with the call-preserved registers. Proper
1463 // defs for return values will be added by setPhysRegsDeadExcept().
1464 MIB.addRegMask(TRI.getCallPreservedMask(CC));
1466 // Finish off the call including any return values.
1467 SmallVector<unsigned, 4> UsedRegs;
1468 finishCall(RetVT, UsedRegs, I, CC, NumBytes, IsVarArg);
1470 // Set all unused physregs defs as dead.
1471 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1476 // Attempt to fast-select a return instruction.
1477 bool PPCFastISel::SelectRet(const Instruction *I) {
1479 if (!FuncInfo.CanLowerReturn)
1482 const ReturnInst *Ret = cast<ReturnInst>(I);
1483 const Function &F = *I->getParent()->getParent();
1485 // Build a list of return value registers.
1486 SmallVector<unsigned, 4> RetRegs;
1487 CallingConv::ID CC = F.getCallingConv();
1489 if (Ret->getNumOperands() > 0) {
1490 SmallVector<ISD::OutputArg, 4> Outs;
1491 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1493 // Analyze operands of the call, assigning locations to each operand.
1494 SmallVector<CCValAssign, 16> ValLocs;
1495 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs, *Context);
1496 CCInfo.AnalyzeReturn(Outs, RetCC_PPC64_ELF_FIS);
1497 const Value *RV = Ret->getOperand(0);
1499 // FIXME: Only one output register for now.
1500 if (ValLocs.size() > 1)
1503 // Special case for returning a constant integer of any size.
1504 // Materialize the constant as an i64 and copy it to the return
1505 // register. This avoids an unnecessary extend or truncate.
1506 if (isa<ConstantInt>(*RV)) {
1507 const Constant *C = cast<Constant>(RV);
1508 unsigned SrcReg = PPCMaterializeInt(C, MVT::i64);
1509 unsigned RetReg = ValLocs[0].getLocReg();
1510 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1511 RetReg).addReg(SrcReg);
1512 RetRegs.push_back(RetReg);
1515 unsigned Reg = getRegForValue(RV);
1520 // Copy the result values into the output registers.
1521 for (unsigned i = 0; i < ValLocs.size(); ++i) {
1523 CCValAssign &VA = ValLocs[i];
1524 assert(VA.isRegLoc() && "Can only return in registers!");
1525 RetRegs.push_back(VA.getLocReg());
1526 unsigned SrcReg = Reg + VA.getValNo();
1528 EVT RVEVT = TLI.getValueType(RV->getType());
1529 if (!RVEVT.isSimple())
1531 MVT RVVT = RVEVT.getSimpleVT();
1532 MVT DestVT = VA.getLocVT();
1534 if (RVVT != DestVT && RVVT != MVT::i8 &&
1535 RVVT != MVT::i16 && RVVT != MVT::i32)
1538 if (RVVT != DestVT) {
1539 switch (VA.getLocInfo()) {
1541 llvm_unreachable("Unknown loc info!");
1542 case CCValAssign::Full:
1543 llvm_unreachable("Full value assign but types don't match?");
1544 case CCValAssign::AExt:
1545 case CCValAssign::ZExt: {
1546 const TargetRegisterClass *RC =
1547 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1548 unsigned TmpReg = createResultReg(RC);
1549 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, true))
1554 case CCValAssign::SExt: {
1555 const TargetRegisterClass *RC =
1556 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1557 unsigned TmpReg = createResultReg(RC);
1558 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, false))
1566 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1567 TII.get(TargetOpcode::COPY), RetRegs[i])
1573 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1576 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1577 MIB.addReg(RetRegs[i], RegState::Implicit);
1582 // Attempt to emit an integer extend of SrcReg into DestReg. Both
1583 // signed and zero extensions are supported. Return false if we
1585 bool PPCFastISel::PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1586 unsigned DestReg, bool IsZExt) {
1587 if (DestVT != MVT::i32 && DestVT != MVT::i64)
1589 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 && SrcVT != MVT::i32)
1592 // Signed extensions use EXTSB, EXTSH, EXTSW.
1595 if (SrcVT == MVT::i8)
1596 Opc = (DestVT == MVT::i32) ? PPC::EXTSB : PPC::EXTSB8_32_64;
1597 else if (SrcVT == MVT::i16)
1598 Opc = (DestVT == MVT::i32) ? PPC::EXTSH : PPC::EXTSH8_32_64;
1600 assert(DestVT == MVT::i64 && "Signed extend from i32 to i32??");
1601 Opc = PPC::EXTSW_32_64;
1603 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1606 // Unsigned 32-bit extensions use RLWINM.
1607 } else if (DestVT == MVT::i32) {
1609 if (SrcVT == MVT::i8)
1612 assert(SrcVT == MVT::i16 && "Unsigned extend from i32 to i32??");
1615 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::RLWINM),
1617 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB).addImm(/*ME=*/31);
1619 // Unsigned 64-bit extensions use RLDICL (with a 32-bit source).
1622 if (SrcVT == MVT::i8)
1624 else if (SrcVT == MVT::i16)
1628 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1629 TII.get(PPC::RLDICL_32_64), DestReg)
1630 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB);
1636 // Attempt to fast-select an indirect branch instruction.
1637 bool PPCFastISel::SelectIndirectBr(const Instruction *I) {
1638 unsigned AddrReg = getRegForValue(I->getOperand(0));
1642 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::MTCTR8))
1644 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::BCTR8));
1646 const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1647 for (unsigned i = 0, e = IB->getNumSuccessors(); i != e; ++i)
1648 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[IB->getSuccessor(i)]);
1653 // Attempt to fast-select a compare instruction.
1654 bool PPCFastISel::SelectCmp(const Instruction *I) {
1655 const CmpInst *CI = cast<CmpInst>(I);
1656 Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
1660 unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
1662 if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
1666 UpdateValueMap(I, CondReg);
1670 // Attempt to fast-select an integer extend instruction.
1671 bool PPCFastISel::SelectIntExt(const Instruction *I) {
1672 Type *DestTy = I->getType();
1673 Value *Src = I->getOperand(0);
1674 Type *SrcTy = Src->getType();
1676 bool IsZExt = isa<ZExtInst>(I);
1677 unsigned SrcReg = getRegForValue(Src);
1678 if (!SrcReg) return false;
1680 EVT SrcEVT, DestEVT;
1681 SrcEVT = TLI.getValueType(SrcTy, true);
1682 DestEVT = TLI.getValueType(DestTy, true);
1683 if (!SrcEVT.isSimple())
1685 if (!DestEVT.isSimple())
1688 MVT SrcVT = SrcEVT.getSimpleVT();
1689 MVT DestVT = DestEVT.getSimpleVT();
1691 // If we know the register class needed for the result of this
1692 // instruction, use it. Otherwise pick the register class of the
1693 // correct size that does not contain X0/R0, since we don't know
1694 // whether downstream uses permit that assignment.
1695 unsigned AssignedReg = FuncInfo.ValueMap[I];
1696 const TargetRegisterClass *RC =
1697 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1698 (DestVT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
1699 &PPC::GPRC_and_GPRC_NOR0RegClass));
1700 unsigned ResultReg = createResultReg(RC);
1702 if (!PPCEmitIntExt(SrcVT, SrcReg, DestVT, ResultReg, IsZExt))
1705 UpdateValueMap(I, ResultReg);
1709 // Attempt to fast-select an instruction that wasn't handled by
1710 // the table-generated machinery.
1711 bool PPCFastISel::TargetSelectInstruction(const Instruction *I) {
1713 switch (I->getOpcode()) {
1714 case Instruction::Load:
1715 return SelectLoad(I);
1716 case Instruction::Store:
1717 return SelectStore(I);
1718 case Instruction::Br:
1719 return SelectBranch(I);
1720 case Instruction::IndirectBr:
1721 return SelectIndirectBr(I);
1722 case Instruction::FPExt:
1723 return SelectFPExt(I);
1724 case Instruction::FPTrunc:
1725 return SelectFPTrunc(I);
1726 case Instruction::SIToFP:
1727 return SelectIToFP(I, /*IsSigned*/ true);
1728 case Instruction::UIToFP:
1729 return SelectIToFP(I, /*IsSigned*/ false);
1730 case Instruction::FPToSI:
1731 return SelectFPToI(I, /*IsSigned*/ true);
1732 case Instruction::FPToUI:
1733 return SelectFPToI(I, /*IsSigned*/ false);
1734 case Instruction::Add:
1735 return SelectBinaryIntOp(I, ISD::ADD);
1736 case Instruction::Or:
1737 return SelectBinaryIntOp(I, ISD::OR);
1738 case Instruction::Sub:
1739 return SelectBinaryIntOp(I, ISD::SUB);
1740 case Instruction::Call:
1741 if (dyn_cast<IntrinsicInst>(I))
1743 return SelectCall(I);
1744 case Instruction::Ret:
1745 return SelectRet(I);
1746 case Instruction::ZExt:
1747 case Instruction::SExt:
1748 return SelectIntExt(I);
1749 // Here add other flavors of Instruction::XXX that automated
1750 // cases don't catch. For example, switches are terminators
1751 // that aren't yet handled.
1758 // Materialize a floating-point constant into a register, and return
1759 // the register number (or zero if we failed to handle it).
1760 unsigned PPCFastISel::PPCMaterializeFP(const ConstantFP *CFP, MVT VT) {
1761 // No plans to handle long double here.
1762 if (VT != MVT::f32 && VT != MVT::f64)
1765 // All FP constants are loaded from the constant pool.
1766 unsigned Align = TD.getPrefTypeAlignment(CFP->getType());
1767 assert(Align > 0 && "Unexpectedly missing alignment information!");
1768 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
1769 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
1770 CodeModel::Model CModel = TM.getCodeModel();
1772 MachineMemOperand *MMO =
1773 FuncInfo.MF->getMachineMemOperand(
1774 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
1775 (VT == MVT::f32) ? 4 : 8, Align);
1777 unsigned Opc = (VT == MVT::f32) ? PPC::LFS : PPC::LFD;
1778 unsigned TmpReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1780 // For small code model, generate a LF[SD](0, LDtocCPT(Idx, X2)).
1781 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault) {
1782 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocCPT),
1784 .addConstantPoolIndex(Idx).addReg(PPC::X2);
1785 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1786 .addImm(0).addReg(TmpReg).addMemOperand(MMO);
1788 // Otherwise we generate LF[SD](Idx[lo], ADDIStocHA(X2, Idx)).
1789 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDIStocHA),
1790 TmpReg).addReg(PPC::X2).addConstantPoolIndex(Idx);
1791 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1792 .addConstantPoolIndex(Idx, 0, PPCII::MO_TOC_LO)
1794 .addMemOperand(MMO);
1800 // Materialize the address of a global value into a register, and return
1801 // the register number (or zero if we failed to handle it).
1802 unsigned PPCFastISel::PPCMaterializeGV(const GlobalValue *GV, MVT VT) {
1803 assert(VT == MVT::i64 && "Non-address!");
1804 const TargetRegisterClass *RC = &PPC::G8RC_and_G8RC_NOX0RegClass;
1805 unsigned DestReg = createResultReg(RC);
1807 // Global values may be plain old object addresses, TLS object
1808 // addresses, constant pool entries, or jump tables. How we generate
1809 // code for these may depend on small, medium, or large code model.
1810 CodeModel::Model CModel = TM.getCodeModel();
1812 // FIXME: Jump tables are not yet required because fast-isel doesn't
1813 // handle switches; if that changes, we need them as well. For now,
1814 // what follows assumes everything's a generic (or TLS) global address.
1815 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1817 // If GV is an alias, use the aliasee for determining thread-locality.
1818 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1819 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
1822 // FIXME: We don't yet handle the complexity of TLS.
1823 bool IsTLS = GVar && GVar->isThreadLocal();
1827 // For small code model, generate a simple TOC load.
1828 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault)
1829 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtoc), DestReg)
1830 .addGlobalAddress(GV).addReg(PPC::X2);
1832 // If the address is an externally defined symbol, a symbol with
1833 // common or externally available linkage, a function address, or a
1834 // jump table address (not yet needed), or if we are generating code
1835 // for large code model, we generate:
1836 // LDtocL(GV, ADDIStocHA(%X2, GV))
1837 // Otherwise we generate:
1838 // ADDItocL(ADDIStocHA(%X2, GV), GV)
1839 // Either way, start with the ADDIStocHA:
1840 unsigned HighPartReg = createResultReg(RC);
1841 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDIStocHA),
1842 HighPartReg).addReg(PPC::X2).addGlobalAddress(GV);
1844 // !GVar implies a function address. An external variable is one
1845 // without an initializer.
1846 // If/when switches are implemented, jump tables should be handled
1847 // on the "if" path here.
1848 if (CModel == CodeModel::Large || !GVar || !GVar->hasInitializer() ||
1849 GVar->hasCommonLinkage() || GVar->hasAvailableExternallyLinkage())
1850 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocL),
1851 DestReg).addGlobalAddress(GV).addReg(HighPartReg);
1853 // Otherwise generate the ADDItocL.
1854 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDItocL),
1855 DestReg).addReg(HighPartReg).addGlobalAddress(GV);
1861 // Materialize a 32-bit integer constant into a register, and return
1862 // the register number (or zero if we failed to handle it).
1863 unsigned PPCFastISel::PPCMaterialize32BitInt(int64_t Imm,
1864 const TargetRegisterClass *RC) {
1865 unsigned Lo = Imm & 0xFFFF;
1866 unsigned Hi = (Imm >> 16) & 0xFFFF;
1868 unsigned ResultReg = createResultReg(RC);
1869 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1872 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1873 TII.get(IsGPRC ? PPC::LI : PPC::LI8), ResultReg)
1876 // Both Lo and Hi have nonzero bits.
1877 unsigned TmpReg = createResultReg(RC);
1878 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1879 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), TmpReg)
1881 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1882 TII.get(IsGPRC ? PPC::ORI : PPC::ORI8), ResultReg)
1883 .addReg(TmpReg).addImm(Lo);
1886 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1887 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), ResultReg)
1893 // Materialize a 64-bit integer constant into a register, and return
1894 // the register number (or zero if we failed to handle it).
1895 unsigned PPCFastISel::PPCMaterialize64BitInt(int64_t Imm,
1896 const TargetRegisterClass *RC) {
1897 unsigned Remainder = 0;
1900 // If the value doesn't fit in 32 bits, see if we can shift it
1901 // so that it fits in 32 bits.
1902 if (!isInt<32>(Imm)) {
1903 Shift = countTrailingZeros<uint64_t>(Imm);
1904 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
1906 if (isInt<32>(ImmSh))
1915 // Handle the high-order 32 bits (if shifted) or the whole 32 bits
1916 // (if not shifted).
1917 unsigned TmpReg1 = PPCMaterialize32BitInt(Imm, RC);
1921 // If upper 32 bits were not zero, we've built them and need to shift
1925 TmpReg2 = createResultReg(RC);
1926 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::RLDICR),
1927 TmpReg2).addReg(TmpReg1).addImm(Shift).addImm(63 - Shift);
1931 unsigned TmpReg3, Hi, Lo;
1932 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
1933 TmpReg3 = createResultReg(RC);
1934 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ORIS8),
1935 TmpReg3).addReg(TmpReg2).addImm(Hi);
1939 if ((Lo = Remainder & 0xFFFF)) {
1940 unsigned ResultReg = createResultReg(RC);
1941 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ORI8),
1942 ResultReg).addReg(TmpReg3).addImm(Lo);
1950 // Materialize an integer constant into a register, and return
1951 // the register number (or zero if we failed to handle it).
1952 unsigned PPCFastISel::PPCMaterializeInt(const Constant *C, MVT VT) {
1954 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
1955 VT != MVT::i8 && VT != MVT::i1)
1958 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
1959 &PPC::GPRCRegClass);
1961 // If the constant is in range, use a load-immediate.
1962 const ConstantInt *CI = cast<ConstantInt>(C);
1963 if (isInt<16>(CI->getSExtValue())) {
1964 unsigned Opc = (VT == MVT::i64) ? PPC::LI8 : PPC::LI;
1965 unsigned ImmReg = createResultReg(RC);
1966 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ImmReg)
1967 .addImm(CI->getSExtValue());
1971 // Construct the constant piecewise.
1972 int64_t Imm = CI->getZExtValue();
1975 return PPCMaterialize64BitInt(Imm, RC);
1976 else if (VT == MVT::i32)
1977 return PPCMaterialize32BitInt(Imm, RC);
1982 // Materialize a constant into a register, and return the register
1983 // number (or zero if we failed to handle it).
1984 unsigned PPCFastISel::TargetMaterializeConstant(const Constant *C) {
1985 EVT CEVT = TLI.getValueType(C->getType(), true);
1987 // Only handle simple types.
1988 if (!CEVT.isSimple()) return 0;
1989 MVT VT = CEVT.getSimpleVT();
1991 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1992 return PPCMaterializeFP(CFP, VT);
1993 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1994 return PPCMaterializeGV(GV, VT);
1995 else if (isa<ConstantInt>(C))
1996 return PPCMaterializeInt(C, VT);
1997 // TBD: Global values.
2002 // Materialize the address created by an alloca into a register, and
2003 // return the register number (or zero if we failed to handle it). TBD.
2004 unsigned PPCFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
2008 // Fold loads into extends when possible.
2009 // FIXME: We can have multiple redundant extend/trunc instructions
2010 // following a load. The folding only picks up one. Extend this
2011 // to check subsequent instructions for the same pattern and remove
2012 // them. Thus ResultReg should be the def reg for the last redundant
2013 // instruction in a chain, and all intervening instructions can be
2014 // removed from parent. Change test/CodeGen/PowerPC/fast-isel-fold.ll
2015 // to add ELF64-NOT: rldicl to the appropriate tests when this works.
2016 bool PPCFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2017 const LoadInst *LI) {
2018 // Verify we have a legal type before going any further.
2020 if (!isLoadTypeLegal(LI->getType(), VT))
2023 // Combine load followed by zero- or sign-extend.
2024 bool IsZExt = false;
2025 switch(MI->getOpcode()) {
2030 case PPC::RLDICL_32_64: {
2032 unsigned MB = MI->getOperand(3).getImm();
2033 if ((VT == MVT::i8 && MB <= 56) ||
2034 (VT == MVT::i16 && MB <= 48) ||
2035 (VT == MVT::i32 && MB <= 32))
2041 case PPC::RLWINM8: {
2043 unsigned MB = MI->getOperand(3).getImm();
2044 if ((VT == MVT::i8 && MB <= 24) ||
2045 (VT == MVT::i16 && MB <= 16))
2052 case PPC::EXTSB8_32_64:
2053 /* There is no sign-extending load-byte instruction. */
2058 case PPC::EXTSH8_32_64: {
2059 if (VT != MVT::i16 && VT != MVT::i8)
2065 case PPC::EXTSW_32_64: {
2066 if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8)
2072 // See if we can handle this address.
2074 if (!PPCComputeAddress(LI->getOperand(0), Addr))
2077 unsigned ResultReg = MI->getOperand(0).getReg();
2079 if (!PPCEmitLoad(VT, ResultReg, Addr, 0, IsZExt))
2082 MI->eraseFromParent();
2086 // Attempt to lower call arguments in a faster way than done by
2087 // the selection DAG code.
2088 bool PPCFastISel::FastLowerArguments() {
2089 // Defer to normal argument lowering for now. It's reasonably
2090 // efficient. Consider doing something like ARM to handle the
2091 // case where all args fit in registers, no varargs, no float
2096 // Handle materializing integer constants into a register. This is not
2097 // automatically generated for PowerPC, so must be explicitly created here.
2098 unsigned PPCFastISel::FastEmit_i(MVT Ty, MVT VT, unsigned Opc, uint64_t Imm) {
2100 if (Opc != ISD::Constant)
2103 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2104 VT != MVT::i8 && VT != MVT::i1)
2107 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2108 &PPC::GPRCRegClass);
2110 return PPCMaterialize64BitInt(Imm, RC);
2112 return PPCMaterialize32BitInt(Imm, RC);
2115 // Override for ADDI and ADDI8 to set the correct register class
2116 // on RHS operand 0. The automatic infrastructure naively assumes
2117 // GPRC for i32 and G8RC for i64; the concept of "no R0" is lost
2118 // for these cases. At the moment, none of the other automatically
2119 // generated RI instructions require special treatment. However, once
2120 // SelectSelect is implemented, "isel" requires similar handling.
2122 // Also be conservative about the output register class. Avoid
2123 // assigning R0 or X0 to the output register for GPRC and G8RC
2124 // register classes, as any such result could be used in ADDI, etc.,
2125 // where those regs have another meaning.
2126 unsigned PPCFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
2127 const TargetRegisterClass *RC,
2128 unsigned Op0, bool Op0IsKill,
2130 if (MachineInstOpcode == PPC::ADDI)
2131 MRI.setRegClass(Op0, &PPC::GPRC_and_GPRC_NOR0RegClass);
2132 else if (MachineInstOpcode == PPC::ADDI8)
2133 MRI.setRegClass(Op0, &PPC::G8RC_and_G8RC_NOX0RegClass);
2135 const TargetRegisterClass *UseRC =
2136 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2137 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2139 return FastISel::FastEmitInst_ri(MachineInstOpcode, UseRC,
2140 Op0, Op0IsKill, Imm);
2143 // Override for instructions with one register operand to avoid use of
2144 // R0/X0. The automatic infrastructure isn't aware of the context so
2145 // we must be conservative.
2146 unsigned PPCFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
2147 const TargetRegisterClass* RC,
2148 unsigned Op0, bool Op0IsKill) {
2149 const TargetRegisterClass *UseRC =
2150 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2151 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2153 return FastISel::FastEmitInst_r(MachineInstOpcode, UseRC, Op0, Op0IsKill);
2156 // Override for instructions with two register operands to avoid use
2157 // of R0/X0. The automatic infrastructure isn't aware of the context
2158 // so we must be conservative.
2159 unsigned PPCFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
2160 const TargetRegisterClass* RC,
2161 unsigned Op0, bool Op0IsKill,
2162 unsigned Op1, bool Op1IsKill) {
2163 const TargetRegisterClass *UseRC =
2164 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2165 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2167 return FastISel::FastEmitInst_rr(MachineInstOpcode, UseRC, Op0, Op0IsKill,
2172 // Create the fast instruction selector for PowerPC64 ELF.
2173 FastISel *PPC::createFastISel(FunctionLoweringInfo &FuncInfo,
2174 const TargetLibraryInfo *LibInfo) {
2175 const TargetMachine &TM = FuncInfo.MF->getTarget();
2177 // Only available on 64-bit ELF for now.
2178 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
2179 if (Subtarget->isPPC64() && Subtarget->isSVR4ABI())
2180 return new PPCFastISel(FuncInfo, LibInfo);