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),
96 TM(FuncInfo.MF->getTarget()),
97 TII(*TM.getInstrInfo()),
98 TLI(*TM.getTargetLowering()),
99 PPCSubTarget(&TM.getSubtarget<PPCSubtarget>()),
100 Context(&FuncInfo.Fn->getContext()) { }
102 // Backend specific FastISel code.
104 bool TargetSelectInstruction(const Instruction *I) override;
105 unsigned TargetMaterializeConstant(const Constant *C) override;
106 unsigned TargetMaterializeAlloca(const AllocaInst *AI) override;
107 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
108 const LoadInst *LI) override;
109 bool FastLowerArguments() override;
110 unsigned FastEmit_i(MVT Ty, MVT RetTy, unsigned Opc, uint64_t Imm) override;
111 unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
112 const TargetRegisterClass *RC,
113 unsigned Op0, bool Op0IsKill,
115 unsigned FastEmitInst_r(unsigned MachineInstOpcode,
116 const TargetRegisterClass *RC,
117 unsigned Op0, bool Op0IsKill);
118 unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
119 const TargetRegisterClass *RC,
120 unsigned Op0, bool Op0IsKill,
121 unsigned Op1, bool Op1IsKill);
123 // Instruction selection routines.
125 bool SelectLoad(const Instruction *I);
126 bool SelectStore(const Instruction *I);
127 bool SelectBranch(const Instruction *I);
128 bool SelectIndirectBr(const Instruction *I);
129 bool SelectFPExt(const Instruction *I);
130 bool SelectFPTrunc(const Instruction *I);
131 bool SelectIToFP(const Instruction *I, bool IsSigned);
132 bool SelectFPToI(const Instruction *I, bool IsSigned);
133 bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
134 bool SelectCall(const Instruction *I);
135 bool SelectRet(const Instruction *I);
136 bool SelectTrunc(const Instruction *I);
137 bool SelectIntExt(const Instruction *I);
141 bool isTypeLegal(Type *Ty, MVT &VT);
142 bool isLoadTypeLegal(Type *Ty, MVT &VT);
143 bool PPCEmitCmp(const Value *Src1Value, const Value *Src2Value,
144 bool isZExt, unsigned DestReg);
145 bool PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
146 const TargetRegisterClass *RC, bool IsZExt = true,
147 unsigned FP64LoadOpc = PPC::LFD);
148 bool PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr);
149 bool PPCComputeAddress(const Value *Obj, Address &Addr);
150 void PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
152 bool PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
153 unsigned DestReg, bool IsZExt);
154 unsigned PPCMaterializeFP(const ConstantFP *CFP, MVT VT);
155 unsigned PPCMaterializeGV(const GlobalValue *GV, MVT VT);
156 unsigned PPCMaterializeInt(const Constant *C, MVT VT);
157 unsigned PPCMaterialize32BitInt(int64_t Imm,
158 const TargetRegisterClass *RC);
159 unsigned PPCMaterialize64BitInt(int64_t Imm,
160 const TargetRegisterClass *RC);
161 unsigned PPCMoveToIntReg(const Instruction *I, MVT VT,
162 unsigned SrcReg, bool IsSigned);
163 unsigned PPCMoveToFPReg(MVT VT, unsigned SrcReg, bool IsSigned);
165 // Call handling routines.
167 bool processCallArgs(SmallVectorImpl<Value*> &Args,
168 SmallVectorImpl<unsigned> &ArgRegs,
169 SmallVectorImpl<MVT> &ArgVTs,
170 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
171 SmallVectorImpl<unsigned> &RegArgs,
175 void finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
176 const Instruction *I, CallingConv::ID CC,
177 unsigned &NumBytes, bool IsVarArg);
178 CCAssignFn *usePPC32CCs(unsigned Flag);
181 #include "PPCGenFastISel.inc"
185 } // end anonymous namespace
187 #include "PPCGenCallingConv.inc"
189 // Function whose sole purpose is to kill compiler warnings
190 // stemming from unused functions included from PPCGenCallingConv.inc.
191 CCAssignFn *PPCFastISel::usePPC32CCs(unsigned Flag) {
193 return CC_PPC32_SVR4;
195 return CC_PPC32_SVR4_ByVal;
197 return CC_PPC32_SVR4_VarArg;
202 static Optional<PPC::Predicate> getComparePred(CmpInst::Predicate Pred) {
204 // These are not representable with any single compare.
205 case CmpInst::FCMP_FALSE:
206 case CmpInst::FCMP_UEQ:
207 case CmpInst::FCMP_UGT:
208 case CmpInst::FCMP_UGE:
209 case CmpInst::FCMP_ULT:
210 case CmpInst::FCMP_ULE:
211 case CmpInst::FCMP_UNE:
212 case CmpInst::FCMP_TRUE:
214 return Optional<PPC::Predicate>();
216 case CmpInst::FCMP_OEQ:
217 case CmpInst::ICMP_EQ:
220 case CmpInst::FCMP_OGT:
221 case CmpInst::ICMP_UGT:
222 case CmpInst::ICMP_SGT:
225 case CmpInst::FCMP_OGE:
226 case CmpInst::ICMP_UGE:
227 case CmpInst::ICMP_SGE:
230 case CmpInst::FCMP_OLT:
231 case CmpInst::ICMP_ULT:
232 case CmpInst::ICMP_SLT:
235 case CmpInst::FCMP_OLE:
236 case CmpInst::ICMP_ULE:
237 case CmpInst::ICMP_SLE:
240 case CmpInst::FCMP_ONE:
241 case CmpInst::ICMP_NE:
244 case CmpInst::FCMP_ORD:
247 case CmpInst::FCMP_UNO:
252 // Determine whether the type Ty is simple enough to be handled by
253 // fast-isel, and return its equivalent machine type in VT.
254 // FIXME: Copied directly from ARM -- factor into base class?
255 bool PPCFastISel::isTypeLegal(Type *Ty, MVT &VT) {
256 EVT Evt = TLI.getValueType(Ty, true);
258 // Only handle simple types.
259 if (Evt == MVT::Other || !Evt.isSimple()) return false;
260 VT = Evt.getSimpleVT();
262 // Handle all legal types, i.e. a register that will directly hold this
264 return TLI.isTypeLegal(VT);
267 // Determine whether the type Ty is simple enough to be handled by
268 // fast-isel as a load target, and return its equivalent machine type in VT.
269 bool PPCFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
270 if (isTypeLegal(Ty, VT)) return true;
272 // If this is a type than can be sign or zero-extended to a basic operation
273 // go ahead and accept it now.
274 if (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) {
281 // Given a value Obj, create an Address object Addr that represents its
282 // address. Return false if we can't handle it.
283 bool PPCFastISel::PPCComputeAddress(const Value *Obj, Address &Addr) {
284 const User *U = nullptr;
285 unsigned Opcode = Instruction::UserOp1;
286 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
287 // Don't walk into other basic blocks unless the object is an alloca from
288 // another block, otherwise it may not have a virtual register assigned.
289 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
290 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
291 Opcode = I->getOpcode();
294 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
295 Opcode = C->getOpcode();
302 case Instruction::BitCast:
303 // Look through bitcasts.
304 return PPCComputeAddress(U->getOperand(0), Addr);
305 case Instruction::IntToPtr:
306 // Look past no-op inttoptrs.
307 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
308 return PPCComputeAddress(U->getOperand(0), Addr);
310 case Instruction::PtrToInt:
311 // Look past no-op ptrtoints.
312 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
313 return PPCComputeAddress(U->getOperand(0), Addr);
315 case Instruction::GetElementPtr: {
316 Address SavedAddr = Addr;
317 long TmpOffset = Addr.Offset;
319 // Iterate through the GEP folding the constants into offsets where
321 gep_type_iterator GTI = gep_type_begin(U);
322 for (User::const_op_iterator II = U->op_begin() + 1, IE = U->op_end();
323 II != IE; ++II, ++GTI) {
324 const Value *Op = *II;
325 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
326 const StructLayout *SL = DL.getStructLayout(STy);
327 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
328 TmpOffset += SL->getElementOffset(Idx);
330 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
332 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
333 // Constant-offset addressing.
334 TmpOffset += CI->getSExtValue() * S;
337 if (canFoldAddIntoGEP(U, Op)) {
338 // A compatible add with a constant operand. Fold the constant.
340 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
341 TmpOffset += CI->getSExtValue() * S;
342 // Iterate on the other operand.
343 Op = cast<AddOperator>(Op)->getOperand(0);
347 goto unsupported_gep;
352 // Try to grab the base operand now.
353 Addr.Offset = TmpOffset;
354 if (PPCComputeAddress(U->getOperand(0), Addr)) return true;
356 // We failed, restore everything and try the other options.
362 case Instruction::Alloca: {
363 const AllocaInst *AI = cast<AllocaInst>(Obj);
364 DenseMap<const AllocaInst*, int>::iterator SI =
365 FuncInfo.StaticAllocaMap.find(AI);
366 if (SI != FuncInfo.StaticAllocaMap.end()) {
367 Addr.BaseType = Address::FrameIndexBase;
368 Addr.Base.FI = SI->second;
375 // FIXME: References to parameters fall through to the behavior
376 // below. They should be able to reference a frame index since
377 // they are stored to the stack, so we can get "ld rx, offset(r1)"
378 // instead of "addi ry, r1, offset / ld rx, 0(ry)". Obj will
379 // just contain the parameter. Try to handle this with a FI.
381 // Try to get this in a register if nothing else has worked.
382 if (Addr.Base.Reg == 0)
383 Addr.Base.Reg = getRegForValue(Obj);
385 // Prevent assignment of base register to X0, which is inappropriate
386 // for loads and stores alike.
387 if (Addr.Base.Reg != 0)
388 MRI.setRegClass(Addr.Base.Reg, &PPC::G8RC_and_G8RC_NOX0RegClass);
390 return Addr.Base.Reg != 0;
393 // Fix up some addresses that can't be used directly. For example, if
394 // an offset won't fit in an instruction field, we may need to move it
395 // into an index register.
396 void PPCFastISel::PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
397 unsigned &IndexReg) {
399 // Check whether the offset fits in the instruction field.
400 if (!isInt<16>(Addr.Offset))
403 // If this is a stack pointer and the offset needs to be simplified then
404 // put the alloca address into a register, set the base type back to
405 // register and continue. This should almost never happen.
406 if (!UseOffset && Addr.BaseType == Address::FrameIndexBase) {
407 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
408 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDI8),
409 ResultReg).addFrameIndex(Addr.Base.FI).addImm(0);
410 Addr.Base.Reg = ResultReg;
411 Addr.BaseType = Address::RegBase;
415 IntegerType *OffsetTy = ((VT == MVT::i32) ? Type::getInt32Ty(*Context)
416 : Type::getInt64Ty(*Context));
417 const ConstantInt *Offset =
418 ConstantInt::getSigned(OffsetTy, (int64_t)(Addr.Offset));
419 IndexReg = PPCMaterializeInt(Offset, MVT::i64);
420 assert(IndexReg && "Unexpected error in PPCMaterializeInt!");
424 // Emit a load instruction if possible, returning true if we succeeded,
425 // otherwise false. See commentary below for how the register class of
426 // the load is determined.
427 bool PPCFastISel::PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
428 const TargetRegisterClass *RC,
429 bool IsZExt, unsigned FP64LoadOpc) {
431 bool UseOffset = true;
433 // If ResultReg is given, it determines the register class of the load.
434 // Otherwise, RC is the register class to use. If the result of the
435 // load isn't anticipated in this block, both may be zero, in which
436 // case we must make a conservative guess. In particular, don't assign
437 // R0 or X0 to the result register, as the result may be used in a load,
438 // store, add-immediate, or isel that won't permit this. (Though
439 // perhaps the spill and reload of live-exit values would handle this?)
440 const TargetRegisterClass *UseRC =
441 (ResultReg ? MRI.getRegClass(ResultReg) :
443 (VT == MVT::f64 ? &PPC::F8RCRegClass :
444 (VT == MVT::f32 ? &PPC::F4RCRegClass :
445 (VT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
446 &PPC::GPRC_and_GPRC_NOR0RegClass)))));
448 bool Is32BitInt = UseRC->hasSuperClassEq(&PPC::GPRCRegClass);
450 switch (VT.SimpleTy) {
451 default: // e.g., vector types not handled
454 Opc = Is32BitInt ? PPC::LBZ : PPC::LBZ8;
458 (Is32BitInt ? PPC::LHZ : PPC::LHZ8) :
459 (Is32BitInt ? PPC::LHA : PPC::LHA8));
463 (Is32BitInt ? PPC::LWZ : PPC::LWZ8) :
464 (Is32BitInt ? PPC::LWA_32 : PPC::LWA));
465 if ((Opc == PPC::LWA || Opc == PPC::LWA_32) && ((Addr.Offset & 3) != 0))
470 assert(UseRC->hasSuperClassEq(&PPC::G8RCRegClass) &&
471 "64-bit load with 32-bit target??");
472 UseOffset = ((Addr.Offset & 3) == 0);
482 // If necessary, materialize the offset into a register and use
483 // the indexed form. Also handle stack pointers with special needs.
484 unsigned IndexReg = 0;
485 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
487 ResultReg = createResultReg(UseRC);
489 // Note: If we still have a frame index here, we know the offset is
490 // in range, as otherwise PPCSimplifyAddress would have converted it
492 if (Addr.BaseType == Address::FrameIndexBase) {
494 MachineMemOperand *MMO =
495 FuncInfo.MF->getMachineMemOperand(
496 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
497 MachineMemOperand::MOLoad, MFI.getObjectSize(Addr.Base.FI),
498 MFI.getObjectAlignment(Addr.Base.FI));
500 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
501 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
503 // Base reg with offset in range.
504 } else if (UseOffset) {
506 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
507 .addImm(Addr.Offset).addReg(Addr.Base.Reg);
511 // Get the RR opcode corresponding to the RI one. FIXME: It would be
512 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
513 // is hard to get at.
515 default: llvm_unreachable("Unexpected opcode!");
516 case PPC::LBZ: Opc = PPC::LBZX; break;
517 case PPC::LBZ8: Opc = PPC::LBZX8; break;
518 case PPC::LHZ: Opc = PPC::LHZX; break;
519 case PPC::LHZ8: Opc = PPC::LHZX8; break;
520 case PPC::LHA: Opc = PPC::LHAX; break;
521 case PPC::LHA8: Opc = PPC::LHAX8; break;
522 case PPC::LWZ: Opc = PPC::LWZX; break;
523 case PPC::LWZ8: Opc = PPC::LWZX8; break;
524 case PPC::LWA: Opc = PPC::LWAX; break;
525 case PPC::LWA_32: Opc = PPC::LWAX_32; break;
526 case PPC::LD: Opc = PPC::LDX; break;
527 case PPC::LFS: Opc = PPC::LFSX; break;
528 case PPC::LFD: Opc = PPC::LFDX; break;
530 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
531 .addReg(Addr.Base.Reg).addReg(IndexReg);
537 // Attempt to fast-select a load instruction.
538 bool PPCFastISel::SelectLoad(const Instruction *I) {
539 // FIXME: No atomic loads are supported.
540 if (cast<LoadInst>(I)->isAtomic())
543 // Verify we have a legal type before going any further.
545 if (!isLoadTypeLegal(I->getType(), VT))
548 // See if we can handle this address.
550 if (!PPCComputeAddress(I->getOperand(0), Addr))
553 // Look at the currently assigned register for this instruction
554 // to determine the required register class. This is necessary
555 // to constrain RA from using R0/X0 when this is not legal.
556 unsigned AssignedReg = FuncInfo.ValueMap[I];
557 const TargetRegisterClass *RC =
558 AssignedReg ? MRI.getRegClass(AssignedReg) : nullptr;
560 unsigned ResultReg = 0;
561 if (!PPCEmitLoad(VT, ResultReg, Addr, RC))
563 UpdateValueMap(I, ResultReg);
567 // Emit a store instruction to store SrcReg at Addr.
568 bool PPCFastISel::PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr) {
569 assert(SrcReg && "Nothing to store!");
571 bool UseOffset = true;
573 const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
574 bool Is32BitInt = RC->hasSuperClassEq(&PPC::GPRCRegClass);
576 switch (VT.SimpleTy) {
577 default: // e.g., vector types not handled
580 Opc = Is32BitInt ? PPC::STB : PPC::STB8;
583 Opc = Is32BitInt ? PPC::STH : PPC::STH8;
586 assert(Is32BitInt && "Not GPRC for i32??");
591 UseOffset = ((Addr.Offset & 3) == 0);
601 // If necessary, materialize the offset into a register and use
602 // the indexed form. Also handle stack pointers with special needs.
603 unsigned IndexReg = 0;
604 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
606 // Note: If we still have a frame index here, we know the offset is
607 // in range, as otherwise PPCSimplifyAddress would have converted it
609 if (Addr.BaseType == Address::FrameIndexBase) {
610 MachineMemOperand *MMO =
611 FuncInfo.MF->getMachineMemOperand(
612 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
613 MachineMemOperand::MOStore, MFI.getObjectSize(Addr.Base.FI),
614 MFI.getObjectAlignment(Addr.Base.FI));
616 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
619 .addFrameIndex(Addr.Base.FI)
622 // Base reg with offset in range.
623 } else if (UseOffset)
624 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
625 .addReg(SrcReg).addImm(Addr.Offset).addReg(Addr.Base.Reg);
629 // Get the RR opcode corresponding to the RI one. FIXME: It would be
630 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
631 // is hard to get at.
633 default: llvm_unreachable("Unexpected opcode!");
634 case PPC::STB: Opc = PPC::STBX; break;
635 case PPC::STH : Opc = PPC::STHX; break;
636 case PPC::STW : Opc = PPC::STWX; break;
637 case PPC::STB8: Opc = PPC::STBX8; break;
638 case PPC::STH8: Opc = PPC::STHX8; break;
639 case PPC::STW8: Opc = PPC::STWX8; break;
640 case PPC::STD: Opc = PPC::STDX; break;
641 case PPC::STFS: Opc = PPC::STFSX; break;
642 case PPC::STFD: Opc = PPC::STFDX; break;
644 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
645 .addReg(SrcReg).addReg(Addr.Base.Reg).addReg(IndexReg);
651 // Attempt to fast-select a store instruction.
652 bool PPCFastISel::SelectStore(const Instruction *I) {
653 Value *Op0 = I->getOperand(0);
656 // FIXME: No atomics loads are supported.
657 if (cast<StoreInst>(I)->isAtomic())
660 // Verify we have a legal type before going any further.
662 if (!isLoadTypeLegal(Op0->getType(), VT))
665 // Get the value to be stored into a register.
666 SrcReg = getRegForValue(Op0);
670 // See if we can handle this address.
672 if (!PPCComputeAddress(I->getOperand(1), Addr))
675 if (!PPCEmitStore(VT, SrcReg, Addr))
681 // Attempt to fast-select a branch instruction.
682 bool PPCFastISel::SelectBranch(const Instruction *I) {
683 const BranchInst *BI = cast<BranchInst>(I);
684 MachineBasicBlock *BrBB = FuncInfo.MBB;
685 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
686 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
688 // For now, just try the simplest case where it's fed by a compare.
689 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
690 Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
694 PPC::Predicate PPCPred = OptPPCPred.getValue();
696 // Take advantage of fall-through opportunities.
697 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
699 PPCPred = PPC::InvertPredicate(PPCPred);
702 unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
704 if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
708 BuildMI(*BrBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::BCC))
709 .addImm(PPCPred).addReg(CondReg).addMBB(TBB);
710 FastEmitBranch(FBB, DbgLoc);
711 FuncInfo.MBB->addSuccessor(TBB);
714 } else if (const ConstantInt *CI =
715 dyn_cast<ConstantInt>(BI->getCondition())) {
716 uint64_t Imm = CI->getZExtValue();
717 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
718 FastEmitBranch(Target, DbgLoc);
722 // FIXME: ARM looks for a case where the block containing the compare
723 // has been split from the block containing the branch. If this happens,
724 // there is a vreg available containing the result of the compare. I'm
725 // not sure we can do much, as we've lost the predicate information with
726 // the compare instruction -- we have a 4-bit CR but don't know which bit
731 // Attempt to emit a compare of the two source values. Signed and unsigned
732 // comparisons are supported. Return false if we can't handle it.
733 bool PPCFastISel::PPCEmitCmp(const Value *SrcValue1, const Value *SrcValue2,
734 bool IsZExt, unsigned DestReg) {
735 Type *Ty = SrcValue1->getType();
736 EVT SrcEVT = TLI.getValueType(Ty, true);
737 if (!SrcEVT.isSimple())
739 MVT SrcVT = SrcEVT.getSimpleVT();
741 if (SrcVT == MVT::i1 && PPCSubTarget->useCRBits())
744 // See if operand 2 is an immediate encodeable in the compare.
745 // FIXME: Operands are not in canonical order at -O0, so an immediate
746 // operand in position 1 is a lost opportunity for now. We are
747 // similar to ARM in this regard.
751 // Only 16-bit integer constants can be represented in compares for
752 // PowerPC. Others will be materialized into a register.
753 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(SrcValue2)) {
754 if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
755 SrcVT == MVT::i8 || SrcVT == MVT::i1) {
756 const APInt &CIVal = ConstInt->getValue();
757 Imm = (IsZExt) ? (long)CIVal.getZExtValue() : (long)CIVal.getSExtValue();
758 if ((IsZExt && isUInt<16>(Imm)) || (!IsZExt && isInt<16>(Imm)))
764 bool NeedsExt = false;
765 switch (SrcVT.SimpleTy) {
766 default: return false;
768 CmpOpc = PPC::FCMPUS;
771 CmpOpc = PPC::FCMPUD;
777 // Intentional fall-through.
780 CmpOpc = IsZExt ? PPC::CMPLW : PPC::CMPW;
782 CmpOpc = IsZExt ? PPC::CMPLWI : PPC::CMPWI;
786 CmpOpc = IsZExt ? PPC::CMPLD : PPC::CMPD;
788 CmpOpc = IsZExt ? PPC::CMPLDI : PPC::CMPDI;
792 unsigned SrcReg1 = getRegForValue(SrcValue1);
796 unsigned SrcReg2 = 0;
798 SrcReg2 = getRegForValue(SrcValue2);
804 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
805 if (!PPCEmitIntExt(SrcVT, SrcReg1, MVT::i32, ExtReg, IsZExt))
810 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
811 if (!PPCEmitIntExt(SrcVT, SrcReg2, MVT::i32, ExtReg, IsZExt))
818 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc), DestReg)
819 .addReg(SrcReg1).addReg(SrcReg2);
821 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc), DestReg)
822 .addReg(SrcReg1).addImm(Imm);
827 // Attempt to fast-select a floating-point extend instruction.
828 bool PPCFastISel::SelectFPExt(const Instruction *I) {
829 Value *Src = I->getOperand(0);
830 EVT SrcVT = TLI.getValueType(Src->getType(), true);
831 EVT DestVT = TLI.getValueType(I->getType(), true);
833 if (SrcVT != MVT::f32 || DestVT != MVT::f64)
836 unsigned SrcReg = getRegForValue(Src);
840 // No code is generated for a FP extend.
841 UpdateValueMap(I, SrcReg);
845 // Attempt to fast-select a floating-point truncate instruction.
846 bool PPCFastISel::SelectFPTrunc(const Instruction *I) {
847 Value *Src = I->getOperand(0);
848 EVT SrcVT = TLI.getValueType(Src->getType(), true);
849 EVT DestVT = TLI.getValueType(I->getType(), true);
851 if (SrcVT != MVT::f64 || DestVT != MVT::f32)
854 unsigned SrcReg = getRegForValue(Src);
858 // Round the result to single precision.
859 unsigned DestReg = createResultReg(&PPC::F4RCRegClass);
860 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::FRSP), DestReg)
863 UpdateValueMap(I, DestReg);
867 // Move an i32 or i64 value in a GPR to an f64 value in an FPR.
868 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
869 // those should be used instead of moving via a stack slot when the
870 // subtarget permits.
871 // FIXME: The code here is sloppy for the 4-byte case. Can use a 4-byte
872 // stack slot and 4-byte store/load sequence. Or just sext the 4-byte
873 // case to 8 bytes which produces tighter code but wastes stack space.
874 unsigned PPCFastISel::PPCMoveToFPReg(MVT SrcVT, unsigned SrcReg,
877 // If necessary, extend 32-bit int to 64-bit.
878 if (SrcVT == MVT::i32) {
879 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
880 if (!PPCEmitIntExt(MVT::i32, SrcReg, MVT::i64, TmpReg, !IsSigned))
885 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
887 Addr.BaseType = Address::FrameIndexBase;
888 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
890 // Store the value from the GPR.
891 if (!PPCEmitStore(MVT::i64, SrcReg, Addr))
894 // Load the integer value into an FPR. The kind of load used depends
895 // on a number of conditions.
896 unsigned LoadOpc = PPC::LFD;
898 if (SrcVT == MVT::i32) {
900 LoadOpc = PPC::LFIWZX;
902 } else if (PPCSubTarget->hasLFIWAX()) {
903 LoadOpc = PPC::LFIWAX;
908 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
909 unsigned ResultReg = 0;
910 if (!PPCEmitLoad(MVT::f64, ResultReg, Addr, RC, !IsSigned, LoadOpc))
916 // Attempt to fast-select an integer-to-floating-point conversion.
917 bool PPCFastISel::SelectIToFP(const Instruction *I, bool IsSigned) {
919 Type *DstTy = I->getType();
920 if (!isTypeLegal(DstTy, DstVT))
923 if (DstVT != MVT::f32 && DstVT != MVT::f64)
926 Value *Src = I->getOperand(0);
927 EVT SrcEVT = TLI.getValueType(Src->getType(), true);
928 if (!SrcEVT.isSimple())
931 MVT SrcVT = SrcEVT.getSimpleVT();
933 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 &&
934 SrcVT != MVT::i32 && SrcVT != MVT::i64)
937 unsigned SrcReg = getRegForValue(Src);
941 // We can only lower an unsigned convert if we have the newer
942 // floating-point conversion operations.
943 if (!IsSigned && !PPCSubTarget->hasFPCVT())
946 // FIXME: For now we require the newer floating-point conversion operations
947 // (which are present only on P7 and A2 server models) when converting
948 // to single-precision float. Otherwise we have to generate a lot of
949 // fiddly code to avoid double rounding. If necessary, the fiddly code
950 // can be found in PPCTargetLowering::LowerINT_TO_FP().
951 if (DstVT == MVT::f32 && !PPCSubTarget->hasFPCVT())
954 // Extend the input if necessary.
955 if (SrcVT == MVT::i8 || SrcVT == MVT::i16) {
956 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
957 if (!PPCEmitIntExt(SrcVT, SrcReg, MVT::i64, TmpReg, !IsSigned))
963 // Move the integer value to an FPR.
964 unsigned FPReg = PPCMoveToFPReg(SrcVT, SrcReg, IsSigned);
968 // Determine the opcode for the conversion.
969 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
970 unsigned DestReg = createResultReg(RC);
973 if (DstVT == MVT::f32)
974 Opc = IsSigned ? PPC::FCFIDS : PPC::FCFIDUS;
976 Opc = IsSigned ? PPC::FCFID : PPC::FCFIDU;
978 // Generate the convert.
979 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
982 UpdateValueMap(I, DestReg);
986 // Move the floating-point value in SrcReg into an integer destination
987 // register, and return the register (or zero if we can't handle it).
988 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
989 // those should be used instead of moving via a stack slot when the
990 // subtarget permits.
991 unsigned PPCFastISel::PPCMoveToIntReg(const Instruction *I, MVT VT,
992 unsigned SrcReg, bool IsSigned) {
993 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
994 // Note that if have STFIWX available, we could use a 4-byte stack
995 // slot for i32, but this being fast-isel we'll just go with the
996 // easiest code gen possible.
998 Addr.BaseType = Address::FrameIndexBase;
999 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
1001 // Store the value from the FPR.
1002 if (!PPCEmitStore(MVT::f64, SrcReg, Addr))
1005 // Reload it into a GPR. If we want an i32, modify the address
1006 // to have a 4-byte offset so we load from the right place.
1010 // Look at the currently assigned register for this instruction
1011 // to determine the required register class.
1012 unsigned AssignedReg = FuncInfo.ValueMap[I];
1013 const TargetRegisterClass *RC =
1014 AssignedReg ? MRI.getRegClass(AssignedReg) : nullptr;
1016 unsigned ResultReg = 0;
1017 if (!PPCEmitLoad(VT, ResultReg, Addr, RC, !IsSigned))
1023 // Attempt to fast-select a floating-point-to-integer conversion.
1024 bool PPCFastISel::SelectFPToI(const Instruction *I, bool IsSigned) {
1026 Type *DstTy = I->getType();
1027 if (!isTypeLegal(DstTy, DstVT))
1030 if (DstVT != MVT::i32 && DstVT != MVT::i64)
1033 Value *Src = I->getOperand(0);
1034 Type *SrcTy = Src->getType();
1035 if (!isTypeLegal(SrcTy, SrcVT))
1038 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
1041 unsigned SrcReg = getRegForValue(Src);
1045 // Convert f32 to f64 if necessary. This is just a meaningless copy
1046 // to get the register class right. COPY_TO_REGCLASS is needed since
1047 // a COPY from F4RC to F8RC is converted to a F4RC-F4RC copy downstream.
1048 const TargetRegisterClass *InRC = MRI.getRegClass(SrcReg);
1049 if (InRC == &PPC::F4RCRegClass) {
1050 unsigned TmpReg = createResultReg(&PPC::F8RCRegClass);
1051 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1052 TII.get(TargetOpcode::COPY_TO_REGCLASS), TmpReg)
1053 .addReg(SrcReg).addImm(PPC::F8RCRegClassID);
1057 // Determine the opcode for the conversion, which takes place
1058 // entirely within FPRs.
1059 unsigned DestReg = createResultReg(&PPC::F8RCRegClass);
1062 if (DstVT == MVT::i32)
1066 Opc = PPCSubTarget->hasFPCVT() ? PPC::FCTIWUZ : PPC::FCTIDZ;
1068 Opc = IsSigned ? PPC::FCTIDZ : PPC::FCTIDUZ;
1070 // Generate the convert.
1071 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1074 // Now move the integer value from a float register to an integer register.
1075 unsigned IntReg = PPCMoveToIntReg(I, DstVT, DestReg, IsSigned);
1079 UpdateValueMap(I, IntReg);
1083 // Attempt to fast-select a binary integer operation that isn't already
1084 // handled automatically.
1085 bool PPCFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1086 EVT DestVT = TLI.getValueType(I->getType(), true);
1088 // We can get here in the case when we have a binary operation on a non-legal
1089 // type and the target independent selector doesn't know how to handle it.
1090 if (DestVT != MVT::i16 && DestVT != MVT::i8)
1093 // Look at the currently assigned register for this instruction
1094 // to determine the required register class. If there is no register,
1095 // make a conservative choice (don't assign R0).
1096 unsigned AssignedReg = FuncInfo.ValueMap[I];
1097 const TargetRegisterClass *RC =
1098 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1099 &PPC::GPRC_and_GPRC_NOR0RegClass);
1100 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1103 switch (ISDOpcode) {
1104 default: return false;
1106 Opc = IsGPRC ? PPC::ADD4 : PPC::ADD8;
1109 Opc = IsGPRC ? PPC::OR : PPC::OR8;
1112 Opc = IsGPRC ? PPC::SUBF : PPC::SUBF8;
1116 unsigned ResultReg = createResultReg(RC ? RC : &PPC::G8RCRegClass);
1117 unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1118 if (SrcReg1 == 0) return false;
1120 // Handle case of small immediate operand.
1121 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(1))) {
1122 const APInt &CIVal = ConstInt->getValue();
1123 int Imm = (int)CIVal.getSExtValue();
1125 if (isInt<16>(Imm)) {
1128 llvm_unreachable("Missing case!");
1131 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1135 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1148 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1157 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1164 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
1168 UpdateValueMap(I, ResultReg);
1175 unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1176 if (SrcReg2 == 0) return false;
1178 // Reverse operands for subtract-from.
1179 if (ISDOpcode == ISD::SUB)
1180 std::swap(SrcReg1, SrcReg2);
1182 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1183 .addReg(SrcReg1).addReg(SrcReg2);
1184 UpdateValueMap(I, ResultReg);
1188 // Handle arguments to a call that we're attempting to fast-select.
1189 // Return false if the arguments are too complex for us at the moment.
1190 bool PPCFastISel::processCallArgs(SmallVectorImpl<Value*> &Args,
1191 SmallVectorImpl<unsigned> &ArgRegs,
1192 SmallVectorImpl<MVT> &ArgVTs,
1193 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1194 SmallVectorImpl<unsigned> &RegArgs,
1198 SmallVector<CCValAssign, 16> ArgLocs;
1199 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, ArgLocs, *Context);
1201 // Reserve space for the linkage area on the stack.
1202 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false);
1203 CCInfo.AllocateStack(LinkageSize, 8);
1205 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_PPC64_ELF_FIS);
1207 // Bail out if we can't handle any of the arguments.
1208 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1209 CCValAssign &VA = ArgLocs[I];
1210 MVT ArgVT = ArgVTs[VA.getValNo()];
1212 // Skip vector arguments for now, as well as long double and
1213 // uint128_t, and anything that isn't passed in a register.
1214 if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64 || ArgVT == MVT::i1 ||
1215 !VA.isRegLoc() || VA.needsCustom())
1218 // Skip bit-converted arguments for now.
1219 if (VA.getLocInfo() == CCValAssign::BCvt)
1223 // Get a count of how many bytes are to be pushed onto the stack.
1224 NumBytes = CCInfo.getNextStackOffset();
1226 // The prolog code of the callee may store up to 8 GPR argument registers to
1227 // the stack, allowing va_start to index over them in memory if its varargs.
1228 // Because we cannot tell if this is needed on the caller side, we have to
1229 // conservatively assume that it is needed. As such, make sure we have at
1230 // least enough stack space for the caller to store the 8 GPRs.
1231 NumBytes = std::max(NumBytes, LinkageSize + 64);
1233 // Issue CALLSEQ_START.
1234 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1235 TII.get(TII.getCallFrameSetupOpcode()))
1238 // Prepare to assign register arguments. Every argument uses up a
1239 // GPR protocol register even if it's passed in a floating-point
1241 unsigned NextGPR = PPC::X3;
1242 unsigned NextFPR = PPC::F1;
1244 // Process arguments.
1245 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1246 CCValAssign &VA = ArgLocs[I];
1247 unsigned Arg = ArgRegs[VA.getValNo()];
1248 MVT ArgVT = ArgVTs[VA.getValNo()];
1250 // Handle argument promotion and bitcasts.
1251 switch (VA.getLocInfo()) {
1253 llvm_unreachable("Unknown loc info!");
1254 case CCValAssign::Full:
1256 case CCValAssign::SExt: {
1257 MVT DestVT = VA.getLocVT();
1258 const TargetRegisterClass *RC =
1259 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1260 unsigned TmpReg = createResultReg(RC);
1261 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/false))
1262 llvm_unreachable("Failed to emit a sext!");
1267 case CCValAssign::AExt:
1268 case CCValAssign::ZExt: {
1269 MVT DestVT = VA.getLocVT();
1270 const TargetRegisterClass *RC =
1271 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1272 unsigned TmpReg = createResultReg(RC);
1273 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/true))
1274 llvm_unreachable("Failed to emit a zext!");
1279 case CCValAssign::BCvt: {
1280 // FIXME: Not yet handled.
1281 llvm_unreachable("Should have bailed before getting here!");
1286 // Copy this argument to the appropriate register.
1288 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) {
1294 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1295 TII.get(TargetOpcode::COPY), ArgReg).addReg(Arg);
1296 RegArgs.push_back(ArgReg);
1302 // For a call that we've determined we can fast-select, finish the
1303 // call sequence and generate a copy to obtain the return value (if any).
1304 void PPCFastISel::finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1305 const Instruction *I, CallingConv::ID CC,
1306 unsigned &NumBytes, bool IsVarArg) {
1307 // Issue CallSEQ_END.
1308 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1309 TII.get(TII.getCallFrameDestroyOpcode()))
1310 .addImm(NumBytes).addImm(0);
1312 // Next, generate a copy to obtain the return value.
1313 // FIXME: No multi-register return values yet, though I don't foresee
1314 // any real difficulties there.
1315 if (RetVT != MVT::isVoid) {
1316 SmallVector<CCValAssign, 16> RVLocs;
1317 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
1318 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1319 CCValAssign &VA = RVLocs[0];
1320 assert(RVLocs.size() == 1 && "No support for multi-reg return values!");
1321 assert(VA.isRegLoc() && "Can only return in registers!");
1323 MVT DestVT = VA.getValVT();
1324 MVT CopyVT = DestVT;
1326 // Ints smaller than a register still arrive in a full 64-bit
1327 // register, so make sure we recognize this.
1328 if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32)
1331 unsigned SourcePhysReg = VA.getLocReg();
1332 unsigned ResultReg = 0;
1334 if (RetVT == CopyVT) {
1335 const TargetRegisterClass *CpyRC = TLI.getRegClassFor(CopyVT);
1336 ResultReg = createResultReg(CpyRC);
1338 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1339 TII.get(TargetOpcode::COPY), ResultReg)
1340 .addReg(SourcePhysReg);
1342 // If necessary, round the floating result to single precision.
1343 } else if (CopyVT == MVT::f64) {
1344 ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1345 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::FRSP),
1346 ResultReg).addReg(SourcePhysReg);
1348 // If only the low half of a general register is needed, generate
1349 // a GPRC copy instead of a G8RC copy. (EXTRACT_SUBREG can't be
1350 // used along the fast-isel path (not lowered), and downstream logic
1351 // also doesn't like a direct subreg copy on a physical reg.)
1352 } else if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32) {
1353 ResultReg = createResultReg(&PPC::GPRCRegClass);
1354 // Convert physical register from G8RC to GPRC.
1355 SourcePhysReg -= PPC::X0 - PPC::R0;
1356 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1357 TII.get(TargetOpcode::COPY), ResultReg)
1358 .addReg(SourcePhysReg);
1361 assert(ResultReg && "ResultReg unset!");
1362 UsedRegs.push_back(SourcePhysReg);
1363 UpdateValueMap(I, ResultReg);
1367 // Attempt to fast-select a call instruction.
1368 bool PPCFastISel::SelectCall(const Instruction *I) {
1369 const CallInst *CI = cast<CallInst>(I);
1370 const Value *Callee = CI->getCalledValue();
1372 // Can't handle inline asm.
1373 if (isa<InlineAsm>(Callee))
1376 // Allow SelectionDAG isel to handle tail calls.
1377 if (CI->isTailCall())
1380 // Obtain calling convention.
1381 ImmutableCallSite CS(CI);
1382 CallingConv::ID CC = CS.getCallingConv();
1384 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1385 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1386 bool IsVarArg = FTy->isVarArg();
1388 // Not ready for varargs yet.
1392 // Handle simple calls for now, with legal return types and
1393 // those that can be extended.
1394 Type *RetTy = I->getType();
1396 if (RetTy->isVoidTy())
1397 RetVT = MVT::isVoid;
1398 else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
1402 // FIXME: No multi-register return values yet.
1403 if (RetVT != MVT::isVoid && RetVT != MVT::i8 && RetVT != MVT::i16 &&
1404 RetVT != MVT::i32 && RetVT != MVT::i64 && RetVT != MVT::f32 &&
1405 RetVT != MVT::f64) {
1406 SmallVector<CCValAssign, 16> RVLocs;
1407 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
1408 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1409 if (RVLocs.size() > 1)
1413 // Bail early if more than 8 arguments, as we only currently
1414 // handle arguments passed in registers.
1415 unsigned NumArgs = CS.arg_size();
1419 // Set up the argument vectors.
1420 SmallVector<Value*, 8> Args;
1421 SmallVector<unsigned, 8> ArgRegs;
1422 SmallVector<MVT, 8> ArgVTs;
1423 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1425 Args.reserve(NumArgs);
1426 ArgRegs.reserve(NumArgs);
1427 ArgVTs.reserve(NumArgs);
1428 ArgFlags.reserve(NumArgs);
1430 for (ImmutableCallSite::arg_iterator II = CS.arg_begin(), IE = CS.arg_end();
1432 // FIXME: ARM does something for intrinsic calls here, check into that.
1434 unsigned AttrIdx = II - CS.arg_begin() + 1;
1436 // Only handle easy calls for now. It would be reasonably easy
1437 // to handle <= 8-byte structures passed ByVal in registers, but we
1438 // have to ensure they are right-justified in the register.
1439 if (CS.paramHasAttr(AttrIdx, Attribute::InReg) ||
1440 CS.paramHasAttr(AttrIdx, Attribute::StructRet) ||
1441 CS.paramHasAttr(AttrIdx, Attribute::Nest) ||
1442 CS.paramHasAttr(AttrIdx, Attribute::ByVal))
1445 ISD::ArgFlagsTy Flags;
1446 if (CS.paramHasAttr(AttrIdx, Attribute::SExt))
1448 if (CS.paramHasAttr(AttrIdx, Attribute::ZExt))
1451 Type *ArgTy = (*II)->getType();
1453 if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8)
1456 if (ArgVT.isVector())
1459 unsigned Arg = getRegForValue(*II);
1463 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
1464 Flags.setOrigAlign(OriginalAlignment);
1466 Args.push_back(*II);
1467 ArgRegs.push_back(Arg);
1468 ArgVTs.push_back(ArgVT);
1469 ArgFlags.push_back(Flags);
1472 // Process the arguments.
1473 SmallVector<unsigned, 8> RegArgs;
1476 if (!processCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
1477 RegArgs, CC, NumBytes, IsVarArg))
1480 // FIXME: No handling for function pointers yet. This requires
1481 // implementing the function descriptor (OPD) setup.
1482 const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1486 // Build direct call with NOP for TOC restore.
1487 // FIXME: We can and should optimize away the NOP for local calls.
1488 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1489 TII.get(PPC::BL8_NOP));
1491 MIB.addGlobalAddress(GV);
1493 // Add implicit physical register uses to the call.
1494 for (unsigned II = 0, IE = RegArgs.size(); II != IE; ++II)
1495 MIB.addReg(RegArgs[II], RegState::Implicit);
1497 // Add a register mask with the call-preserved registers. Proper
1498 // defs for return values will be added by setPhysRegsDeadExcept().
1499 MIB.addRegMask(TRI.getCallPreservedMask(CC));
1501 // Finish off the call including any return values.
1502 SmallVector<unsigned, 4> UsedRegs;
1503 finishCall(RetVT, UsedRegs, I, CC, NumBytes, IsVarArg);
1505 // Set all unused physregs defs as dead.
1506 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1511 // Attempt to fast-select a return instruction.
1512 bool PPCFastISel::SelectRet(const Instruction *I) {
1514 if (!FuncInfo.CanLowerReturn)
1517 const ReturnInst *Ret = cast<ReturnInst>(I);
1518 const Function &F = *I->getParent()->getParent();
1520 // Build a list of return value registers.
1521 SmallVector<unsigned, 4> RetRegs;
1522 CallingConv::ID CC = F.getCallingConv();
1524 if (Ret->getNumOperands() > 0) {
1525 SmallVector<ISD::OutputArg, 4> Outs;
1526 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1528 // Analyze operands of the call, assigning locations to each operand.
1529 SmallVector<CCValAssign, 16> ValLocs;
1530 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs, *Context);
1531 CCInfo.AnalyzeReturn(Outs, RetCC_PPC64_ELF_FIS);
1532 const Value *RV = Ret->getOperand(0);
1534 // FIXME: Only one output register for now.
1535 if (ValLocs.size() > 1)
1538 // Special case for returning a constant integer of any size.
1539 // Materialize the constant as an i64 and copy it to the return
1540 // register. This avoids an unnecessary extend or truncate.
1541 if (isa<ConstantInt>(*RV)) {
1542 const Constant *C = cast<Constant>(RV);
1543 unsigned SrcReg = PPCMaterializeInt(C, MVT::i64);
1544 unsigned RetReg = ValLocs[0].getLocReg();
1545 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1546 TII.get(TargetOpcode::COPY), RetReg).addReg(SrcReg);
1547 RetRegs.push_back(RetReg);
1550 unsigned Reg = getRegForValue(RV);
1555 // Copy the result values into the output registers.
1556 for (unsigned i = 0; i < ValLocs.size(); ++i) {
1558 CCValAssign &VA = ValLocs[i];
1559 assert(VA.isRegLoc() && "Can only return in registers!");
1560 RetRegs.push_back(VA.getLocReg());
1561 unsigned SrcReg = Reg + VA.getValNo();
1563 EVT RVEVT = TLI.getValueType(RV->getType());
1564 if (!RVEVT.isSimple())
1566 MVT RVVT = RVEVT.getSimpleVT();
1567 MVT DestVT = VA.getLocVT();
1569 if (RVVT != DestVT && RVVT != MVT::i8 &&
1570 RVVT != MVT::i16 && RVVT != MVT::i32)
1573 if (RVVT != DestVT) {
1574 switch (VA.getLocInfo()) {
1576 llvm_unreachable("Unknown loc info!");
1577 case CCValAssign::Full:
1578 llvm_unreachable("Full value assign but types don't match?");
1579 case CCValAssign::AExt:
1580 case CCValAssign::ZExt: {
1581 const TargetRegisterClass *RC =
1582 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1583 unsigned TmpReg = createResultReg(RC);
1584 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, true))
1589 case CCValAssign::SExt: {
1590 const TargetRegisterClass *RC =
1591 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1592 unsigned TmpReg = createResultReg(RC);
1593 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, false))
1601 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1602 TII.get(TargetOpcode::COPY), RetRegs[i])
1608 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1611 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1612 MIB.addReg(RetRegs[i], RegState::Implicit);
1617 // Attempt to emit an integer extend of SrcReg into DestReg. Both
1618 // signed and zero extensions are supported. Return false if we
1620 bool PPCFastISel::PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1621 unsigned DestReg, bool IsZExt) {
1622 if (DestVT != MVT::i32 && DestVT != MVT::i64)
1624 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 && SrcVT != MVT::i32)
1627 // Signed extensions use EXTSB, EXTSH, EXTSW.
1630 if (SrcVT == MVT::i8)
1631 Opc = (DestVT == MVT::i32) ? PPC::EXTSB : PPC::EXTSB8_32_64;
1632 else if (SrcVT == MVT::i16)
1633 Opc = (DestVT == MVT::i32) ? PPC::EXTSH : PPC::EXTSH8_32_64;
1635 assert(DestVT == MVT::i64 && "Signed extend from i32 to i32??");
1636 Opc = PPC::EXTSW_32_64;
1638 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1641 // Unsigned 32-bit extensions use RLWINM.
1642 } else if (DestVT == MVT::i32) {
1644 if (SrcVT == MVT::i8)
1647 assert(SrcVT == MVT::i16 && "Unsigned extend from i32 to i32??");
1650 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::RLWINM),
1652 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB).addImm(/*ME=*/31);
1654 // Unsigned 64-bit extensions use RLDICL (with a 32-bit source).
1657 if (SrcVT == MVT::i8)
1659 else if (SrcVT == MVT::i16)
1663 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1664 TII.get(PPC::RLDICL_32_64), DestReg)
1665 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB);
1671 // Attempt to fast-select an indirect branch instruction.
1672 bool PPCFastISel::SelectIndirectBr(const Instruction *I) {
1673 unsigned AddrReg = getRegForValue(I->getOperand(0));
1677 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::MTCTR8))
1679 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::BCTR8));
1681 const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1682 for (unsigned i = 0, e = IB->getNumSuccessors(); i != e; ++i)
1683 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[IB->getSuccessor(i)]);
1688 // Attempt to fast-select an integer truncate instruction.
1689 bool PPCFastISel::SelectTrunc(const Instruction *I) {
1690 Value *Src = I->getOperand(0);
1691 EVT SrcVT = TLI.getValueType(Src->getType(), true);
1692 EVT DestVT = TLI.getValueType(I->getType(), true);
1694 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16)
1697 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8)
1700 unsigned SrcReg = getRegForValue(Src);
1704 // The only interesting case is when we need to switch register classes.
1705 if (SrcVT == MVT::i64) {
1706 unsigned ResultReg = createResultReg(&PPC::GPRCRegClass);
1707 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1708 TII.get(TargetOpcode::COPY),
1709 ResultReg).addReg(SrcReg, 0, PPC::sub_32);
1713 UpdateValueMap(I, SrcReg);
1717 // Attempt to fast-select an integer extend instruction.
1718 bool PPCFastISel::SelectIntExt(const Instruction *I) {
1719 Type *DestTy = I->getType();
1720 Value *Src = I->getOperand(0);
1721 Type *SrcTy = Src->getType();
1723 bool IsZExt = isa<ZExtInst>(I);
1724 unsigned SrcReg = getRegForValue(Src);
1725 if (!SrcReg) return false;
1727 EVT SrcEVT, DestEVT;
1728 SrcEVT = TLI.getValueType(SrcTy, true);
1729 DestEVT = TLI.getValueType(DestTy, true);
1730 if (!SrcEVT.isSimple())
1732 if (!DestEVT.isSimple())
1735 MVT SrcVT = SrcEVT.getSimpleVT();
1736 MVT DestVT = DestEVT.getSimpleVT();
1738 // If we know the register class needed for the result of this
1739 // instruction, use it. Otherwise pick the register class of the
1740 // correct size that does not contain X0/R0, since we don't know
1741 // whether downstream uses permit that assignment.
1742 unsigned AssignedReg = FuncInfo.ValueMap[I];
1743 const TargetRegisterClass *RC =
1744 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1745 (DestVT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
1746 &PPC::GPRC_and_GPRC_NOR0RegClass));
1747 unsigned ResultReg = createResultReg(RC);
1749 if (!PPCEmitIntExt(SrcVT, SrcReg, DestVT, ResultReg, IsZExt))
1752 UpdateValueMap(I, ResultReg);
1756 // Attempt to fast-select an instruction that wasn't handled by
1757 // the table-generated machinery.
1758 bool PPCFastISel::TargetSelectInstruction(const Instruction *I) {
1760 switch (I->getOpcode()) {
1761 case Instruction::Load:
1762 return SelectLoad(I);
1763 case Instruction::Store:
1764 return SelectStore(I);
1765 case Instruction::Br:
1766 return SelectBranch(I);
1767 case Instruction::IndirectBr:
1768 return SelectIndirectBr(I);
1769 case Instruction::FPExt:
1770 return SelectFPExt(I);
1771 case Instruction::FPTrunc:
1772 return SelectFPTrunc(I);
1773 case Instruction::SIToFP:
1774 return SelectIToFP(I, /*IsSigned*/ true);
1775 case Instruction::UIToFP:
1776 return SelectIToFP(I, /*IsSigned*/ false);
1777 case Instruction::FPToSI:
1778 return SelectFPToI(I, /*IsSigned*/ true);
1779 case Instruction::FPToUI:
1780 return SelectFPToI(I, /*IsSigned*/ false);
1781 case Instruction::Add:
1782 return SelectBinaryIntOp(I, ISD::ADD);
1783 case Instruction::Or:
1784 return SelectBinaryIntOp(I, ISD::OR);
1785 case Instruction::Sub:
1786 return SelectBinaryIntOp(I, ISD::SUB);
1787 case Instruction::Call:
1788 if (dyn_cast<IntrinsicInst>(I))
1790 return SelectCall(I);
1791 case Instruction::Ret:
1792 return SelectRet(I);
1793 case Instruction::Trunc:
1794 return SelectTrunc(I);
1795 case Instruction::ZExt:
1796 case Instruction::SExt:
1797 return SelectIntExt(I);
1798 // Here add other flavors of Instruction::XXX that automated
1799 // cases don't catch. For example, switches are terminators
1800 // that aren't yet handled.
1807 // Materialize a floating-point constant into a register, and return
1808 // the register number (or zero if we failed to handle it).
1809 unsigned PPCFastISel::PPCMaterializeFP(const ConstantFP *CFP, MVT VT) {
1810 // No plans to handle long double here.
1811 if (VT != MVT::f32 && VT != MVT::f64)
1814 // All FP constants are loaded from the constant pool.
1815 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
1816 assert(Align > 0 && "Unexpectedly missing alignment information!");
1817 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
1818 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
1819 CodeModel::Model CModel = TM.getCodeModel();
1821 MachineMemOperand *MMO =
1822 FuncInfo.MF->getMachineMemOperand(
1823 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
1824 (VT == MVT::f32) ? 4 : 8, Align);
1826 unsigned Opc = (VT == MVT::f32) ? PPC::LFS : PPC::LFD;
1827 unsigned TmpReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1829 // For small code model, generate a LF[SD](0, LDtocCPT(Idx, X2)).
1830 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault) {
1831 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocCPT),
1833 .addConstantPoolIndex(Idx).addReg(PPC::X2);
1834 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1835 .addImm(0).addReg(TmpReg).addMemOperand(MMO);
1837 // Otherwise we generate LF[SD](Idx[lo], ADDIStocHA(X2, Idx)).
1838 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDIStocHA),
1839 TmpReg).addReg(PPC::X2).addConstantPoolIndex(Idx);
1840 // But for large code model, we must generate a LDtocL followed
1842 if (CModel == CodeModel::Large) {
1843 unsigned TmpReg2 = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1844 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocL),
1845 TmpReg2).addConstantPoolIndex(Idx).addReg(TmpReg);
1846 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1847 .addImm(0).addReg(TmpReg2);
1849 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1850 .addConstantPoolIndex(Idx, 0, PPCII::MO_TOC_LO)
1852 .addMemOperand(MMO);
1858 // Materialize the address of a global value into a register, and return
1859 // the register number (or zero if we failed to handle it).
1860 unsigned PPCFastISel::PPCMaterializeGV(const GlobalValue *GV, MVT VT) {
1861 assert(VT == MVT::i64 && "Non-address!");
1862 const TargetRegisterClass *RC = &PPC::G8RC_and_G8RC_NOX0RegClass;
1863 unsigned DestReg = createResultReg(RC);
1865 // Global values may be plain old object addresses, TLS object
1866 // addresses, constant pool entries, or jump tables. How we generate
1867 // code for these may depend on small, medium, or large code model.
1868 CodeModel::Model CModel = TM.getCodeModel();
1870 // FIXME: Jump tables are not yet required because fast-isel doesn't
1871 // handle switches; if that changes, we need them as well. For now,
1872 // what follows assumes everything's a generic (or TLS) global address.
1874 // FIXME: We don't yet handle the complexity of TLS.
1875 if (GV->isThreadLocal())
1878 // For small code model, generate a simple TOC load.
1879 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault)
1880 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtoc),
1882 .addGlobalAddress(GV)
1885 // If the address is an externally defined symbol, a symbol with common
1886 // or externally available linkage, a non-local function address, or a
1887 // jump table address (not yet needed), or if we are generating code
1888 // for large code model, we generate:
1889 // LDtocL(GV, ADDIStocHA(%X2, GV))
1890 // Otherwise we generate:
1891 // ADDItocL(ADDIStocHA(%X2, GV), GV)
1892 // Either way, start with the ADDIStocHA:
1893 unsigned HighPartReg = createResultReg(RC);
1894 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDIStocHA),
1895 HighPartReg).addReg(PPC::X2).addGlobalAddress(GV);
1897 // If/when switches are implemented, jump tables should be handled
1898 // on the "if" path here.
1899 if (CModel == CodeModel::Large ||
1900 (GV->getType()->getElementType()->isFunctionTy() &&
1901 (GV->isDeclaration() || GV->isWeakForLinker())) ||
1902 GV->isDeclaration() || GV->hasCommonLinkage() ||
1903 GV->hasAvailableExternallyLinkage())
1904 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocL),
1905 DestReg).addGlobalAddress(GV).addReg(HighPartReg);
1907 // Otherwise generate the ADDItocL.
1908 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDItocL),
1909 DestReg).addReg(HighPartReg).addGlobalAddress(GV);
1915 // Materialize a 32-bit integer constant into a register, and return
1916 // the register number (or zero if we failed to handle it).
1917 unsigned PPCFastISel::PPCMaterialize32BitInt(int64_t Imm,
1918 const TargetRegisterClass *RC) {
1919 unsigned Lo = Imm & 0xFFFF;
1920 unsigned Hi = (Imm >> 16) & 0xFFFF;
1922 unsigned ResultReg = createResultReg(RC);
1923 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1926 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1927 TII.get(IsGPRC ? PPC::LI : PPC::LI8), ResultReg)
1930 // Both Lo and Hi have nonzero bits.
1931 unsigned TmpReg = createResultReg(RC);
1932 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1933 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), TmpReg)
1935 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1936 TII.get(IsGPRC ? PPC::ORI : PPC::ORI8), ResultReg)
1937 .addReg(TmpReg).addImm(Lo);
1940 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1941 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), ResultReg)
1947 // Materialize a 64-bit integer constant into a register, and return
1948 // the register number (or zero if we failed to handle it).
1949 unsigned PPCFastISel::PPCMaterialize64BitInt(int64_t Imm,
1950 const TargetRegisterClass *RC) {
1951 unsigned Remainder = 0;
1954 // If the value doesn't fit in 32 bits, see if we can shift it
1955 // so that it fits in 32 bits.
1956 if (!isInt<32>(Imm)) {
1957 Shift = countTrailingZeros<uint64_t>(Imm);
1958 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
1960 if (isInt<32>(ImmSh))
1969 // Handle the high-order 32 bits (if shifted) or the whole 32 bits
1970 // (if not shifted).
1971 unsigned TmpReg1 = PPCMaterialize32BitInt(Imm, RC);
1975 // If upper 32 bits were not zero, we've built them and need to shift
1979 TmpReg2 = createResultReg(RC);
1980 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::RLDICR),
1981 TmpReg2).addReg(TmpReg1).addImm(Shift).addImm(63 - Shift);
1985 unsigned TmpReg3, Hi, Lo;
1986 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
1987 TmpReg3 = createResultReg(RC);
1988 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ORIS8),
1989 TmpReg3).addReg(TmpReg2).addImm(Hi);
1993 if ((Lo = Remainder & 0xFFFF)) {
1994 unsigned ResultReg = createResultReg(RC);
1995 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ORI8),
1996 ResultReg).addReg(TmpReg3).addImm(Lo);
2004 // Materialize an integer constant into a register, and return
2005 // the register number (or zero if we failed to handle it).
2006 unsigned PPCFastISel::PPCMaterializeInt(const Constant *C, MVT VT) {
2007 // If we're using CR bit registers for i1 values, handle that as a special
2009 if (VT == MVT::i1 && PPCSubTarget->useCRBits()) {
2010 const ConstantInt *CI = cast<ConstantInt>(C);
2011 unsigned ImmReg = createResultReg(&PPC::CRBITRCRegClass);
2012 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2013 TII.get(CI->isZero() ? PPC::CRUNSET : PPC::CRSET), ImmReg);
2017 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2018 VT != MVT::i8 && VT != MVT::i1)
2021 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2022 &PPC::GPRCRegClass);
2024 // If the constant is in range, use a load-immediate.
2025 const ConstantInt *CI = cast<ConstantInt>(C);
2026 if (isInt<16>(CI->getSExtValue())) {
2027 unsigned Opc = (VT == MVT::i64) ? PPC::LI8 : PPC::LI;
2028 unsigned ImmReg = createResultReg(RC);
2029 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ImmReg)
2030 .addImm(CI->getSExtValue());
2034 // Construct the constant piecewise.
2035 int64_t Imm = CI->getZExtValue();
2038 return PPCMaterialize64BitInt(Imm, RC);
2039 else if (VT == MVT::i32)
2040 return PPCMaterialize32BitInt(Imm, RC);
2045 // Materialize a constant into a register, and return the register
2046 // number (or zero if we failed to handle it).
2047 unsigned PPCFastISel::TargetMaterializeConstant(const Constant *C) {
2048 EVT CEVT = TLI.getValueType(C->getType(), true);
2050 // Only handle simple types.
2051 if (!CEVT.isSimple()) return 0;
2052 MVT VT = CEVT.getSimpleVT();
2054 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
2055 return PPCMaterializeFP(CFP, VT);
2056 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
2057 return PPCMaterializeGV(GV, VT);
2058 else if (isa<ConstantInt>(C))
2059 return PPCMaterializeInt(C, VT);
2064 // Materialize the address created by an alloca into a register, and
2065 // return the register number (or zero if we failed to handle it).
2066 unsigned PPCFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
2067 // Don't handle dynamic allocas.
2068 if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
2071 if (!isLoadTypeLegal(AI->getType(), VT)) return 0;
2073 DenseMap<const AllocaInst*, int>::iterator SI =
2074 FuncInfo.StaticAllocaMap.find(AI);
2076 if (SI != FuncInfo.StaticAllocaMap.end()) {
2077 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
2078 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDI8),
2079 ResultReg).addFrameIndex(SI->second).addImm(0);
2086 // Fold loads into extends when possible.
2087 // FIXME: We can have multiple redundant extend/trunc instructions
2088 // following a load. The folding only picks up one. Extend this
2089 // to check subsequent instructions for the same pattern and remove
2090 // them. Thus ResultReg should be the def reg for the last redundant
2091 // instruction in a chain, and all intervening instructions can be
2092 // removed from parent. Change test/CodeGen/PowerPC/fast-isel-fold.ll
2093 // to add ELF64-NOT: rldicl to the appropriate tests when this works.
2094 bool PPCFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2095 const LoadInst *LI) {
2096 // Verify we have a legal type before going any further.
2098 if (!isLoadTypeLegal(LI->getType(), VT))
2101 // Combine load followed by zero- or sign-extend.
2102 bool IsZExt = false;
2103 switch(MI->getOpcode()) {
2108 case PPC::RLDICL_32_64: {
2110 unsigned MB = MI->getOperand(3).getImm();
2111 if ((VT == MVT::i8 && MB <= 56) ||
2112 (VT == MVT::i16 && MB <= 48) ||
2113 (VT == MVT::i32 && MB <= 32))
2119 case PPC::RLWINM8: {
2121 unsigned MB = MI->getOperand(3).getImm();
2122 if ((VT == MVT::i8 && MB <= 24) ||
2123 (VT == MVT::i16 && MB <= 16))
2130 case PPC::EXTSB8_32_64:
2131 /* There is no sign-extending load-byte instruction. */
2136 case PPC::EXTSH8_32_64: {
2137 if (VT != MVT::i16 && VT != MVT::i8)
2143 case PPC::EXTSW_32_64: {
2144 if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8)
2150 // See if we can handle this address.
2152 if (!PPCComputeAddress(LI->getOperand(0), Addr))
2155 unsigned ResultReg = MI->getOperand(0).getReg();
2157 if (!PPCEmitLoad(VT, ResultReg, Addr, nullptr, IsZExt))
2160 MI->eraseFromParent();
2164 // Attempt to lower call arguments in a faster way than done by
2165 // the selection DAG code.
2166 bool PPCFastISel::FastLowerArguments() {
2167 // Defer to normal argument lowering for now. It's reasonably
2168 // efficient. Consider doing something like ARM to handle the
2169 // case where all args fit in registers, no varargs, no float
2174 // Handle materializing integer constants into a register. This is not
2175 // automatically generated for PowerPC, so must be explicitly created here.
2176 unsigned PPCFastISel::FastEmit_i(MVT Ty, MVT VT, unsigned Opc, uint64_t Imm) {
2178 if (Opc != ISD::Constant)
2181 // If we're using CR bit registers for i1 values, handle that as a special
2183 if (VT == MVT::i1 && PPCSubTarget->useCRBits()) {
2184 unsigned ImmReg = createResultReg(&PPC::CRBITRCRegClass);
2185 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2186 TII.get(Imm == 0 ? PPC::CRUNSET : PPC::CRSET), ImmReg);
2190 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2191 VT != MVT::i8 && VT != MVT::i1)
2194 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2195 &PPC::GPRCRegClass);
2197 return PPCMaterialize64BitInt(Imm, RC);
2199 return PPCMaterialize32BitInt(Imm, RC);
2202 // Override for ADDI and ADDI8 to set the correct register class
2203 // on RHS operand 0. The automatic infrastructure naively assumes
2204 // GPRC for i32 and G8RC for i64; the concept of "no R0" is lost
2205 // for these cases. At the moment, none of the other automatically
2206 // generated RI instructions require special treatment. However, once
2207 // SelectSelect is implemented, "isel" requires similar handling.
2209 // Also be conservative about the output register class. Avoid
2210 // assigning R0 or X0 to the output register for GPRC and G8RC
2211 // register classes, as any such result could be used in ADDI, etc.,
2212 // where those regs have another meaning.
2213 unsigned PPCFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
2214 const TargetRegisterClass *RC,
2215 unsigned Op0, bool Op0IsKill,
2217 if (MachineInstOpcode == PPC::ADDI)
2218 MRI.setRegClass(Op0, &PPC::GPRC_and_GPRC_NOR0RegClass);
2219 else if (MachineInstOpcode == PPC::ADDI8)
2220 MRI.setRegClass(Op0, &PPC::G8RC_and_G8RC_NOX0RegClass);
2222 const TargetRegisterClass *UseRC =
2223 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2224 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2226 return FastISel::FastEmitInst_ri(MachineInstOpcode, UseRC,
2227 Op0, Op0IsKill, Imm);
2230 // Override for instructions with one register operand to avoid use of
2231 // R0/X0. The automatic infrastructure isn't aware of the context so
2232 // we must be conservative.
2233 unsigned PPCFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
2234 const TargetRegisterClass* RC,
2235 unsigned Op0, bool Op0IsKill) {
2236 const TargetRegisterClass *UseRC =
2237 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2238 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2240 return FastISel::FastEmitInst_r(MachineInstOpcode, UseRC, Op0, Op0IsKill);
2243 // Override for instructions with two register operands to avoid use
2244 // of R0/X0. The automatic infrastructure isn't aware of the context
2245 // so we must be conservative.
2246 unsigned PPCFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
2247 const TargetRegisterClass* RC,
2248 unsigned Op0, bool Op0IsKill,
2249 unsigned Op1, bool Op1IsKill) {
2250 const TargetRegisterClass *UseRC =
2251 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2252 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2254 return FastISel::FastEmitInst_rr(MachineInstOpcode, UseRC, Op0, Op0IsKill,
2259 // Create the fast instruction selector for PowerPC64 ELF.
2260 FastISel *PPC::createFastISel(FunctionLoweringInfo &FuncInfo,
2261 const TargetLibraryInfo *LibInfo) {
2262 const TargetMachine &TM = FuncInfo.MF->getTarget();
2264 // Only available on 64-bit ELF for now.
2265 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
2266 if (Subtarget->isPPC64() && Subtarget->isSVR4ABI())
2267 return new PPCFastISel(FuncInfo, LibInfo);