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 //===----------------------------------------------------------------------===//
17 #include "MCTargetDesc/PPCPredicates.h"
18 #include "PPCISelLowering.h"
19 #include "PPCSubtarget.h"
20 #include "PPCTargetMachine.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/FastISel.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/GetElementPtrTypeIterator.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/Target/TargetLowering.h"
37 #include "llvm/Target/TargetMachine.h"
39 //===----------------------------------------------------------------------===//
42 // fastLowerArguments: Handle simple cases.
43 // PPCMaterializeGV: Handle TLS.
44 // SelectCall: Handle function pointers.
45 // SelectCall: Handle multi-register return values.
46 // SelectCall: Optimize away nops for local calls.
47 // processCallArgs: Handle bit-converted arguments.
48 // finishCall: Handle multi-register return values.
49 // PPCComputeAddress: Handle parameter references as FrameIndex's.
50 // PPCEmitCmp: Handle immediate as operand 1.
51 // SelectCall: Handle small byval arguments.
52 // SelectIntrinsicCall: Implement.
53 // SelectSelect: Implement.
54 // Consider factoring isTypeLegal into the base class.
55 // Implement switches and jump tables.
57 //===----------------------------------------------------------------------===//
60 #define DEBUG_TYPE "ppcfastisel"
64 typedef struct Address {
77 // Innocuous defaults for our address.
79 : BaseType(RegBase), Offset(0) {
84 class PPCFastISel final : public FastISel {
86 const TargetMachine &TM;
87 const TargetInstrInfo &TII;
88 const TargetLowering &TLI;
89 const PPCSubtarget *PPCSubTarget;
93 explicit PPCFastISel(FunctionLoweringInfo &FuncInfo,
94 const TargetLibraryInfo *LibInfo)
95 : FastISel(FuncInfo, LibInfo), TM(FuncInfo.MF->getTarget()),
96 TII(*TM.getSubtargetImpl()->getInstrInfo()),
97 TLI(*TM.getSubtargetImpl()->getTargetLowering()),
98 PPCSubTarget(&TM.getSubtarget<PPCSubtarget>()),
99 Context(&FuncInfo.Fn->getContext()) {}
101 // Backend specific FastISel code.
103 bool fastSelectInstruction(const Instruction *I) override;
104 unsigned fastMaterializeConstant(const Constant *C) override;
105 unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
106 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
107 const LoadInst *LI) override;
108 bool fastLowerArguments() override;
109 unsigned fastEmit_i(MVT Ty, MVT RetTy, unsigned Opc, uint64_t Imm) override;
110 unsigned fastEmitInst_ri(unsigned MachineInstOpcode,
111 const TargetRegisterClass *RC,
112 unsigned Op0, bool Op0IsKill,
114 unsigned fastEmitInst_r(unsigned MachineInstOpcode,
115 const TargetRegisterClass *RC,
116 unsigned Op0, bool Op0IsKill);
117 unsigned fastEmitInst_rr(unsigned MachineInstOpcode,
118 const TargetRegisterClass *RC,
119 unsigned Op0, bool Op0IsKill,
120 unsigned Op1, bool Op1IsKill);
122 // Instruction selection routines.
124 bool SelectLoad(const Instruction *I);
125 bool SelectStore(const Instruction *I);
126 bool SelectBranch(const Instruction *I);
127 bool SelectIndirectBr(const Instruction *I);
128 bool SelectFPExt(const Instruction *I);
129 bool SelectFPTrunc(const Instruction *I);
130 bool SelectIToFP(const Instruction *I, bool IsSigned);
131 bool SelectFPToI(const Instruction *I, bool IsSigned);
132 bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
133 bool SelectCall(const Instruction *I);
134 bool SelectRet(const Instruction *I);
135 bool SelectTrunc(const Instruction *I);
136 bool SelectIntExt(const Instruction *I);
140 bool isTypeLegal(Type *Ty, MVT &VT);
141 bool isLoadTypeLegal(Type *Ty, MVT &VT);
142 bool PPCEmitCmp(const Value *Src1Value, const Value *Src2Value,
143 bool isZExt, unsigned DestReg);
144 bool PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
145 const TargetRegisterClass *RC, bool IsZExt = true,
146 unsigned FP64LoadOpc = PPC::LFD);
147 bool PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr);
148 bool PPCComputeAddress(const Value *Obj, Address &Addr);
149 void PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
151 bool PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
152 unsigned DestReg, bool IsZExt);
153 unsigned PPCMaterializeFP(const ConstantFP *CFP, MVT VT);
154 unsigned PPCMaterializeGV(const GlobalValue *GV, MVT VT);
155 unsigned PPCMaterializeInt(const Constant *C, MVT VT, bool UseSExt = true);
156 unsigned PPCMaterialize32BitInt(int64_t Imm,
157 const TargetRegisterClass *RC);
158 unsigned PPCMaterialize64BitInt(int64_t Imm,
159 const TargetRegisterClass *RC);
160 unsigned PPCMoveToIntReg(const Instruction *I, MVT VT,
161 unsigned SrcReg, bool IsSigned);
162 unsigned PPCMoveToFPReg(MVT VT, unsigned SrcReg, bool IsSigned);
164 // Call handling routines.
166 bool processCallArgs(SmallVectorImpl<Value*> &Args,
167 SmallVectorImpl<unsigned> &ArgRegs,
168 SmallVectorImpl<MVT> &ArgVTs,
169 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
170 SmallVectorImpl<unsigned> &RegArgs,
174 void finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
175 const Instruction *I, CallingConv::ID CC,
176 unsigned &NumBytes, bool IsVarArg);
177 CCAssignFn *usePPC32CCs(unsigned Flag);
180 #include "PPCGenFastISel.inc"
184 } // end anonymous namespace
186 #include "PPCGenCallingConv.inc"
188 // Function whose sole purpose is to kill compiler warnings
189 // stemming from unused functions included from PPCGenCallingConv.inc.
190 CCAssignFn *PPCFastISel::usePPC32CCs(unsigned Flag) {
192 return CC_PPC32_SVR4;
194 return CC_PPC32_SVR4_ByVal;
196 return CC_PPC32_SVR4_VarArg;
201 static Optional<PPC::Predicate> getComparePred(CmpInst::Predicate Pred) {
203 // These are not representable with any single compare.
204 case CmpInst::FCMP_FALSE:
205 case CmpInst::FCMP_UEQ:
206 case CmpInst::FCMP_UGT:
207 case CmpInst::FCMP_UGE:
208 case CmpInst::FCMP_ULT:
209 case CmpInst::FCMP_ULE:
210 case CmpInst::FCMP_UNE:
211 case CmpInst::FCMP_TRUE:
213 return Optional<PPC::Predicate>();
215 case CmpInst::FCMP_OEQ:
216 case CmpInst::ICMP_EQ:
219 case CmpInst::FCMP_OGT:
220 case CmpInst::ICMP_UGT:
221 case CmpInst::ICMP_SGT:
224 case CmpInst::FCMP_OGE:
225 case CmpInst::ICMP_UGE:
226 case CmpInst::ICMP_SGE:
229 case CmpInst::FCMP_OLT:
230 case CmpInst::ICMP_ULT:
231 case CmpInst::ICMP_SLT:
234 case CmpInst::FCMP_OLE:
235 case CmpInst::ICMP_ULE:
236 case CmpInst::ICMP_SLE:
239 case CmpInst::FCMP_ONE:
240 case CmpInst::ICMP_NE:
243 case CmpInst::FCMP_ORD:
246 case CmpInst::FCMP_UNO:
251 // Determine whether the type Ty is simple enough to be handled by
252 // fast-isel, and return its equivalent machine type in VT.
253 // FIXME: Copied directly from ARM -- factor into base class?
254 bool PPCFastISel::isTypeLegal(Type *Ty, MVT &VT) {
255 EVT Evt = TLI.getValueType(Ty, true);
257 // Only handle simple types.
258 if (Evt == MVT::Other || !Evt.isSimple()) return false;
259 VT = Evt.getSimpleVT();
261 // Handle all legal types, i.e. a register that will directly hold this
263 return TLI.isTypeLegal(VT);
266 // Determine whether the type Ty is simple enough to be handled by
267 // fast-isel as a load target, and return its equivalent machine type in VT.
268 bool PPCFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
269 if (isTypeLegal(Ty, VT)) return true;
271 // If this is a type than can be sign or zero-extended to a basic operation
272 // go ahead and accept it now.
273 if (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) {
280 // Given a value Obj, create an Address object Addr that represents its
281 // address. Return false if we can't handle it.
282 bool PPCFastISel::PPCComputeAddress(const Value *Obj, Address &Addr) {
283 const User *U = nullptr;
284 unsigned Opcode = Instruction::UserOp1;
285 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
286 // Don't walk into other basic blocks unless the object is an alloca from
287 // another block, otherwise it may not have a virtual register assigned.
288 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
289 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
290 Opcode = I->getOpcode();
293 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
294 Opcode = C->getOpcode();
301 case Instruction::BitCast:
302 // Look through bitcasts.
303 return PPCComputeAddress(U->getOperand(0), Addr);
304 case Instruction::IntToPtr:
305 // Look past no-op inttoptrs.
306 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
307 return PPCComputeAddress(U->getOperand(0), Addr);
309 case Instruction::PtrToInt:
310 // Look past no-op ptrtoints.
311 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
312 return PPCComputeAddress(U->getOperand(0), Addr);
314 case Instruction::GetElementPtr: {
315 Address SavedAddr = Addr;
316 long TmpOffset = Addr.Offset;
318 // Iterate through the GEP folding the constants into offsets where
320 gep_type_iterator GTI = gep_type_begin(U);
321 for (User::const_op_iterator II = U->op_begin() + 1, IE = U->op_end();
322 II != IE; ++II, ++GTI) {
323 const Value *Op = *II;
324 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
325 const StructLayout *SL = DL.getStructLayout(STy);
326 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
327 TmpOffset += SL->getElementOffset(Idx);
329 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
331 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
332 // Constant-offset addressing.
333 TmpOffset += CI->getSExtValue() * S;
336 if (canFoldAddIntoGEP(U, Op)) {
337 // A compatible add with a constant operand. Fold the constant.
339 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
340 TmpOffset += CI->getSExtValue() * S;
341 // Iterate on the other operand.
342 Op = cast<AddOperator>(Op)->getOperand(0);
346 goto unsupported_gep;
351 // Try to grab the base operand now.
352 Addr.Offset = TmpOffset;
353 if (PPCComputeAddress(U->getOperand(0), Addr)) return true;
355 // We failed, restore everything and try the other options.
361 case Instruction::Alloca: {
362 const AllocaInst *AI = cast<AllocaInst>(Obj);
363 DenseMap<const AllocaInst*, int>::iterator SI =
364 FuncInfo.StaticAllocaMap.find(AI);
365 if (SI != FuncInfo.StaticAllocaMap.end()) {
366 Addr.BaseType = Address::FrameIndexBase;
367 Addr.Base.FI = SI->second;
374 // FIXME: References to parameters fall through to the behavior
375 // below. They should be able to reference a frame index since
376 // they are stored to the stack, so we can get "ld rx, offset(r1)"
377 // instead of "addi ry, r1, offset / ld rx, 0(ry)". Obj will
378 // just contain the parameter. Try to handle this with a FI.
380 // Try to get this in a register if nothing else has worked.
381 if (Addr.Base.Reg == 0)
382 Addr.Base.Reg = getRegForValue(Obj);
384 // Prevent assignment of base register to X0, which is inappropriate
385 // for loads and stores alike.
386 if (Addr.Base.Reg != 0)
387 MRI.setRegClass(Addr.Base.Reg, &PPC::G8RC_and_G8RC_NOX0RegClass);
389 return Addr.Base.Reg != 0;
392 // Fix up some addresses that can't be used directly. For example, if
393 // an offset won't fit in an instruction field, we may need to move it
394 // into an index register.
395 void PPCFastISel::PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
396 unsigned &IndexReg) {
398 // Check whether the offset fits in the instruction field.
399 if (!isInt<16>(Addr.Offset))
402 // If this is a stack pointer and the offset needs to be simplified then
403 // put the alloca address into a register, set the base type back to
404 // register and continue. This should almost never happen.
405 if (!UseOffset && Addr.BaseType == Address::FrameIndexBase) {
406 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
407 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDI8),
408 ResultReg).addFrameIndex(Addr.Base.FI).addImm(0);
409 Addr.Base.Reg = ResultReg;
410 Addr.BaseType = Address::RegBase;
414 IntegerType *OffsetTy = ((VT == MVT::i32) ? Type::getInt32Ty(*Context)
415 : Type::getInt64Ty(*Context));
416 const ConstantInt *Offset =
417 ConstantInt::getSigned(OffsetTy, (int64_t)(Addr.Offset));
418 IndexReg = PPCMaterializeInt(Offset, MVT::i64);
419 assert(IndexReg && "Unexpected error in PPCMaterializeInt!");
423 // Emit a load instruction if possible, returning true if we succeeded,
424 // otherwise false. See commentary below for how the register class of
425 // the load is determined.
426 bool PPCFastISel::PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
427 const TargetRegisterClass *RC,
428 bool IsZExt, unsigned FP64LoadOpc) {
430 bool UseOffset = true;
432 // If ResultReg is given, it determines the register class of the load.
433 // Otherwise, RC is the register class to use. If the result of the
434 // load isn't anticipated in this block, both may be zero, in which
435 // case we must make a conservative guess. In particular, don't assign
436 // R0 or X0 to the result register, as the result may be used in a load,
437 // store, add-immediate, or isel that won't permit this. (Though
438 // perhaps the spill and reload of live-exit values would handle this?)
439 const TargetRegisterClass *UseRC =
440 (ResultReg ? MRI.getRegClass(ResultReg) :
442 (VT == MVT::f64 ? &PPC::F8RCRegClass :
443 (VT == MVT::f32 ? &PPC::F4RCRegClass :
444 (VT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
445 &PPC::GPRC_and_GPRC_NOR0RegClass)))));
447 bool Is32BitInt = UseRC->hasSuperClassEq(&PPC::GPRCRegClass);
449 switch (VT.SimpleTy) {
450 default: // e.g., vector types not handled
453 Opc = Is32BitInt ? PPC::LBZ : PPC::LBZ8;
457 (Is32BitInt ? PPC::LHZ : PPC::LHZ8) :
458 (Is32BitInt ? PPC::LHA : PPC::LHA8));
462 (Is32BitInt ? PPC::LWZ : PPC::LWZ8) :
463 (Is32BitInt ? PPC::LWA_32 : PPC::LWA));
464 if ((Opc == PPC::LWA || Opc == PPC::LWA_32) && ((Addr.Offset & 3) != 0))
469 assert(UseRC->hasSuperClassEq(&PPC::G8RCRegClass) &&
470 "64-bit load with 32-bit target??");
471 UseOffset = ((Addr.Offset & 3) == 0);
481 // If necessary, materialize the offset into a register and use
482 // the indexed form. Also handle stack pointers with special needs.
483 unsigned IndexReg = 0;
484 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
486 ResultReg = createResultReg(UseRC);
488 // Note: If we still have a frame index here, we know the offset is
489 // in range, as otherwise PPCSimplifyAddress would have converted it
491 if (Addr.BaseType == Address::FrameIndexBase) {
493 MachineMemOperand *MMO =
494 FuncInfo.MF->getMachineMemOperand(
495 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
496 MachineMemOperand::MOLoad, MFI.getObjectSize(Addr.Base.FI),
497 MFI.getObjectAlignment(Addr.Base.FI));
499 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
500 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
502 // Base reg with offset in range.
503 } else if (UseOffset) {
505 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
506 .addImm(Addr.Offset).addReg(Addr.Base.Reg);
510 // Get the RR opcode corresponding to the RI one. FIXME: It would be
511 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
512 // is hard to get at.
514 default: llvm_unreachable("Unexpected opcode!");
515 case PPC::LBZ: Opc = PPC::LBZX; break;
516 case PPC::LBZ8: Opc = PPC::LBZX8; break;
517 case PPC::LHZ: Opc = PPC::LHZX; break;
518 case PPC::LHZ8: Opc = PPC::LHZX8; break;
519 case PPC::LHA: Opc = PPC::LHAX; break;
520 case PPC::LHA8: Opc = PPC::LHAX8; break;
521 case PPC::LWZ: Opc = PPC::LWZX; break;
522 case PPC::LWZ8: Opc = PPC::LWZX8; break;
523 case PPC::LWA: Opc = PPC::LWAX; break;
524 case PPC::LWA_32: Opc = PPC::LWAX_32; break;
525 case PPC::LD: Opc = PPC::LDX; break;
526 case PPC::LFS: Opc = PPC::LFSX; break;
527 case PPC::LFD: Opc = PPC::LFDX; break;
529 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
530 .addReg(Addr.Base.Reg).addReg(IndexReg);
536 // Attempt to fast-select a load instruction.
537 bool PPCFastISel::SelectLoad(const Instruction *I) {
538 // FIXME: No atomic loads are supported.
539 if (cast<LoadInst>(I)->isAtomic())
542 // Verify we have a legal type before going any further.
544 if (!isLoadTypeLegal(I->getType(), VT))
547 // See if we can handle this address.
549 if (!PPCComputeAddress(I->getOperand(0), Addr))
552 // Look at the currently assigned register for this instruction
553 // to determine the required register class. This is necessary
554 // to constrain RA from using R0/X0 when this is not legal.
555 unsigned AssignedReg = FuncInfo.ValueMap[I];
556 const TargetRegisterClass *RC =
557 AssignedReg ? MRI.getRegClass(AssignedReg) : nullptr;
559 unsigned ResultReg = 0;
560 if (!PPCEmitLoad(VT, ResultReg, Addr, RC))
562 updateValueMap(I, ResultReg);
566 // Emit a store instruction to store SrcReg at Addr.
567 bool PPCFastISel::PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr) {
568 assert(SrcReg && "Nothing to store!");
570 bool UseOffset = true;
572 const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
573 bool Is32BitInt = RC->hasSuperClassEq(&PPC::GPRCRegClass);
575 switch (VT.SimpleTy) {
576 default: // e.g., vector types not handled
579 Opc = Is32BitInt ? PPC::STB : PPC::STB8;
582 Opc = Is32BitInt ? PPC::STH : PPC::STH8;
585 assert(Is32BitInt && "Not GPRC for i32??");
590 UseOffset = ((Addr.Offset & 3) == 0);
600 // If necessary, materialize the offset into a register and use
601 // the indexed form. Also handle stack pointers with special needs.
602 unsigned IndexReg = 0;
603 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
605 // Note: If we still have a frame index here, we know the offset is
606 // in range, as otherwise PPCSimplifyAddress would have converted it
608 if (Addr.BaseType == Address::FrameIndexBase) {
609 MachineMemOperand *MMO =
610 FuncInfo.MF->getMachineMemOperand(
611 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
612 MachineMemOperand::MOStore, MFI.getObjectSize(Addr.Base.FI),
613 MFI.getObjectAlignment(Addr.Base.FI));
615 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
618 .addFrameIndex(Addr.Base.FI)
621 // Base reg with offset in range.
622 } else if (UseOffset)
623 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 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, DbgLoc, 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, DbgLoc, TII.get(PPC::BCC))
708 .addImm(PPCPred).addReg(CondReg).addMBB(TBB);
709 fastEmitBranch(FBB, DbgLoc);
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, DbgLoc);
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 if (SrcVT == MVT::i1 && PPCSubTarget->useCRBits())
743 // See if operand 2 is an immediate encodeable in the compare.
744 // FIXME: Operands are not in canonical order at -O0, so an immediate
745 // operand in position 1 is a lost opportunity for now. We are
746 // similar to ARM in this regard.
750 // Only 16-bit integer constants can be represented in compares for
751 // PowerPC. Others will be materialized into a register.
752 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(SrcValue2)) {
753 if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
754 SrcVT == MVT::i8 || SrcVT == MVT::i1) {
755 const APInt &CIVal = ConstInt->getValue();
756 Imm = (IsZExt) ? (long)CIVal.getZExtValue() : (long)CIVal.getSExtValue();
757 if ((IsZExt && isUInt<16>(Imm)) || (!IsZExt && isInt<16>(Imm)))
763 bool NeedsExt = false;
764 switch (SrcVT.SimpleTy) {
765 default: return false;
767 CmpOpc = PPC::FCMPUS;
770 CmpOpc = PPC::FCMPUD;
776 // Intentional fall-through.
779 CmpOpc = IsZExt ? PPC::CMPLW : PPC::CMPW;
781 CmpOpc = IsZExt ? PPC::CMPLWI : PPC::CMPWI;
785 CmpOpc = IsZExt ? PPC::CMPLD : PPC::CMPD;
787 CmpOpc = IsZExt ? PPC::CMPLDI : PPC::CMPDI;
791 unsigned SrcReg1 = getRegForValue(SrcValue1);
795 unsigned SrcReg2 = 0;
797 SrcReg2 = getRegForValue(SrcValue2);
803 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
804 if (!PPCEmitIntExt(SrcVT, SrcReg1, MVT::i32, ExtReg, IsZExt))
809 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
810 if (!PPCEmitIntExt(SrcVT, SrcReg2, MVT::i32, ExtReg, IsZExt))
817 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc), DestReg)
818 .addReg(SrcReg1).addReg(SrcReg2);
820 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc), DestReg)
821 .addReg(SrcReg1).addImm(Imm);
826 // Attempt to fast-select a floating-point extend instruction.
827 bool PPCFastISel::SelectFPExt(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::f32 || DestVT != MVT::f64)
835 unsigned SrcReg = getRegForValue(Src);
839 // No code is generated for a FP extend.
840 updateValueMap(I, SrcReg);
844 // Attempt to fast-select a floating-point truncate instruction.
845 bool PPCFastISel::SelectFPTrunc(const Instruction *I) {
846 Value *Src = I->getOperand(0);
847 EVT SrcVT = TLI.getValueType(Src->getType(), true);
848 EVT DestVT = TLI.getValueType(I->getType(), true);
850 if (SrcVT != MVT::f64 || DestVT != MVT::f32)
853 unsigned SrcReg = getRegForValue(Src);
857 // Round the result to single precision.
858 unsigned DestReg = createResultReg(&PPC::F4RCRegClass);
859 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::FRSP), DestReg)
862 updateValueMap(I, DestReg);
866 // Move an i32 or i64 value in a GPR to an f64 value in an FPR.
867 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
868 // those should be used instead of moving via a stack slot when the
869 // subtarget permits.
870 // FIXME: The code here is sloppy for the 4-byte case. Can use a 4-byte
871 // stack slot and 4-byte store/load sequence. Or just sext the 4-byte
872 // case to 8 bytes which produces tighter code but wastes stack space.
873 unsigned PPCFastISel::PPCMoveToFPReg(MVT SrcVT, unsigned SrcReg,
876 // If necessary, extend 32-bit int to 64-bit.
877 if (SrcVT == MVT::i32) {
878 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
879 if (!PPCEmitIntExt(MVT::i32, SrcReg, MVT::i64, TmpReg, !IsSigned))
884 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
886 Addr.BaseType = Address::FrameIndexBase;
887 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
889 // Store the value from the GPR.
890 if (!PPCEmitStore(MVT::i64, SrcReg, Addr))
893 // Load the integer value into an FPR. The kind of load used depends
894 // on a number of conditions.
895 unsigned LoadOpc = PPC::LFD;
897 if (SrcVT == MVT::i32) {
899 LoadOpc = PPC::LFIWZX;
901 } else if (PPCSubTarget->hasLFIWAX()) {
902 LoadOpc = PPC::LFIWAX;
907 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
908 unsigned ResultReg = 0;
909 if (!PPCEmitLoad(MVT::f64, ResultReg, Addr, RC, !IsSigned, LoadOpc))
915 // Attempt to fast-select an integer-to-floating-point conversion.
916 bool PPCFastISel::SelectIToFP(const Instruction *I, bool IsSigned) {
918 Type *DstTy = I->getType();
919 if (!isTypeLegal(DstTy, DstVT))
922 if (DstVT != MVT::f32 && DstVT != MVT::f64)
925 Value *Src = I->getOperand(0);
926 EVT SrcEVT = TLI.getValueType(Src->getType(), true);
927 if (!SrcEVT.isSimple())
930 MVT SrcVT = SrcEVT.getSimpleVT();
932 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 &&
933 SrcVT != MVT::i32 && SrcVT != MVT::i64)
936 unsigned SrcReg = getRegForValue(Src);
940 // We can only lower an unsigned convert if we have the newer
941 // floating-point conversion operations.
942 if (!IsSigned && !PPCSubTarget->hasFPCVT())
945 // FIXME: For now we require the newer floating-point conversion operations
946 // (which are present only on P7 and A2 server models) when converting
947 // to single-precision float. Otherwise we have to generate a lot of
948 // fiddly code to avoid double rounding. If necessary, the fiddly code
949 // can be found in PPCTargetLowering::LowerINT_TO_FP().
950 if (DstVT == MVT::f32 && !PPCSubTarget->hasFPCVT())
953 // Extend the input if necessary.
954 if (SrcVT == MVT::i8 || SrcVT == MVT::i16) {
955 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
956 if (!PPCEmitIntExt(SrcVT, SrcReg, MVT::i64, TmpReg, !IsSigned))
962 // Move the integer value to an FPR.
963 unsigned FPReg = PPCMoveToFPReg(SrcVT, SrcReg, IsSigned);
967 // Determine the opcode for the conversion.
968 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
969 unsigned DestReg = createResultReg(RC);
972 if (DstVT == MVT::f32)
973 Opc = IsSigned ? PPC::FCFIDS : PPC::FCFIDUS;
975 Opc = IsSigned ? PPC::FCFID : PPC::FCFIDU;
977 // Generate the convert.
978 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
981 updateValueMap(I, DestReg);
985 // Move the floating-point value in SrcReg into an integer destination
986 // register, and return the register (or zero if we can't handle it).
987 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
988 // those should be used instead of moving via a stack slot when the
989 // subtarget permits.
990 unsigned PPCFastISel::PPCMoveToIntReg(const Instruction *I, MVT VT,
991 unsigned SrcReg, bool IsSigned) {
992 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
993 // Note that if have STFIWX available, we could use a 4-byte stack
994 // slot for i32, but this being fast-isel we'll just go with the
995 // easiest code gen possible.
997 Addr.BaseType = Address::FrameIndexBase;
998 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
1000 // Store the value from the FPR.
1001 if (!PPCEmitStore(MVT::f64, SrcReg, Addr))
1004 // Reload it into a GPR. If we want an i32, modify the address
1005 // to have a 4-byte offset so we load from the right place.
1009 // Look at the currently assigned register for this instruction
1010 // to determine the required register class.
1011 unsigned AssignedReg = FuncInfo.ValueMap[I];
1012 const TargetRegisterClass *RC =
1013 AssignedReg ? MRI.getRegClass(AssignedReg) : nullptr;
1015 unsigned ResultReg = 0;
1016 if (!PPCEmitLoad(VT, ResultReg, Addr, RC, !IsSigned))
1022 // Attempt to fast-select a floating-point-to-integer conversion.
1023 bool PPCFastISel::SelectFPToI(const Instruction *I, bool IsSigned) {
1025 Type *DstTy = I->getType();
1026 if (!isTypeLegal(DstTy, DstVT))
1029 if (DstVT != MVT::i32 && DstVT != MVT::i64)
1032 // If we don't have FCTIDUZ and we need it, punt to SelectionDAG.
1033 if (DstVT == MVT::i64 && !IsSigned && !PPCSubTarget->hasFPCVT())
1036 Value *Src = I->getOperand(0);
1037 Type *SrcTy = Src->getType();
1038 if (!isTypeLegal(SrcTy, SrcVT))
1041 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
1044 unsigned SrcReg = getRegForValue(Src);
1048 // Convert f32 to f64 if necessary. This is just a meaningless copy
1049 // to get the register class right. COPY_TO_REGCLASS is needed since
1050 // a COPY from F4RC to F8RC is converted to a F4RC-F4RC copy downstream.
1051 const TargetRegisterClass *InRC = MRI.getRegClass(SrcReg);
1052 if (InRC == &PPC::F4RCRegClass) {
1053 unsigned TmpReg = createResultReg(&PPC::F8RCRegClass);
1054 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1055 TII.get(TargetOpcode::COPY_TO_REGCLASS), TmpReg)
1056 .addReg(SrcReg).addImm(PPC::F8RCRegClassID);
1060 // Determine the opcode for the conversion, which takes place
1061 // entirely within FPRs.
1062 unsigned DestReg = createResultReg(&PPC::F8RCRegClass);
1065 if (DstVT == MVT::i32)
1069 Opc = PPCSubTarget->hasFPCVT() ? PPC::FCTIWUZ : PPC::FCTIDZ;
1071 Opc = IsSigned ? PPC::FCTIDZ : PPC::FCTIDUZ;
1073 // Generate the convert.
1074 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1077 // Now move the integer value from a float register to an integer register.
1078 unsigned IntReg = PPCMoveToIntReg(I, DstVT, DestReg, IsSigned);
1082 updateValueMap(I, IntReg);
1086 // Attempt to fast-select a binary integer operation that isn't already
1087 // handled automatically.
1088 bool PPCFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1089 EVT DestVT = TLI.getValueType(I->getType(), true);
1091 // We can get here in the case when we have a binary operation on a non-legal
1092 // type and the target independent selector doesn't know how to handle it.
1093 if (DestVT != MVT::i16 && DestVT != MVT::i8)
1096 // Look at the currently assigned register for this instruction
1097 // to determine the required register class. If there is no register,
1098 // make a conservative choice (don't assign R0).
1099 unsigned AssignedReg = FuncInfo.ValueMap[I];
1100 const TargetRegisterClass *RC =
1101 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1102 &PPC::GPRC_and_GPRC_NOR0RegClass);
1103 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1106 switch (ISDOpcode) {
1107 default: return false;
1109 Opc = IsGPRC ? PPC::ADD4 : PPC::ADD8;
1112 Opc = IsGPRC ? PPC::OR : PPC::OR8;
1115 Opc = IsGPRC ? PPC::SUBF : PPC::SUBF8;
1119 unsigned ResultReg = createResultReg(RC ? RC : &PPC::G8RCRegClass);
1120 unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1121 if (SrcReg1 == 0) return false;
1123 // Handle case of small immediate operand.
1124 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(1))) {
1125 const APInt &CIVal = ConstInt->getValue();
1126 int Imm = (int)CIVal.getSExtValue();
1128 if (isInt<16>(Imm)) {
1131 llvm_unreachable("Missing case!");
1134 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1138 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1151 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1160 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1167 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
1171 updateValueMap(I, ResultReg);
1178 unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1179 if (SrcReg2 == 0) return false;
1181 // Reverse operands for subtract-from.
1182 if (ISDOpcode == ISD::SUB)
1183 std::swap(SrcReg1, SrcReg2);
1185 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1186 .addReg(SrcReg1).addReg(SrcReg2);
1187 updateValueMap(I, ResultReg);
1191 // Handle arguments to a call that we're attempting to fast-select.
1192 // Return false if the arguments are too complex for us at the moment.
1193 bool PPCFastISel::processCallArgs(SmallVectorImpl<Value*> &Args,
1194 SmallVectorImpl<unsigned> &ArgRegs,
1195 SmallVectorImpl<MVT> &ArgVTs,
1196 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1197 SmallVectorImpl<unsigned> &RegArgs,
1201 SmallVector<CCValAssign, 16> ArgLocs;
1202 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, *Context);
1204 // Reserve space for the linkage area on the stack.
1205 bool isELFv2ABI = PPCSubTarget->isELFv2ABI();
1206 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
1208 CCInfo.AllocateStack(LinkageSize, 8);
1210 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_PPC64_ELF_FIS);
1212 // Bail out if we can't handle any of the arguments.
1213 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1214 CCValAssign &VA = ArgLocs[I];
1215 MVT ArgVT = ArgVTs[VA.getValNo()];
1217 // Skip vector arguments for now, as well as long double and
1218 // uint128_t, and anything that isn't passed in a register.
1219 if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64 || ArgVT == MVT::i1 ||
1220 !VA.isRegLoc() || VA.needsCustom())
1223 // Skip bit-converted arguments for now.
1224 if (VA.getLocInfo() == CCValAssign::BCvt)
1228 // Get a count of how many bytes are to be pushed onto the stack.
1229 NumBytes = CCInfo.getNextStackOffset();
1231 // The prolog code of the callee may store up to 8 GPR argument registers to
1232 // the stack, allowing va_start to index over them in memory if its varargs.
1233 // Because we cannot tell if this is needed on the caller side, we have to
1234 // conservatively assume that it is needed. As such, make sure we have at
1235 // least enough stack space for the caller to store the 8 GPRs.
1236 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
1237 NumBytes = std::max(NumBytes, LinkageSize + 64);
1239 // Issue CALLSEQ_START.
1240 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1241 TII.get(TII.getCallFrameSetupOpcode()))
1244 // Prepare to assign register arguments. Every argument uses up a
1245 // GPR protocol register even if it's passed in a floating-point
1247 unsigned NextGPR = PPC::X3;
1248 unsigned NextFPR = PPC::F1;
1250 // Process arguments.
1251 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1252 CCValAssign &VA = ArgLocs[I];
1253 unsigned Arg = ArgRegs[VA.getValNo()];
1254 MVT ArgVT = ArgVTs[VA.getValNo()];
1256 // Handle argument promotion and bitcasts.
1257 switch (VA.getLocInfo()) {
1259 llvm_unreachable("Unknown loc info!");
1260 case CCValAssign::Full:
1262 case CCValAssign::SExt: {
1263 MVT DestVT = VA.getLocVT();
1264 const TargetRegisterClass *RC =
1265 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1266 unsigned TmpReg = createResultReg(RC);
1267 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/false))
1268 llvm_unreachable("Failed to emit a sext!");
1273 case CCValAssign::AExt:
1274 case CCValAssign::ZExt: {
1275 MVT DestVT = VA.getLocVT();
1276 const TargetRegisterClass *RC =
1277 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1278 unsigned TmpReg = createResultReg(RC);
1279 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/true))
1280 llvm_unreachable("Failed to emit a zext!");
1285 case CCValAssign::BCvt: {
1286 // FIXME: Not yet handled.
1287 llvm_unreachable("Should have bailed before getting here!");
1292 // Copy this argument to the appropriate register.
1294 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) {
1300 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1301 TII.get(TargetOpcode::COPY), ArgReg).addReg(Arg);
1302 RegArgs.push_back(ArgReg);
1308 // For a call that we've determined we can fast-select, finish the
1309 // call sequence and generate a copy to obtain the return value (if any).
1310 void PPCFastISel::finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1311 const Instruction *I, CallingConv::ID CC,
1312 unsigned &NumBytes, bool IsVarArg) {
1313 // Issue CallSEQ_END.
1314 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1315 TII.get(TII.getCallFrameDestroyOpcode()))
1316 .addImm(NumBytes).addImm(0);
1318 // Next, generate a copy to obtain the return value.
1319 // FIXME: No multi-register return values yet, though I don't foresee
1320 // any real difficulties there.
1321 if (RetVT != MVT::isVoid) {
1322 SmallVector<CCValAssign, 16> RVLocs;
1323 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs, *Context);
1324 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1325 CCValAssign &VA = RVLocs[0];
1326 assert(RVLocs.size() == 1 && "No support for multi-reg return values!");
1327 assert(VA.isRegLoc() && "Can only return in registers!");
1329 MVT DestVT = VA.getValVT();
1330 MVT CopyVT = DestVT;
1332 // Ints smaller than a register still arrive in a full 64-bit
1333 // register, so make sure we recognize this.
1334 if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32)
1337 unsigned SourcePhysReg = VA.getLocReg();
1338 unsigned ResultReg = 0;
1340 if (RetVT == CopyVT) {
1341 const TargetRegisterClass *CpyRC = TLI.getRegClassFor(CopyVT);
1342 ResultReg = createResultReg(CpyRC);
1344 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1345 TII.get(TargetOpcode::COPY), ResultReg)
1346 .addReg(SourcePhysReg);
1348 // If necessary, round the floating result to single precision.
1349 } else if (CopyVT == MVT::f64) {
1350 ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1351 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::FRSP),
1352 ResultReg).addReg(SourcePhysReg);
1354 // If only the low half of a general register is needed, generate
1355 // a GPRC copy instead of a G8RC copy. (EXTRACT_SUBREG can't be
1356 // used along the fast-isel path (not lowered), and downstream logic
1357 // also doesn't like a direct subreg copy on a physical reg.)
1358 } else if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32) {
1359 ResultReg = createResultReg(&PPC::GPRCRegClass);
1360 // Convert physical register from G8RC to GPRC.
1361 SourcePhysReg -= PPC::X0 - PPC::R0;
1362 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1363 TII.get(TargetOpcode::COPY), ResultReg)
1364 .addReg(SourcePhysReg);
1367 assert(ResultReg && "ResultReg unset!");
1368 UsedRegs.push_back(SourcePhysReg);
1369 updateValueMap(I, ResultReg);
1373 // Attempt to fast-select a call instruction.
1374 bool PPCFastISel::SelectCall(const Instruction *I) {
1375 const CallInst *CI = cast<CallInst>(I);
1376 const Value *Callee = CI->getCalledValue();
1378 // Can't handle inline asm.
1379 if (isa<InlineAsm>(Callee))
1382 // Allow SelectionDAG isel to handle tail calls.
1383 if (CI->isTailCall())
1386 // Obtain calling convention.
1387 ImmutableCallSite CS(CI);
1388 CallingConv::ID CC = CS.getCallingConv();
1390 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1391 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1392 bool IsVarArg = FTy->isVarArg();
1394 // Not ready for varargs yet.
1398 // Handle simple calls for now, with legal return types and
1399 // those that can be extended.
1400 Type *RetTy = I->getType();
1402 if (RetTy->isVoidTy())
1403 RetVT = MVT::isVoid;
1404 else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
1408 // FIXME: No multi-register return values yet.
1409 if (RetVT != MVT::isVoid && RetVT != MVT::i8 && RetVT != MVT::i16 &&
1410 RetVT != MVT::i32 && RetVT != MVT::i64 && RetVT != MVT::f32 &&
1411 RetVT != MVT::f64) {
1412 SmallVector<CCValAssign, 16> RVLocs;
1413 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs, *Context);
1414 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1415 if (RVLocs.size() > 1)
1419 // Bail early if more than 8 arguments, as we only currently
1420 // handle arguments passed in registers.
1421 unsigned NumArgs = CS.arg_size();
1425 // Set up the argument vectors.
1426 SmallVector<Value*, 8> Args;
1427 SmallVector<unsigned, 8> ArgRegs;
1428 SmallVector<MVT, 8> ArgVTs;
1429 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1431 Args.reserve(NumArgs);
1432 ArgRegs.reserve(NumArgs);
1433 ArgVTs.reserve(NumArgs);
1434 ArgFlags.reserve(NumArgs);
1436 for (ImmutableCallSite::arg_iterator II = CS.arg_begin(), IE = CS.arg_end();
1438 // FIXME: ARM does something for intrinsic calls here, check into that.
1440 unsigned AttrIdx = II - CS.arg_begin() + 1;
1442 // Only handle easy calls for now. It would be reasonably easy
1443 // to handle <= 8-byte structures passed ByVal in registers, but we
1444 // have to ensure they are right-justified in the register.
1445 if (CS.paramHasAttr(AttrIdx, Attribute::InReg) ||
1446 CS.paramHasAttr(AttrIdx, Attribute::StructRet) ||
1447 CS.paramHasAttr(AttrIdx, Attribute::Nest) ||
1448 CS.paramHasAttr(AttrIdx, Attribute::ByVal))
1451 ISD::ArgFlagsTy Flags;
1452 if (CS.paramHasAttr(AttrIdx, Attribute::SExt))
1454 if (CS.paramHasAttr(AttrIdx, Attribute::ZExt))
1457 Type *ArgTy = (*II)->getType();
1459 if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8)
1462 if (ArgVT.isVector())
1465 unsigned Arg = getRegForValue(*II);
1469 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
1470 Flags.setOrigAlign(OriginalAlignment);
1472 Args.push_back(*II);
1473 ArgRegs.push_back(Arg);
1474 ArgVTs.push_back(ArgVT);
1475 ArgFlags.push_back(Flags);
1478 // Process the arguments.
1479 SmallVector<unsigned, 8> RegArgs;
1482 if (!processCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
1483 RegArgs, CC, NumBytes, IsVarArg))
1486 // FIXME: No handling for function pointers yet. This requires
1487 // implementing the function descriptor (OPD) setup.
1488 const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1492 // Build direct call with NOP for TOC restore.
1493 // FIXME: We can and should optimize away the NOP for local calls.
1494 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1495 TII.get(PPC::BL8_NOP));
1497 MIB.addGlobalAddress(GV);
1499 // Add implicit physical register uses to the call.
1500 for (unsigned II = 0, IE = RegArgs.size(); II != IE; ++II)
1501 MIB.addReg(RegArgs[II], RegState::Implicit);
1503 // Direct calls in the ELFv2 ABI need the TOC register live into the call.
1504 if (PPCSubTarget->isELFv2ABI())
1505 MIB.addReg(PPC::X2, RegState::Implicit);
1507 // Add a register mask with the call-preserved registers. Proper
1508 // defs for return values will be added by setPhysRegsDeadExcept().
1509 MIB.addRegMask(TRI.getCallPreservedMask(CC));
1511 // Finish off the call including any return values.
1512 SmallVector<unsigned, 4> UsedRegs;
1513 finishCall(RetVT, UsedRegs, I, CC, NumBytes, IsVarArg);
1515 // Set all unused physregs defs as dead.
1516 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1521 // Attempt to fast-select a return instruction.
1522 bool PPCFastISel::SelectRet(const Instruction *I) {
1524 if (!FuncInfo.CanLowerReturn)
1527 const ReturnInst *Ret = cast<ReturnInst>(I);
1528 const Function &F = *I->getParent()->getParent();
1530 // Build a list of return value registers.
1531 SmallVector<unsigned, 4> RetRegs;
1532 CallingConv::ID CC = F.getCallingConv();
1534 if (Ret->getNumOperands() > 0) {
1535 SmallVector<ISD::OutputArg, 4> Outs;
1536 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1538 // Analyze operands of the call, assigning locations to each operand.
1539 SmallVector<CCValAssign, 16> ValLocs;
1540 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, *Context);
1541 CCInfo.AnalyzeReturn(Outs, RetCC_PPC64_ELF_FIS);
1542 const Value *RV = Ret->getOperand(0);
1544 // FIXME: Only one output register for now.
1545 if (ValLocs.size() > 1)
1548 // Special case for returning a constant integer of any size.
1549 // Materialize the constant as an i64 and copy it to the return
1550 // register. We still need to worry about properly extending the sign. E.g:
1551 // If the constant has only one bit, it means it is a boolean. Therefore
1552 // we can't use PPCMaterializeInt because it extends the sign which will
1553 // cause negations of the returned value to be incorrect as they are
1554 // implemented as the flip of the least significant bit.
1555 if (isa<ConstantInt>(*RV)) {
1556 const Constant *C = cast<Constant>(RV);
1558 CCValAssign &VA = ValLocs[0];
1560 unsigned RetReg = VA.getLocReg();
1561 unsigned SrcReg = PPCMaterializeInt(C, MVT::i64,
1562 VA.getLocInfo() == CCValAssign::SExt);
1564 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1565 TII.get(TargetOpcode::COPY), RetReg).addReg(SrcReg);
1567 RetRegs.push_back(RetReg);
1570 unsigned Reg = getRegForValue(RV);
1575 // Copy the result values into the output registers.
1576 for (unsigned i = 0; i < ValLocs.size(); ++i) {
1578 CCValAssign &VA = ValLocs[i];
1579 assert(VA.isRegLoc() && "Can only return in registers!");
1580 RetRegs.push_back(VA.getLocReg());
1581 unsigned SrcReg = Reg + VA.getValNo();
1583 EVT RVEVT = TLI.getValueType(RV->getType());
1584 if (!RVEVT.isSimple())
1586 MVT RVVT = RVEVT.getSimpleVT();
1587 MVT DestVT = VA.getLocVT();
1589 if (RVVT != DestVT && RVVT != MVT::i8 &&
1590 RVVT != MVT::i16 && RVVT != MVT::i32)
1593 if (RVVT != DestVT) {
1594 switch (VA.getLocInfo()) {
1596 llvm_unreachable("Unknown loc info!");
1597 case CCValAssign::Full:
1598 llvm_unreachable("Full value assign but types don't match?");
1599 case CCValAssign::AExt:
1600 case CCValAssign::ZExt: {
1601 const TargetRegisterClass *RC =
1602 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1603 unsigned TmpReg = createResultReg(RC);
1604 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, true))
1609 case CCValAssign::SExt: {
1610 const TargetRegisterClass *RC =
1611 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1612 unsigned TmpReg = createResultReg(RC);
1613 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, false))
1621 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1622 TII.get(TargetOpcode::COPY), RetRegs[i])
1628 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1631 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1632 MIB.addReg(RetRegs[i], RegState::Implicit);
1637 // Attempt to emit an integer extend of SrcReg into DestReg. Both
1638 // signed and zero extensions are supported. Return false if we
1640 bool PPCFastISel::PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1641 unsigned DestReg, bool IsZExt) {
1642 if (DestVT != MVT::i32 && DestVT != MVT::i64)
1644 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 && SrcVT != MVT::i32)
1647 // Signed extensions use EXTSB, EXTSH, EXTSW.
1650 if (SrcVT == MVT::i8)
1651 Opc = (DestVT == MVT::i32) ? PPC::EXTSB : PPC::EXTSB8_32_64;
1652 else if (SrcVT == MVT::i16)
1653 Opc = (DestVT == MVT::i32) ? PPC::EXTSH : PPC::EXTSH8_32_64;
1655 assert(DestVT == MVT::i64 && "Signed extend from i32 to i32??");
1656 Opc = PPC::EXTSW_32_64;
1658 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1661 // Unsigned 32-bit extensions use RLWINM.
1662 } else if (DestVT == MVT::i32) {
1664 if (SrcVT == MVT::i8)
1667 assert(SrcVT == MVT::i16 && "Unsigned extend from i32 to i32??");
1670 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::RLWINM),
1672 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB).addImm(/*ME=*/31);
1674 // Unsigned 64-bit extensions use RLDICL (with a 32-bit source).
1677 if (SrcVT == MVT::i8)
1679 else if (SrcVT == MVT::i16)
1683 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1684 TII.get(PPC::RLDICL_32_64), DestReg)
1685 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB);
1691 // Attempt to fast-select an indirect branch instruction.
1692 bool PPCFastISel::SelectIndirectBr(const Instruction *I) {
1693 unsigned AddrReg = getRegForValue(I->getOperand(0));
1697 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::MTCTR8))
1699 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::BCTR8));
1701 const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1702 for (unsigned i = 0, e = IB->getNumSuccessors(); i != e; ++i)
1703 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[IB->getSuccessor(i)]);
1708 // Attempt to fast-select an integer truncate instruction.
1709 bool PPCFastISel::SelectTrunc(const Instruction *I) {
1710 Value *Src = I->getOperand(0);
1711 EVT SrcVT = TLI.getValueType(Src->getType(), true);
1712 EVT DestVT = TLI.getValueType(I->getType(), true);
1714 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16)
1717 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8)
1720 unsigned SrcReg = getRegForValue(Src);
1724 // The only interesting case is when we need to switch register classes.
1725 if (SrcVT == MVT::i64) {
1726 unsigned ResultReg = createResultReg(&PPC::GPRCRegClass);
1727 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1728 TII.get(TargetOpcode::COPY),
1729 ResultReg).addReg(SrcReg, 0, PPC::sub_32);
1733 updateValueMap(I, SrcReg);
1737 // Attempt to fast-select an integer extend instruction.
1738 bool PPCFastISel::SelectIntExt(const Instruction *I) {
1739 Type *DestTy = I->getType();
1740 Value *Src = I->getOperand(0);
1741 Type *SrcTy = Src->getType();
1743 bool IsZExt = isa<ZExtInst>(I);
1744 unsigned SrcReg = getRegForValue(Src);
1745 if (!SrcReg) return false;
1747 EVT SrcEVT, DestEVT;
1748 SrcEVT = TLI.getValueType(SrcTy, true);
1749 DestEVT = TLI.getValueType(DestTy, true);
1750 if (!SrcEVT.isSimple())
1752 if (!DestEVT.isSimple())
1755 MVT SrcVT = SrcEVT.getSimpleVT();
1756 MVT DestVT = DestEVT.getSimpleVT();
1758 // If we know the register class needed for the result of this
1759 // instruction, use it. Otherwise pick the register class of the
1760 // correct size that does not contain X0/R0, since we don't know
1761 // whether downstream uses permit that assignment.
1762 unsigned AssignedReg = FuncInfo.ValueMap[I];
1763 const TargetRegisterClass *RC =
1764 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1765 (DestVT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
1766 &PPC::GPRC_and_GPRC_NOR0RegClass));
1767 unsigned ResultReg = createResultReg(RC);
1769 if (!PPCEmitIntExt(SrcVT, SrcReg, DestVT, ResultReg, IsZExt))
1772 updateValueMap(I, ResultReg);
1776 // Attempt to fast-select an instruction that wasn't handled by
1777 // the table-generated machinery.
1778 bool PPCFastISel::fastSelectInstruction(const Instruction *I) {
1780 switch (I->getOpcode()) {
1781 case Instruction::Load:
1782 return SelectLoad(I);
1783 case Instruction::Store:
1784 return SelectStore(I);
1785 case Instruction::Br:
1786 return SelectBranch(I);
1787 case Instruction::IndirectBr:
1788 return SelectIndirectBr(I);
1789 case Instruction::FPExt:
1790 return SelectFPExt(I);
1791 case Instruction::FPTrunc:
1792 return SelectFPTrunc(I);
1793 case Instruction::SIToFP:
1794 return SelectIToFP(I, /*IsSigned*/ true);
1795 case Instruction::UIToFP:
1796 return SelectIToFP(I, /*IsSigned*/ false);
1797 case Instruction::FPToSI:
1798 return SelectFPToI(I, /*IsSigned*/ true);
1799 case Instruction::FPToUI:
1800 return SelectFPToI(I, /*IsSigned*/ false);
1801 case Instruction::Add:
1802 return SelectBinaryIntOp(I, ISD::ADD);
1803 case Instruction::Or:
1804 return SelectBinaryIntOp(I, ISD::OR);
1805 case Instruction::Sub:
1806 return SelectBinaryIntOp(I, ISD::SUB);
1807 case Instruction::Call:
1808 if (dyn_cast<IntrinsicInst>(I))
1810 return SelectCall(I);
1811 case Instruction::Ret:
1812 return SelectRet(I);
1813 case Instruction::Trunc:
1814 return SelectTrunc(I);
1815 case Instruction::ZExt:
1816 case Instruction::SExt:
1817 return SelectIntExt(I);
1818 // Here add other flavors of Instruction::XXX that automated
1819 // cases don't catch. For example, switches are terminators
1820 // that aren't yet handled.
1827 // Materialize a floating-point constant into a register, and return
1828 // the register number (or zero if we failed to handle it).
1829 unsigned PPCFastISel::PPCMaterializeFP(const ConstantFP *CFP, MVT VT) {
1830 // No plans to handle long double here.
1831 if (VT != MVT::f32 && VT != MVT::f64)
1834 // All FP constants are loaded from the constant pool.
1835 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
1836 assert(Align > 0 && "Unexpectedly missing alignment information!");
1837 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
1838 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
1839 CodeModel::Model CModel = TM.getCodeModel();
1841 MachineMemOperand *MMO =
1842 FuncInfo.MF->getMachineMemOperand(
1843 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
1844 (VT == MVT::f32) ? 4 : 8, Align);
1846 unsigned Opc = (VT == MVT::f32) ? PPC::LFS : PPC::LFD;
1847 unsigned TmpReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1849 // For small code model, generate a LF[SD](0, LDtocCPT(Idx, X2)).
1850 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault) {
1851 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocCPT),
1853 .addConstantPoolIndex(Idx).addReg(PPC::X2);
1854 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1855 .addImm(0).addReg(TmpReg).addMemOperand(MMO);
1857 // Otherwise we generate LF[SD](Idx[lo], ADDIStocHA(X2, Idx)).
1858 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDIStocHA),
1859 TmpReg).addReg(PPC::X2).addConstantPoolIndex(Idx);
1860 // But for large code model, we must generate a LDtocL followed
1862 if (CModel == CodeModel::Large) {
1863 unsigned TmpReg2 = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1864 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocL),
1865 TmpReg2).addConstantPoolIndex(Idx).addReg(TmpReg);
1866 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1867 .addImm(0).addReg(TmpReg2);
1869 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1870 .addConstantPoolIndex(Idx, 0, PPCII::MO_TOC_LO)
1872 .addMemOperand(MMO);
1878 // Materialize the address of a global value into a register, and return
1879 // the register number (or zero if we failed to handle it).
1880 unsigned PPCFastISel::PPCMaterializeGV(const GlobalValue *GV, MVT VT) {
1881 assert(VT == MVT::i64 && "Non-address!");
1882 const TargetRegisterClass *RC = &PPC::G8RC_and_G8RC_NOX0RegClass;
1883 unsigned DestReg = createResultReg(RC);
1885 // Global values may be plain old object addresses, TLS object
1886 // addresses, constant pool entries, or jump tables. How we generate
1887 // code for these may depend on small, medium, or large code model.
1888 CodeModel::Model CModel = TM.getCodeModel();
1890 // FIXME: Jump tables are not yet required because fast-isel doesn't
1891 // handle switches; if that changes, we need them as well. For now,
1892 // what follows assumes everything's a generic (or TLS) global address.
1894 // FIXME: We don't yet handle the complexity of TLS.
1895 if (GV->isThreadLocal())
1898 // For small code model, generate a simple TOC load.
1899 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault)
1900 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtoc),
1902 .addGlobalAddress(GV)
1905 // If the address is an externally defined symbol, a symbol with common
1906 // or externally available linkage, a non-local function address, or a
1907 // jump table address (not yet needed), or if we are generating code
1908 // for large code model, we generate:
1909 // LDtocL(GV, ADDIStocHA(%X2, GV))
1910 // Otherwise we generate:
1911 // ADDItocL(ADDIStocHA(%X2, GV), GV)
1912 // Either way, start with the ADDIStocHA:
1913 unsigned HighPartReg = createResultReg(RC);
1914 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDIStocHA),
1915 HighPartReg).addReg(PPC::X2).addGlobalAddress(GV);
1917 // If/when switches are implemented, jump tables should be handled
1918 // on the "if" path here.
1919 if (CModel == CodeModel::Large ||
1920 (GV->getType()->getElementType()->isFunctionTy() &&
1921 (GV->isDeclaration() || GV->isWeakForLinker())) ||
1922 GV->isDeclaration() || GV->hasCommonLinkage() ||
1923 GV->hasAvailableExternallyLinkage())
1924 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocL),
1925 DestReg).addGlobalAddress(GV).addReg(HighPartReg);
1927 // Otherwise generate the ADDItocL.
1928 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDItocL),
1929 DestReg).addReg(HighPartReg).addGlobalAddress(GV);
1935 // Materialize a 32-bit integer constant into a register, and return
1936 // the register number (or zero if we failed to handle it).
1937 unsigned PPCFastISel::PPCMaterialize32BitInt(int64_t Imm,
1938 const TargetRegisterClass *RC) {
1939 unsigned Lo = Imm & 0xFFFF;
1940 unsigned Hi = (Imm >> 16) & 0xFFFF;
1942 unsigned ResultReg = createResultReg(RC);
1943 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1946 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1947 TII.get(IsGPRC ? PPC::LI : PPC::LI8), ResultReg)
1950 // Both Lo and Hi have nonzero bits.
1951 unsigned TmpReg = createResultReg(RC);
1952 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1953 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), TmpReg)
1955 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1956 TII.get(IsGPRC ? PPC::ORI : PPC::ORI8), ResultReg)
1957 .addReg(TmpReg).addImm(Lo);
1960 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1961 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), ResultReg)
1967 // Materialize a 64-bit integer constant into a register, and return
1968 // the register number (or zero if we failed to handle it).
1969 unsigned PPCFastISel::PPCMaterialize64BitInt(int64_t Imm,
1970 const TargetRegisterClass *RC) {
1971 unsigned Remainder = 0;
1974 // If the value doesn't fit in 32 bits, see if we can shift it
1975 // so that it fits in 32 bits.
1976 if (!isInt<32>(Imm)) {
1977 Shift = countTrailingZeros<uint64_t>(Imm);
1978 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
1980 if (isInt<32>(ImmSh))
1989 // Handle the high-order 32 bits (if shifted) or the whole 32 bits
1990 // (if not shifted).
1991 unsigned TmpReg1 = PPCMaterialize32BitInt(Imm, RC);
1995 // If upper 32 bits were not zero, we've built them and need to shift
1999 TmpReg2 = createResultReg(RC);
2000 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::RLDICR),
2001 TmpReg2).addReg(TmpReg1).addImm(Shift).addImm(63 - Shift);
2005 unsigned TmpReg3, Hi, Lo;
2006 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
2007 TmpReg3 = createResultReg(RC);
2008 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ORIS8),
2009 TmpReg3).addReg(TmpReg2).addImm(Hi);
2013 if ((Lo = Remainder & 0xFFFF)) {
2014 unsigned ResultReg = createResultReg(RC);
2015 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ORI8),
2016 ResultReg).addReg(TmpReg3).addImm(Lo);
2024 // Materialize an integer constant into a register, and return
2025 // the register number (or zero if we failed to handle it).
2026 unsigned PPCFastISel::PPCMaterializeInt(const Constant *C, MVT VT,
2028 // If we're using CR bit registers for i1 values, handle that as a special
2030 if (VT == MVT::i1 && PPCSubTarget->useCRBits()) {
2031 const ConstantInt *CI = cast<ConstantInt>(C);
2032 unsigned ImmReg = createResultReg(&PPC::CRBITRCRegClass);
2033 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2034 TII.get(CI->isZero() ? PPC::CRUNSET : PPC::CRSET), ImmReg);
2038 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2039 VT != MVT::i8 && VT != MVT::i1)
2042 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2043 &PPC::GPRCRegClass);
2045 // If the constant is in range, use a load-immediate.
2046 const ConstantInt *CI = cast<ConstantInt>(C);
2047 if (isInt<16>(CI->getSExtValue())) {
2048 unsigned Opc = (VT == MVT::i64) ? PPC::LI8 : PPC::LI;
2049 unsigned ImmReg = createResultReg(RC);
2050 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ImmReg)
2051 .addImm( (UseSExt) ? CI->getSExtValue() : CI->getZExtValue() );
2055 // Construct the constant piecewise.
2056 int64_t Imm = CI->getZExtValue();
2059 return PPCMaterialize64BitInt(Imm, RC);
2060 else if (VT == MVT::i32)
2061 return PPCMaterialize32BitInt(Imm, RC);
2066 // Materialize a constant into a register, and return the register
2067 // number (or zero if we failed to handle it).
2068 unsigned PPCFastISel::fastMaterializeConstant(const Constant *C) {
2069 EVT CEVT = TLI.getValueType(C->getType(), true);
2071 // Only handle simple types.
2072 if (!CEVT.isSimple()) return 0;
2073 MVT VT = CEVT.getSimpleVT();
2075 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
2076 return PPCMaterializeFP(CFP, VT);
2077 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
2078 return PPCMaterializeGV(GV, VT);
2079 else if (isa<ConstantInt>(C))
2080 return PPCMaterializeInt(C, VT);
2085 // Materialize the address created by an alloca into a register, and
2086 // return the register number (or zero if we failed to handle it).
2087 unsigned PPCFastISel::fastMaterializeAlloca(const AllocaInst *AI) {
2088 // Don't handle dynamic allocas.
2089 if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
2092 if (!isLoadTypeLegal(AI->getType(), VT)) return 0;
2094 DenseMap<const AllocaInst*, int>::iterator SI =
2095 FuncInfo.StaticAllocaMap.find(AI);
2097 if (SI != FuncInfo.StaticAllocaMap.end()) {
2098 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
2099 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDI8),
2100 ResultReg).addFrameIndex(SI->second).addImm(0);
2107 // Fold loads into extends when possible.
2108 // FIXME: We can have multiple redundant extend/trunc instructions
2109 // following a load. The folding only picks up one. Extend this
2110 // to check subsequent instructions for the same pattern and remove
2111 // them. Thus ResultReg should be the def reg for the last redundant
2112 // instruction in a chain, and all intervening instructions can be
2113 // removed from parent. Change test/CodeGen/PowerPC/fast-isel-fold.ll
2114 // to add ELF64-NOT: rldicl to the appropriate tests when this works.
2115 bool PPCFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2116 const LoadInst *LI) {
2117 // Verify we have a legal type before going any further.
2119 if (!isLoadTypeLegal(LI->getType(), VT))
2122 // Combine load followed by zero- or sign-extend.
2123 bool IsZExt = false;
2124 switch(MI->getOpcode()) {
2129 case PPC::RLDICL_32_64: {
2131 unsigned MB = MI->getOperand(3).getImm();
2132 if ((VT == MVT::i8 && MB <= 56) ||
2133 (VT == MVT::i16 && MB <= 48) ||
2134 (VT == MVT::i32 && MB <= 32))
2140 case PPC::RLWINM8: {
2142 unsigned MB = MI->getOperand(3).getImm();
2143 if ((VT == MVT::i8 && MB <= 24) ||
2144 (VT == MVT::i16 && MB <= 16))
2151 case PPC::EXTSB8_32_64:
2152 /* There is no sign-extending load-byte instruction. */
2157 case PPC::EXTSH8_32_64: {
2158 if (VT != MVT::i16 && VT != MVT::i8)
2164 case PPC::EXTSW_32_64: {
2165 if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8)
2171 // See if we can handle this address.
2173 if (!PPCComputeAddress(LI->getOperand(0), Addr))
2176 unsigned ResultReg = MI->getOperand(0).getReg();
2178 if (!PPCEmitLoad(VT, ResultReg, Addr, nullptr, IsZExt))
2181 MI->eraseFromParent();
2185 // Attempt to lower call arguments in a faster way than done by
2186 // the selection DAG code.
2187 bool PPCFastISel::fastLowerArguments() {
2188 // Defer to normal argument lowering for now. It's reasonably
2189 // efficient. Consider doing something like ARM to handle the
2190 // case where all args fit in registers, no varargs, no float
2195 // Handle materializing integer constants into a register. This is not
2196 // automatically generated for PowerPC, so must be explicitly created here.
2197 unsigned PPCFastISel::fastEmit_i(MVT Ty, MVT VT, unsigned Opc, uint64_t Imm) {
2199 if (Opc != ISD::Constant)
2202 // If we're using CR bit registers for i1 values, handle that as a special
2204 if (VT == MVT::i1 && PPCSubTarget->useCRBits()) {
2205 unsigned ImmReg = createResultReg(&PPC::CRBITRCRegClass);
2206 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2207 TII.get(Imm == 0 ? PPC::CRUNSET : PPC::CRSET), ImmReg);
2211 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2212 VT != MVT::i8 && VT != MVT::i1)
2215 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2216 &PPC::GPRCRegClass);
2218 return PPCMaterialize64BitInt(Imm, RC);
2220 return PPCMaterialize32BitInt(Imm, RC);
2223 // Override for ADDI and ADDI8 to set the correct register class
2224 // on RHS operand 0. The automatic infrastructure naively assumes
2225 // GPRC for i32 and G8RC for i64; the concept of "no R0" is lost
2226 // for these cases. At the moment, none of the other automatically
2227 // generated RI instructions require special treatment. However, once
2228 // SelectSelect is implemented, "isel" requires similar handling.
2230 // Also be conservative about the output register class. Avoid
2231 // assigning R0 or X0 to the output register for GPRC and G8RC
2232 // register classes, as any such result could be used in ADDI, etc.,
2233 // where those regs have another meaning.
2234 unsigned PPCFastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
2235 const TargetRegisterClass *RC,
2236 unsigned Op0, bool Op0IsKill,
2238 if (MachineInstOpcode == PPC::ADDI)
2239 MRI.setRegClass(Op0, &PPC::GPRC_and_GPRC_NOR0RegClass);
2240 else if (MachineInstOpcode == PPC::ADDI8)
2241 MRI.setRegClass(Op0, &PPC::G8RC_and_G8RC_NOX0RegClass);
2243 const TargetRegisterClass *UseRC =
2244 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2245 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2247 return FastISel::fastEmitInst_ri(MachineInstOpcode, UseRC,
2248 Op0, Op0IsKill, Imm);
2251 // Override for instructions with one register operand to avoid use of
2252 // R0/X0. The automatic infrastructure isn't aware of the context so
2253 // we must be conservative.
2254 unsigned PPCFastISel::fastEmitInst_r(unsigned MachineInstOpcode,
2255 const TargetRegisterClass* RC,
2256 unsigned Op0, bool Op0IsKill) {
2257 const TargetRegisterClass *UseRC =
2258 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2259 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2261 return FastISel::fastEmitInst_r(MachineInstOpcode, UseRC, Op0, Op0IsKill);
2264 // Override for instructions with two register operands to avoid use
2265 // of R0/X0. The automatic infrastructure isn't aware of the context
2266 // so we must be conservative.
2267 unsigned PPCFastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
2268 const TargetRegisterClass* RC,
2269 unsigned Op0, bool Op0IsKill,
2270 unsigned Op1, bool Op1IsKill) {
2271 const TargetRegisterClass *UseRC =
2272 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2273 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2275 return FastISel::fastEmitInst_rr(MachineInstOpcode, UseRC, Op0, Op0IsKill,
2280 // Create the fast instruction selector for PowerPC64 ELF.
2281 FastISel *PPC::createFastISel(FunctionLoweringInfo &FuncInfo,
2282 const TargetLibraryInfo *LibInfo) {
2283 const TargetMachine &TM = FuncInfo.MF->getTarget();
2285 // Only available on 64-bit ELF for now.
2286 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
2287 if (Subtarget->isPPC64() && Subtarget->isSVR4ABI())
2288 return new PPCFastISel(FuncInfo, LibInfo);