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 isVSFRCRegister(unsigned Register) const {
143 return MRI.getRegClass(Register)->getID() == PPC::VSFRCRegClassID;
145 bool PPCEmitCmp(const Value *Src1Value, const Value *Src2Value,
146 bool isZExt, unsigned DestReg);
147 bool PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
148 const TargetRegisterClass *RC, bool IsZExt = true,
149 unsigned FP64LoadOpc = PPC::LFD);
150 bool PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr);
151 bool PPCComputeAddress(const Value *Obj, Address &Addr);
152 void PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
154 bool PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
155 unsigned DestReg, bool IsZExt);
156 unsigned PPCMaterializeFP(const ConstantFP *CFP, MVT VT);
157 unsigned PPCMaterializeGV(const GlobalValue *GV, MVT VT);
158 unsigned PPCMaterializeInt(const Constant *C, MVT VT, bool UseSExt = true);
159 unsigned PPCMaterialize32BitInt(int64_t Imm,
160 const TargetRegisterClass *RC);
161 unsigned PPCMaterialize64BitInt(int64_t Imm,
162 const TargetRegisterClass *RC);
163 unsigned PPCMoveToIntReg(const Instruction *I, MVT VT,
164 unsigned SrcReg, bool IsSigned);
165 unsigned PPCMoveToFPReg(MVT VT, unsigned SrcReg, bool IsSigned);
167 // Call handling routines.
169 bool processCallArgs(SmallVectorImpl<Value*> &Args,
170 SmallVectorImpl<unsigned> &ArgRegs,
171 SmallVectorImpl<MVT> &ArgVTs,
172 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
173 SmallVectorImpl<unsigned> &RegArgs,
177 void finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
178 const Instruction *I, CallingConv::ID CC,
179 unsigned &NumBytes, bool IsVarArg);
180 CCAssignFn *usePPC32CCs(unsigned Flag);
183 #include "PPCGenFastISel.inc"
187 } // end anonymous namespace
189 #include "PPCGenCallingConv.inc"
191 // Function whose sole purpose is to kill compiler warnings
192 // stemming from unused functions included from PPCGenCallingConv.inc.
193 CCAssignFn *PPCFastISel::usePPC32CCs(unsigned Flag) {
195 return CC_PPC32_SVR4;
197 return CC_PPC32_SVR4_ByVal;
199 return CC_PPC32_SVR4_VarArg;
204 static Optional<PPC::Predicate> getComparePred(CmpInst::Predicate Pred) {
206 // These are not representable with any single compare.
207 case CmpInst::FCMP_FALSE:
208 case CmpInst::FCMP_UEQ:
209 case CmpInst::FCMP_UGT:
210 case CmpInst::FCMP_UGE:
211 case CmpInst::FCMP_ULT:
212 case CmpInst::FCMP_ULE:
213 case CmpInst::FCMP_UNE:
214 case CmpInst::FCMP_TRUE:
216 return Optional<PPC::Predicate>();
218 case CmpInst::FCMP_OEQ:
219 case CmpInst::ICMP_EQ:
222 case CmpInst::FCMP_OGT:
223 case CmpInst::ICMP_UGT:
224 case CmpInst::ICMP_SGT:
227 case CmpInst::FCMP_OGE:
228 case CmpInst::ICMP_UGE:
229 case CmpInst::ICMP_SGE:
232 case CmpInst::FCMP_OLT:
233 case CmpInst::ICMP_ULT:
234 case CmpInst::ICMP_SLT:
237 case CmpInst::FCMP_OLE:
238 case CmpInst::ICMP_ULE:
239 case CmpInst::ICMP_SLE:
242 case CmpInst::FCMP_ONE:
243 case CmpInst::ICMP_NE:
246 case CmpInst::FCMP_ORD:
249 case CmpInst::FCMP_UNO:
254 // Determine whether the type Ty is simple enough to be handled by
255 // fast-isel, and return its equivalent machine type in VT.
256 // FIXME: Copied directly from ARM -- factor into base class?
257 bool PPCFastISel::isTypeLegal(Type *Ty, MVT &VT) {
258 EVT Evt = TLI.getValueType(Ty, true);
260 // Only handle simple types.
261 if (Evt == MVT::Other || !Evt.isSimple()) return false;
262 VT = Evt.getSimpleVT();
264 // Handle all legal types, i.e. a register that will directly hold this
266 return TLI.isTypeLegal(VT);
269 // Determine whether the type Ty is simple enough to be handled by
270 // fast-isel as a load target, and return its equivalent machine type in VT.
271 bool PPCFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
272 if (isTypeLegal(Ty, VT)) return true;
274 // If this is a type than can be sign or zero-extended to a basic operation
275 // go ahead and accept it now.
276 if (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) {
283 // Given a value Obj, create an Address object Addr that represents its
284 // address. Return false if we can't handle it.
285 bool PPCFastISel::PPCComputeAddress(const Value *Obj, Address &Addr) {
286 const User *U = nullptr;
287 unsigned Opcode = Instruction::UserOp1;
288 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
289 // Don't walk into other basic blocks unless the object is an alloca from
290 // another block, otherwise it may not have a virtual register assigned.
291 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
292 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
293 Opcode = I->getOpcode();
296 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
297 Opcode = C->getOpcode();
304 case Instruction::BitCast:
305 // Look through bitcasts.
306 return PPCComputeAddress(U->getOperand(0), Addr);
307 case Instruction::IntToPtr:
308 // Look past no-op inttoptrs.
309 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
310 return PPCComputeAddress(U->getOperand(0), Addr);
312 case Instruction::PtrToInt:
313 // Look past no-op ptrtoints.
314 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
315 return PPCComputeAddress(U->getOperand(0), Addr);
317 case Instruction::GetElementPtr: {
318 Address SavedAddr = Addr;
319 long TmpOffset = Addr.Offset;
321 // Iterate through the GEP folding the constants into offsets where
323 gep_type_iterator GTI = gep_type_begin(U);
324 for (User::const_op_iterator II = U->op_begin() + 1, IE = U->op_end();
325 II != IE; ++II, ++GTI) {
326 const Value *Op = *II;
327 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
328 const StructLayout *SL = DL.getStructLayout(STy);
329 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
330 TmpOffset += SL->getElementOffset(Idx);
332 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
334 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
335 // Constant-offset addressing.
336 TmpOffset += CI->getSExtValue() * S;
339 if (canFoldAddIntoGEP(U, Op)) {
340 // A compatible add with a constant operand. Fold the constant.
342 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
343 TmpOffset += CI->getSExtValue() * S;
344 // Iterate on the other operand.
345 Op = cast<AddOperator>(Op)->getOperand(0);
349 goto unsupported_gep;
354 // Try to grab the base operand now.
355 Addr.Offset = TmpOffset;
356 if (PPCComputeAddress(U->getOperand(0), Addr)) return true;
358 // We failed, restore everything and try the other options.
364 case Instruction::Alloca: {
365 const AllocaInst *AI = cast<AllocaInst>(Obj);
366 DenseMap<const AllocaInst*, int>::iterator SI =
367 FuncInfo.StaticAllocaMap.find(AI);
368 if (SI != FuncInfo.StaticAllocaMap.end()) {
369 Addr.BaseType = Address::FrameIndexBase;
370 Addr.Base.FI = SI->second;
377 // FIXME: References to parameters fall through to the behavior
378 // below. They should be able to reference a frame index since
379 // they are stored to the stack, so we can get "ld rx, offset(r1)"
380 // instead of "addi ry, r1, offset / ld rx, 0(ry)". Obj will
381 // just contain the parameter. Try to handle this with a FI.
383 // Try to get this in a register if nothing else has worked.
384 if (Addr.Base.Reg == 0)
385 Addr.Base.Reg = getRegForValue(Obj);
387 // Prevent assignment of base register to X0, which is inappropriate
388 // for loads and stores alike.
389 if (Addr.Base.Reg != 0)
390 MRI.setRegClass(Addr.Base.Reg, &PPC::G8RC_and_G8RC_NOX0RegClass);
392 return Addr.Base.Reg != 0;
395 // Fix up some addresses that can't be used directly. For example, if
396 // an offset won't fit in an instruction field, we may need to move it
397 // into an index register.
398 void PPCFastISel::PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
399 unsigned &IndexReg) {
401 // Check whether the offset fits in the instruction field.
402 if (!isInt<16>(Addr.Offset))
405 // If this is a stack pointer and the offset needs to be simplified then
406 // put the alloca address into a register, set the base type back to
407 // register and continue. This should almost never happen.
408 if (!UseOffset && Addr.BaseType == Address::FrameIndexBase) {
409 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
410 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDI8),
411 ResultReg).addFrameIndex(Addr.Base.FI).addImm(0);
412 Addr.Base.Reg = ResultReg;
413 Addr.BaseType = Address::RegBase;
417 IntegerType *OffsetTy = ((VT == MVT::i32) ? Type::getInt32Ty(*Context)
418 : Type::getInt64Ty(*Context));
419 const ConstantInt *Offset =
420 ConstantInt::getSigned(OffsetTy, (int64_t)(Addr.Offset));
421 IndexReg = PPCMaterializeInt(Offset, MVT::i64);
422 assert(IndexReg && "Unexpected error in PPCMaterializeInt!");
426 // Emit a load instruction if possible, returning true if we succeeded,
427 // otherwise false. See commentary below for how the register class of
428 // the load is determined.
429 bool PPCFastISel::PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
430 const TargetRegisterClass *RC,
431 bool IsZExt, unsigned FP64LoadOpc) {
433 bool UseOffset = true;
435 // If ResultReg is given, it determines the register class of the load.
436 // Otherwise, RC is the register class to use. If the result of the
437 // load isn't anticipated in this block, both may be zero, in which
438 // case we must make a conservative guess. In particular, don't assign
439 // R0 or X0 to the result register, as the result may be used in a load,
440 // store, add-immediate, or isel that won't permit this. (Though
441 // perhaps the spill and reload of live-exit values would handle this?)
442 const TargetRegisterClass *UseRC =
443 (ResultReg ? MRI.getRegClass(ResultReg) :
445 (VT == MVT::f64 ? &PPC::F8RCRegClass :
446 (VT == MVT::f32 ? &PPC::F4RCRegClass :
447 (VT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
448 &PPC::GPRC_and_GPRC_NOR0RegClass)))));
450 bool Is32BitInt = UseRC->hasSuperClassEq(&PPC::GPRCRegClass);
452 switch (VT.SimpleTy) {
453 default: // e.g., vector types not handled
456 Opc = Is32BitInt ? PPC::LBZ : PPC::LBZ8;
460 (Is32BitInt ? PPC::LHZ : PPC::LHZ8) :
461 (Is32BitInt ? PPC::LHA : PPC::LHA8));
465 (Is32BitInt ? PPC::LWZ : PPC::LWZ8) :
466 (Is32BitInt ? PPC::LWA_32 : PPC::LWA));
467 if ((Opc == PPC::LWA || Opc == PPC::LWA_32) && ((Addr.Offset & 3) != 0))
472 assert(UseRC->hasSuperClassEq(&PPC::G8RCRegClass) &&
473 "64-bit load with 32-bit target??");
474 UseOffset = ((Addr.Offset & 3) == 0);
484 // If necessary, materialize the offset into a register and use
485 // the indexed form. Also handle stack pointers with special needs.
486 unsigned IndexReg = 0;
487 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
489 // If this is a potential VSX load with an offset of 0, a VSX indexed load can
491 bool IsVSFRC = (ResultReg != 0) && isVSFRCRegister(ResultReg);
492 if (IsVSFRC && (Opc == PPC::LFD) &&
493 (Addr.BaseType != Address::FrameIndexBase) && UseOffset &&
494 (Addr.Offset == 0)) {
499 ResultReg = createResultReg(UseRC);
501 // Note: If we still have a frame index here, we know the offset is
502 // in range, as otherwise PPCSimplifyAddress would have converted it
504 if (Addr.BaseType == Address::FrameIndexBase) {
505 // VSX only provides an indexed load.
506 if (IsVSFRC && Opc == PPC::LFD) return false;
508 MachineMemOperand *MMO =
509 FuncInfo.MF->getMachineMemOperand(
510 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
511 MachineMemOperand::MOLoad, MFI.getObjectSize(Addr.Base.FI),
512 MFI.getObjectAlignment(Addr.Base.FI));
514 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
515 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
517 // Base reg with offset in range.
518 } else if (UseOffset) {
519 // VSX only provides an indexed load.
520 if (IsVSFRC && Opc == PPC::LFD) return false;
522 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
523 .addImm(Addr.Offset).addReg(Addr.Base.Reg);
527 // Get the RR opcode corresponding to the RI one. FIXME: It would be
528 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
529 // is hard to get at.
531 default: llvm_unreachable("Unexpected opcode!");
532 case PPC::LBZ: Opc = PPC::LBZX; break;
533 case PPC::LBZ8: Opc = PPC::LBZX8; break;
534 case PPC::LHZ: Opc = PPC::LHZX; break;
535 case PPC::LHZ8: Opc = PPC::LHZX8; break;
536 case PPC::LHA: Opc = PPC::LHAX; break;
537 case PPC::LHA8: Opc = PPC::LHAX8; break;
538 case PPC::LWZ: Opc = PPC::LWZX; break;
539 case PPC::LWZ8: Opc = PPC::LWZX8; break;
540 case PPC::LWA: Opc = PPC::LWAX; break;
541 case PPC::LWA_32: Opc = PPC::LWAX_32; break;
542 case PPC::LD: Opc = PPC::LDX; break;
543 case PPC::LFS: Opc = PPC::LFSX; break;
544 case PPC::LFD: Opc = IsVSFRC ? PPC::LXSDX : PPC::LFDX; break;
546 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
547 .addReg(Addr.Base.Reg).addReg(IndexReg);
553 // Attempt to fast-select a load instruction.
554 bool PPCFastISel::SelectLoad(const Instruction *I) {
555 // FIXME: No atomic loads are supported.
556 if (cast<LoadInst>(I)->isAtomic())
559 // Verify we have a legal type before going any further.
561 if (!isLoadTypeLegal(I->getType(), VT))
564 // See if we can handle this address.
566 if (!PPCComputeAddress(I->getOperand(0), Addr))
569 // Look at the currently assigned register for this instruction
570 // to determine the required register class. This is necessary
571 // to constrain RA from using R0/X0 when this is not legal.
572 unsigned AssignedReg = FuncInfo.ValueMap[I];
573 const TargetRegisterClass *RC =
574 AssignedReg ? MRI.getRegClass(AssignedReg) : nullptr;
576 unsigned ResultReg = 0;
577 if (!PPCEmitLoad(VT, ResultReg, Addr, RC))
579 updateValueMap(I, ResultReg);
583 // Emit a store instruction to store SrcReg at Addr.
584 bool PPCFastISel::PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr) {
585 assert(SrcReg && "Nothing to store!");
587 bool UseOffset = true;
589 const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
590 bool Is32BitInt = RC->hasSuperClassEq(&PPC::GPRCRegClass);
592 switch (VT.SimpleTy) {
593 default: // e.g., vector types not handled
596 Opc = Is32BitInt ? PPC::STB : PPC::STB8;
599 Opc = Is32BitInt ? PPC::STH : PPC::STH8;
602 assert(Is32BitInt && "Not GPRC for i32??");
607 UseOffset = ((Addr.Offset & 3) == 0);
617 // If necessary, materialize the offset into a register and use
618 // the indexed form. Also handle stack pointers with special needs.
619 unsigned IndexReg = 0;
620 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
622 // If this is a potential VSX store with an offset of 0, a VSX indexed store
624 bool IsVSFRC = isVSFRCRegister(SrcReg);
625 if (IsVSFRC && (Opc == PPC::STFD) &&
626 (Addr.BaseType != Address::FrameIndexBase) && UseOffset &&
627 (Addr.Offset == 0)) {
631 // Note: If we still have a frame index here, we know the offset is
632 // in range, as otherwise PPCSimplifyAddress would have converted it
634 if (Addr.BaseType == Address::FrameIndexBase) {
635 // VSX only provides an indexed store.
636 if (IsVSFRC && Opc == PPC::STFD) return false;
638 MachineMemOperand *MMO =
639 FuncInfo.MF->getMachineMemOperand(
640 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
641 MachineMemOperand::MOStore, MFI.getObjectSize(Addr.Base.FI),
642 MFI.getObjectAlignment(Addr.Base.FI));
644 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
647 .addFrameIndex(Addr.Base.FI)
650 // Base reg with offset in range.
651 } else if (UseOffset) {
652 // VSX only provides an indexed store.
653 if (IsVSFRC && Opc == PPC::STFD) return false;
655 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
656 .addReg(SrcReg).addImm(Addr.Offset).addReg(Addr.Base.Reg);
660 // Get the RR opcode corresponding to the RI one. FIXME: It would be
661 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
662 // is hard to get at.
664 default: llvm_unreachable("Unexpected opcode!");
665 case PPC::STB: Opc = PPC::STBX; break;
666 case PPC::STH : Opc = PPC::STHX; break;
667 case PPC::STW : Opc = PPC::STWX; break;
668 case PPC::STB8: Opc = PPC::STBX8; break;
669 case PPC::STH8: Opc = PPC::STHX8; break;
670 case PPC::STW8: Opc = PPC::STWX8; break;
671 case PPC::STD: Opc = PPC::STDX; break;
672 case PPC::STFS: Opc = PPC::STFSX; break;
673 case PPC::STFD: Opc = IsVSFRC ? PPC::STXSDX : PPC::STFDX; break;
675 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
676 .addReg(SrcReg).addReg(Addr.Base.Reg).addReg(IndexReg);
682 // Attempt to fast-select a store instruction.
683 bool PPCFastISel::SelectStore(const Instruction *I) {
684 Value *Op0 = I->getOperand(0);
687 // FIXME: No atomics loads are supported.
688 if (cast<StoreInst>(I)->isAtomic())
691 // Verify we have a legal type before going any further.
693 if (!isLoadTypeLegal(Op0->getType(), VT))
696 // Get the value to be stored into a register.
697 SrcReg = getRegForValue(Op0);
701 // See if we can handle this address.
703 if (!PPCComputeAddress(I->getOperand(1), Addr))
706 if (!PPCEmitStore(VT, SrcReg, Addr))
712 // Attempt to fast-select a branch instruction.
713 bool PPCFastISel::SelectBranch(const Instruction *I) {
714 const BranchInst *BI = cast<BranchInst>(I);
715 MachineBasicBlock *BrBB = FuncInfo.MBB;
716 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
717 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
719 // For now, just try the simplest case where it's fed by a compare.
720 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
721 Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
725 PPC::Predicate PPCPred = OptPPCPred.getValue();
727 // Take advantage of fall-through opportunities.
728 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
730 PPCPred = PPC::InvertPredicate(PPCPred);
733 unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
735 if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
739 BuildMI(*BrBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::BCC))
740 .addImm(PPCPred).addReg(CondReg).addMBB(TBB);
741 fastEmitBranch(FBB, DbgLoc);
742 FuncInfo.MBB->addSuccessor(TBB);
745 } else if (const ConstantInt *CI =
746 dyn_cast<ConstantInt>(BI->getCondition())) {
747 uint64_t Imm = CI->getZExtValue();
748 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
749 fastEmitBranch(Target, DbgLoc);
753 // FIXME: ARM looks for a case where the block containing the compare
754 // has been split from the block containing the branch. If this happens,
755 // there is a vreg available containing the result of the compare. I'm
756 // not sure we can do much, as we've lost the predicate information with
757 // the compare instruction -- we have a 4-bit CR but don't know which bit
762 // Attempt to emit a compare of the two source values. Signed and unsigned
763 // comparisons are supported. Return false if we can't handle it.
764 bool PPCFastISel::PPCEmitCmp(const Value *SrcValue1, const Value *SrcValue2,
765 bool IsZExt, unsigned DestReg) {
766 Type *Ty = SrcValue1->getType();
767 EVT SrcEVT = TLI.getValueType(Ty, true);
768 if (!SrcEVT.isSimple())
770 MVT SrcVT = SrcEVT.getSimpleVT();
772 if (SrcVT == MVT::i1 && PPCSubTarget->useCRBits())
775 // See if operand 2 is an immediate encodeable in the compare.
776 // FIXME: Operands are not in canonical order at -O0, so an immediate
777 // operand in position 1 is a lost opportunity for now. We are
778 // similar to ARM in this regard.
782 // Only 16-bit integer constants can be represented in compares for
783 // PowerPC. Others will be materialized into a register.
784 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(SrcValue2)) {
785 if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
786 SrcVT == MVT::i8 || SrcVT == MVT::i1) {
787 const APInt &CIVal = ConstInt->getValue();
788 Imm = (IsZExt) ? (long)CIVal.getZExtValue() : (long)CIVal.getSExtValue();
789 if ((IsZExt && isUInt<16>(Imm)) || (!IsZExt && isInt<16>(Imm)))
795 bool NeedsExt = false;
796 switch (SrcVT.SimpleTy) {
797 default: return false;
799 CmpOpc = PPC::FCMPUS;
802 CmpOpc = PPC::FCMPUD;
808 // Intentional fall-through.
811 CmpOpc = IsZExt ? PPC::CMPLW : PPC::CMPW;
813 CmpOpc = IsZExt ? PPC::CMPLWI : PPC::CMPWI;
817 CmpOpc = IsZExt ? PPC::CMPLD : PPC::CMPD;
819 CmpOpc = IsZExt ? PPC::CMPLDI : PPC::CMPDI;
823 unsigned SrcReg1 = getRegForValue(SrcValue1);
827 unsigned SrcReg2 = 0;
829 SrcReg2 = getRegForValue(SrcValue2);
835 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
836 if (!PPCEmitIntExt(SrcVT, SrcReg1, MVT::i32, ExtReg, IsZExt))
841 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
842 if (!PPCEmitIntExt(SrcVT, SrcReg2, MVT::i32, ExtReg, IsZExt))
849 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc), DestReg)
850 .addReg(SrcReg1).addReg(SrcReg2);
852 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc), DestReg)
853 .addReg(SrcReg1).addImm(Imm);
858 // Attempt to fast-select a floating-point extend instruction.
859 bool PPCFastISel::SelectFPExt(const Instruction *I) {
860 Value *Src = I->getOperand(0);
861 EVT SrcVT = TLI.getValueType(Src->getType(), true);
862 EVT DestVT = TLI.getValueType(I->getType(), true);
864 if (SrcVT != MVT::f32 || DestVT != MVT::f64)
867 unsigned SrcReg = getRegForValue(Src);
871 // No code is generated for a FP extend.
872 updateValueMap(I, SrcReg);
876 // Attempt to fast-select a floating-point truncate instruction.
877 bool PPCFastISel::SelectFPTrunc(const Instruction *I) {
878 Value *Src = I->getOperand(0);
879 EVT SrcVT = TLI.getValueType(Src->getType(), true);
880 EVT DestVT = TLI.getValueType(I->getType(), true);
882 if (SrcVT != MVT::f64 || DestVT != MVT::f32)
885 unsigned SrcReg = getRegForValue(Src);
889 // Round the result to single precision.
890 unsigned DestReg = createResultReg(&PPC::F4RCRegClass);
891 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::FRSP), DestReg)
894 updateValueMap(I, DestReg);
898 // Move an i32 or i64 value in a GPR to an f64 value in an FPR.
899 // FIXME: When direct register moves are implemented (see PowerISA 2.07),
900 // those should be used instead of moving via a stack slot when the
901 // subtarget permits.
902 // FIXME: The code here is sloppy for the 4-byte case. Can use a 4-byte
903 // stack slot and 4-byte store/load sequence. Or just sext the 4-byte
904 // case to 8 bytes which produces tighter code but wastes stack space.
905 unsigned PPCFastISel::PPCMoveToFPReg(MVT SrcVT, unsigned SrcReg,
908 // If necessary, extend 32-bit int to 64-bit.
909 if (SrcVT == MVT::i32) {
910 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
911 if (!PPCEmitIntExt(MVT::i32, SrcReg, MVT::i64, TmpReg, !IsSigned))
916 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
918 Addr.BaseType = Address::FrameIndexBase;
919 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
921 // Store the value from the GPR.
922 if (!PPCEmitStore(MVT::i64, SrcReg, Addr))
925 // Load the integer value into an FPR. The kind of load used depends
926 // on a number of conditions.
927 unsigned LoadOpc = PPC::LFD;
929 if (SrcVT == MVT::i32) {
931 LoadOpc = PPC::LFIWZX;
932 Addr.Offset = (PPCSubTarget->isLittleEndian()) ? 0 : 4;
933 } else if (PPCSubTarget->hasLFIWAX()) {
934 LoadOpc = PPC::LFIWAX;
935 Addr.Offset = (PPCSubTarget->isLittleEndian()) ? 0 : 4;
939 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
940 unsigned ResultReg = 0;
941 if (!PPCEmitLoad(MVT::f64, ResultReg, Addr, RC, !IsSigned, LoadOpc))
947 // Attempt to fast-select an integer-to-floating-point conversion.
948 bool PPCFastISel::SelectIToFP(const Instruction *I, bool IsSigned) {
950 Type *DstTy = I->getType();
951 if (!isTypeLegal(DstTy, DstVT))
954 if (DstVT != MVT::f32 && DstVT != MVT::f64)
957 Value *Src = I->getOperand(0);
958 EVT SrcEVT = TLI.getValueType(Src->getType(), true);
959 if (!SrcEVT.isSimple())
962 MVT SrcVT = SrcEVT.getSimpleVT();
964 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 &&
965 SrcVT != MVT::i32 && SrcVT != MVT::i64)
968 unsigned SrcReg = getRegForValue(Src);
972 // We can only lower an unsigned convert if we have the newer
973 // floating-point conversion operations.
974 if (!IsSigned && !PPCSubTarget->hasFPCVT())
977 // FIXME: For now we require the newer floating-point conversion operations
978 // (which are present only on P7 and A2 server models) when converting
979 // to single-precision float. Otherwise we have to generate a lot of
980 // fiddly code to avoid double rounding. If necessary, the fiddly code
981 // can be found in PPCTargetLowering::LowerINT_TO_FP().
982 if (DstVT == MVT::f32 && !PPCSubTarget->hasFPCVT())
985 // Extend the input if necessary.
986 if (SrcVT == MVT::i8 || SrcVT == MVT::i16) {
987 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
988 if (!PPCEmitIntExt(SrcVT, SrcReg, MVT::i64, TmpReg, !IsSigned))
994 // Move the integer value to an FPR.
995 unsigned FPReg = PPCMoveToFPReg(SrcVT, SrcReg, IsSigned);
999 // Determine the opcode for the conversion.
1000 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
1001 unsigned DestReg = createResultReg(RC);
1004 if (DstVT == MVT::f32)
1005 Opc = IsSigned ? PPC::FCFIDS : PPC::FCFIDUS;
1007 Opc = IsSigned ? PPC::FCFID : PPC::FCFIDU;
1009 // Generate the convert.
1010 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1013 updateValueMap(I, DestReg);
1017 // Move the floating-point value in SrcReg into an integer destination
1018 // register, and return the register (or zero if we can't handle it).
1019 // FIXME: When direct register moves are implemented (see PowerISA 2.07),
1020 // those should be used instead of moving via a stack slot when the
1021 // subtarget permits.
1022 unsigned PPCFastISel::PPCMoveToIntReg(const Instruction *I, MVT VT,
1023 unsigned SrcReg, bool IsSigned) {
1024 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
1025 // Note that if have STFIWX available, we could use a 4-byte stack
1026 // slot for i32, but this being fast-isel we'll just go with the
1027 // easiest code gen possible.
1029 Addr.BaseType = Address::FrameIndexBase;
1030 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
1032 // Store the value from the FPR.
1033 if (!PPCEmitStore(MVT::f64, SrcReg, Addr))
1036 // Reload it into a GPR. If we want an i32, modify the address
1037 // to have a 4-byte offset so we load from the right place.
1041 // Look at the currently assigned register for this instruction
1042 // to determine the required register class.
1043 unsigned AssignedReg = FuncInfo.ValueMap[I];
1044 const TargetRegisterClass *RC =
1045 AssignedReg ? MRI.getRegClass(AssignedReg) : nullptr;
1047 unsigned ResultReg = 0;
1048 if (!PPCEmitLoad(VT, ResultReg, Addr, RC, !IsSigned))
1054 // Attempt to fast-select a floating-point-to-integer conversion.
1055 bool PPCFastISel::SelectFPToI(const Instruction *I, bool IsSigned) {
1057 Type *DstTy = I->getType();
1058 if (!isTypeLegal(DstTy, DstVT))
1061 if (DstVT != MVT::i32 && DstVT != MVT::i64)
1064 // If we don't have FCTIDUZ and we need it, punt to SelectionDAG.
1065 if (DstVT == MVT::i64 && !IsSigned && !PPCSubTarget->hasFPCVT())
1068 Value *Src = I->getOperand(0);
1069 Type *SrcTy = Src->getType();
1070 if (!isTypeLegal(SrcTy, SrcVT))
1073 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
1076 unsigned SrcReg = getRegForValue(Src);
1080 // Convert f32 to f64 if necessary. This is just a meaningless copy
1081 // to get the register class right. COPY_TO_REGCLASS is needed since
1082 // a COPY from F4RC to F8RC is converted to a F4RC-F4RC copy downstream.
1083 const TargetRegisterClass *InRC = MRI.getRegClass(SrcReg);
1084 if (InRC == &PPC::F4RCRegClass) {
1085 unsigned TmpReg = createResultReg(&PPC::F8RCRegClass);
1086 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1087 TII.get(TargetOpcode::COPY_TO_REGCLASS), TmpReg)
1088 .addReg(SrcReg).addImm(PPC::F8RCRegClassID);
1092 // Determine the opcode for the conversion, which takes place
1093 // entirely within FPRs.
1094 unsigned DestReg = createResultReg(&PPC::F8RCRegClass);
1097 if (DstVT == MVT::i32)
1101 Opc = PPCSubTarget->hasFPCVT() ? PPC::FCTIWUZ : PPC::FCTIDZ;
1103 Opc = IsSigned ? PPC::FCTIDZ : PPC::FCTIDUZ;
1105 // Generate the convert.
1106 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1109 // Now move the integer value from a float register to an integer register.
1110 unsigned IntReg = PPCMoveToIntReg(I, DstVT, DestReg, IsSigned);
1114 updateValueMap(I, IntReg);
1118 // Attempt to fast-select a binary integer operation that isn't already
1119 // handled automatically.
1120 bool PPCFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1121 EVT DestVT = TLI.getValueType(I->getType(), true);
1123 // We can get here in the case when we have a binary operation on a non-legal
1124 // type and the target independent selector doesn't know how to handle it.
1125 if (DestVT != MVT::i16 && DestVT != MVT::i8)
1128 // Look at the currently assigned register for this instruction
1129 // to determine the required register class. If there is no register,
1130 // make a conservative choice (don't assign R0).
1131 unsigned AssignedReg = FuncInfo.ValueMap[I];
1132 const TargetRegisterClass *RC =
1133 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1134 &PPC::GPRC_and_GPRC_NOR0RegClass);
1135 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1138 switch (ISDOpcode) {
1139 default: return false;
1141 Opc = IsGPRC ? PPC::ADD4 : PPC::ADD8;
1144 Opc = IsGPRC ? PPC::OR : PPC::OR8;
1147 Opc = IsGPRC ? PPC::SUBF : PPC::SUBF8;
1151 unsigned ResultReg = createResultReg(RC ? RC : &PPC::G8RCRegClass);
1152 unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1153 if (SrcReg1 == 0) return false;
1155 // Handle case of small immediate operand.
1156 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(1))) {
1157 const APInt &CIVal = ConstInt->getValue();
1158 int Imm = (int)CIVal.getSExtValue();
1160 if (isInt<16>(Imm)) {
1163 llvm_unreachable("Missing case!");
1166 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1170 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1183 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1192 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1199 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
1203 updateValueMap(I, ResultReg);
1210 unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1211 if (SrcReg2 == 0) return false;
1213 // Reverse operands for subtract-from.
1214 if (ISDOpcode == ISD::SUB)
1215 std::swap(SrcReg1, SrcReg2);
1217 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1218 .addReg(SrcReg1).addReg(SrcReg2);
1219 updateValueMap(I, ResultReg);
1223 // Handle arguments to a call that we're attempting to fast-select.
1224 // Return false if the arguments are too complex for us at the moment.
1225 bool PPCFastISel::processCallArgs(SmallVectorImpl<Value*> &Args,
1226 SmallVectorImpl<unsigned> &ArgRegs,
1227 SmallVectorImpl<MVT> &ArgVTs,
1228 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1229 SmallVectorImpl<unsigned> &RegArgs,
1233 SmallVector<CCValAssign, 16> ArgLocs;
1234 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, *Context);
1236 // Reserve space for the linkage area on the stack.
1237 bool isELFv2ABI = PPCSubTarget->isELFv2ABI();
1238 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
1240 CCInfo.AllocateStack(LinkageSize, 8);
1242 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_PPC64_ELF_FIS);
1244 // Bail out if we can't handle any of the arguments.
1245 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1246 CCValAssign &VA = ArgLocs[I];
1247 MVT ArgVT = ArgVTs[VA.getValNo()];
1249 // Skip vector arguments for now, as well as long double and
1250 // uint128_t, and anything that isn't passed in a register.
1251 if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64 || ArgVT == MVT::i1 ||
1252 !VA.isRegLoc() || VA.needsCustom())
1255 // Skip bit-converted arguments for now.
1256 if (VA.getLocInfo() == CCValAssign::BCvt)
1260 // Get a count of how many bytes are to be pushed onto the stack.
1261 NumBytes = CCInfo.getNextStackOffset();
1263 // The prolog code of the callee may store up to 8 GPR argument registers to
1264 // the stack, allowing va_start to index over them in memory if its varargs.
1265 // Because we cannot tell if this is needed on the caller side, we have to
1266 // conservatively assume that it is needed. As such, make sure we have at
1267 // least enough stack space for the caller to store the 8 GPRs.
1268 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
1269 NumBytes = std::max(NumBytes, LinkageSize + 64);
1271 // Issue CALLSEQ_START.
1272 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1273 TII.get(TII.getCallFrameSetupOpcode()))
1276 // Prepare to assign register arguments. Every argument uses up a
1277 // GPR protocol register even if it's passed in a floating-point
1279 unsigned NextGPR = PPC::X3;
1280 unsigned NextFPR = PPC::F1;
1282 // Process arguments.
1283 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1284 CCValAssign &VA = ArgLocs[I];
1285 unsigned Arg = ArgRegs[VA.getValNo()];
1286 MVT ArgVT = ArgVTs[VA.getValNo()];
1288 // Handle argument promotion and bitcasts.
1289 switch (VA.getLocInfo()) {
1291 llvm_unreachable("Unknown loc info!");
1292 case CCValAssign::Full:
1294 case CCValAssign::SExt: {
1295 MVT DestVT = VA.getLocVT();
1296 const TargetRegisterClass *RC =
1297 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1298 unsigned TmpReg = createResultReg(RC);
1299 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/false))
1300 llvm_unreachable("Failed to emit a sext!");
1305 case CCValAssign::AExt:
1306 case CCValAssign::ZExt: {
1307 MVT DestVT = VA.getLocVT();
1308 const TargetRegisterClass *RC =
1309 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1310 unsigned TmpReg = createResultReg(RC);
1311 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/true))
1312 llvm_unreachable("Failed to emit a zext!");
1317 case CCValAssign::BCvt: {
1318 // FIXME: Not yet handled.
1319 llvm_unreachable("Should have bailed before getting here!");
1324 // Copy this argument to the appropriate register.
1326 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) {
1332 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1333 TII.get(TargetOpcode::COPY), ArgReg).addReg(Arg);
1334 RegArgs.push_back(ArgReg);
1340 // For a call that we've determined we can fast-select, finish the
1341 // call sequence and generate a copy to obtain the return value (if any).
1342 void PPCFastISel::finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1343 const Instruction *I, CallingConv::ID CC,
1344 unsigned &NumBytes, bool IsVarArg) {
1345 // Issue CallSEQ_END.
1346 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1347 TII.get(TII.getCallFrameDestroyOpcode()))
1348 .addImm(NumBytes).addImm(0);
1350 // Next, generate a copy to obtain the return value.
1351 // FIXME: No multi-register return values yet, though I don't foresee
1352 // any real difficulties there.
1353 if (RetVT != MVT::isVoid) {
1354 SmallVector<CCValAssign, 16> RVLocs;
1355 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs, *Context);
1356 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1357 CCValAssign &VA = RVLocs[0];
1358 assert(RVLocs.size() == 1 && "No support for multi-reg return values!");
1359 assert(VA.isRegLoc() && "Can only return in registers!");
1361 MVT DestVT = VA.getValVT();
1362 MVT CopyVT = DestVT;
1364 // Ints smaller than a register still arrive in a full 64-bit
1365 // register, so make sure we recognize this.
1366 if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32)
1369 unsigned SourcePhysReg = VA.getLocReg();
1370 unsigned ResultReg = 0;
1372 if (RetVT == CopyVT) {
1373 const TargetRegisterClass *CpyRC = TLI.getRegClassFor(CopyVT);
1374 ResultReg = createResultReg(CpyRC);
1376 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1377 TII.get(TargetOpcode::COPY), ResultReg)
1378 .addReg(SourcePhysReg);
1380 // If necessary, round the floating result to single precision.
1381 } else if (CopyVT == MVT::f64) {
1382 ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1383 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::FRSP),
1384 ResultReg).addReg(SourcePhysReg);
1386 // If only the low half of a general register is needed, generate
1387 // a GPRC copy instead of a G8RC copy. (EXTRACT_SUBREG can't be
1388 // used along the fast-isel path (not lowered), and downstream logic
1389 // also doesn't like a direct subreg copy on a physical reg.)
1390 } else if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32) {
1391 ResultReg = createResultReg(&PPC::GPRCRegClass);
1392 // Convert physical register from G8RC to GPRC.
1393 SourcePhysReg -= PPC::X0 - PPC::R0;
1394 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1395 TII.get(TargetOpcode::COPY), ResultReg)
1396 .addReg(SourcePhysReg);
1399 assert(ResultReg && "ResultReg unset!");
1400 UsedRegs.push_back(SourcePhysReg);
1401 updateValueMap(I, ResultReg);
1405 // Attempt to fast-select a call instruction.
1406 bool PPCFastISel::SelectCall(const Instruction *I) {
1407 const CallInst *CI = cast<CallInst>(I);
1408 const Value *Callee = CI->getCalledValue();
1410 // Can't handle inline asm.
1411 if (isa<InlineAsm>(Callee))
1414 // Allow SelectionDAG isel to handle tail calls.
1415 if (CI->isTailCall())
1418 // Obtain calling convention.
1419 ImmutableCallSite CS(CI);
1420 CallingConv::ID CC = CS.getCallingConv();
1422 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1423 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1424 bool IsVarArg = FTy->isVarArg();
1426 // Not ready for varargs yet.
1430 // Handle simple calls for now, with legal return types and
1431 // those that can be extended.
1432 Type *RetTy = I->getType();
1434 if (RetTy->isVoidTy())
1435 RetVT = MVT::isVoid;
1436 else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
1440 // FIXME: No multi-register return values yet.
1441 if (RetVT != MVT::isVoid && RetVT != MVT::i8 && RetVT != MVT::i16 &&
1442 RetVT != MVT::i32 && RetVT != MVT::i64 && RetVT != MVT::f32 &&
1443 RetVT != MVT::f64) {
1444 SmallVector<CCValAssign, 16> RVLocs;
1445 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs, *Context);
1446 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1447 if (RVLocs.size() > 1)
1451 // Bail early if more than 8 arguments, as we only currently
1452 // handle arguments passed in registers.
1453 unsigned NumArgs = CS.arg_size();
1457 // Set up the argument vectors.
1458 SmallVector<Value*, 8> Args;
1459 SmallVector<unsigned, 8> ArgRegs;
1460 SmallVector<MVT, 8> ArgVTs;
1461 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1463 Args.reserve(NumArgs);
1464 ArgRegs.reserve(NumArgs);
1465 ArgVTs.reserve(NumArgs);
1466 ArgFlags.reserve(NumArgs);
1468 for (ImmutableCallSite::arg_iterator II = CS.arg_begin(), IE = CS.arg_end();
1470 // FIXME: ARM does something for intrinsic calls here, check into that.
1472 unsigned AttrIdx = II - CS.arg_begin() + 1;
1474 // Only handle easy calls for now. It would be reasonably easy
1475 // to handle <= 8-byte structures passed ByVal in registers, but we
1476 // have to ensure they are right-justified in the register.
1477 if (CS.paramHasAttr(AttrIdx, Attribute::InReg) ||
1478 CS.paramHasAttr(AttrIdx, Attribute::StructRet) ||
1479 CS.paramHasAttr(AttrIdx, Attribute::Nest) ||
1480 CS.paramHasAttr(AttrIdx, Attribute::ByVal))
1483 ISD::ArgFlagsTy Flags;
1484 if (CS.paramHasAttr(AttrIdx, Attribute::SExt))
1486 if (CS.paramHasAttr(AttrIdx, Attribute::ZExt))
1489 Type *ArgTy = (*II)->getType();
1491 if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8)
1494 if (ArgVT.isVector())
1497 unsigned Arg = getRegForValue(*II);
1501 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
1502 Flags.setOrigAlign(OriginalAlignment);
1504 Args.push_back(*II);
1505 ArgRegs.push_back(Arg);
1506 ArgVTs.push_back(ArgVT);
1507 ArgFlags.push_back(Flags);
1510 // Process the arguments.
1511 SmallVector<unsigned, 8> RegArgs;
1514 if (!processCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
1515 RegArgs, CC, NumBytes, IsVarArg))
1518 // FIXME: No handling for function pointers yet. This requires
1519 // implementing the function descriptor (OPD) setup.
1520 const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1524 // Build direct call with NOP for TOC restore.
1525 // FIXME: We can and should optimize away the NOP for local calls.
1526 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1527 TII.get(PPC::BL8_NOP));
1529 MIB.addGlobalAddress(GV);
1531 // Add implicit physical register uses to the call.
1532 for (unsigned II = 0, IE = RegArgs.size(); II != IE; ++II)
1533 MIB.addReg(RegArgs[II], RegState::Implicit);
1535 // Direct calls in the ELFv2 ABI need the TOC register live into the call.
1536 if (PPCSubTarget->isELFv2ABI())
1537 MIB.addReg(PPC::X2, RegState::Implicit);
1539 // Add a register mask with the call-preserved registers. Proper
1540 // defs for return values will be added by setPhysRegsDeadExcept().
1541 MIB.addRegMask(TRI.getCallPreservedMask(CC));
1543 // Finish off the call including any return values.
1544 SmallVector<unsigned, 4> UsedRegs;
1545 finishCall(RetVT, UsedRegs, I, CC, NumBytes, IsVarArg);
1547 // Set all unused physregs defs as dead.
1548 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1553 // Attempt to fast-select a return instruction.
1554 bool PPCFastISel::SelectRet(const Instruction *I) {
1556 if (!FuncInfo.CanLowerReturn)
1559 const ReturnInst *Ret = cast<ReturnInst>(I);
1560 const Function &F = *I->getParent()->getParent();
1562 // Build a list of return value registers.
1563 SmallVector<unsigned, 4> RetRegs;
1564 CallingConv::ID CC = F.getCallingConv();
1566 if (Ret->getNumOperands() > 0) {
1567 SmallVector<ISD::OutputArg, 4> Outs;
1568 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1570 // Analyze operands of the call, assigning locations to each operand.
1571 SmallVector<CCValAssign, 16> ValLocs;
1572 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, *Context);
1573 CCInfo.AnalyzeReturn(Outs, RetCC_PPC64_ELF_FIS);
1574 const Value *RV = Ret->getOperand(0);
1576 // FIXME: Only one output register for now.
1577 if (ValLocs.size() > 1)
1580 // Special case for returning a constant integer of any size.
1581 // Materialize the constant as an i64 and copy it to the return
1582 // register. We still need to worry about properly extending the sign. E.g:
1583 // If the constant has only one bit, it means it is a boolean. Therefore
1584 // we can't use PPCMaterializeInt because it extends the sign which will
1585 // cause negations of the returned value to be incorrect as they are
1586 // implemented as the flip of the least significant bit.
1587 if (isa<ConstantInt>(*RV)) {
1588 const Constant *C = cast<Constant>(RV);
1590 CCValAssign &VA = ValLocs[0];
1592 unsigned RetReg = VA.getLocReg();
1593 unsigned SrcReg = PPCMaterializeInt(C, MVT::i64,
1594 VA.getLocInfo() == CCValAssign::SExt);
1596 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1597 TII.get(TargetOpcode::COPY), RetReg).addReg(SrcReg);
1599 RetRegs.push_back(RetReg);
1602 unsigned Reg = getRegForValue(RV);
1607 // Copy the result values into the output registers.
1608 for (unsigned i = 0; i < ValLocs.size(); ++i) {
1610 CCValAssign &VA = ValLocs[i];
1611 assert(VA.isRegLoc() && "Can only return in registers!");
1612 RetRegs.push_back(VA.getLocReg());
1613 unsigned SrcReg = Reg + VA.getValNo();
1615 EVT RVEVT = TLI.getValueType(RV->getType());
1616 if (!RVEVT.isSimple())
1618 MVT RVVT = RVEVT.getSimpleVT();
1619 MVT DestVT = VA.getLocVT();
1621 if (RVVT != DestVT && RVVT != MVT::i8 &&
1622 RVVT != MVT::i16 && RVVT != MVT::i32)
1625 if (RVVT != DestVT) {
1626 switch (VA.getLocInfo()) {
1628 llvm_unreachable("Unknown loc info!");
1629 case CCValAssign::Full:
1630 llvm_unreachable("Full value assign but types don't match?");
1631 case CCValAssign::AExt:
1632 case CCValAssign::ZExt: {
1633 const TargetRegisterClass *RC =
1634 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1635 unsigned TmpReg = createResultReg(RC);
1636 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, true))
1641 case CCValAssign::SExt: {
1642 const TargetRegisterClass *RC =
1643 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1644 unsigned TmpReg = createResultReg(RC);
1645 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, false))
1653 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1654 TII.get(TargetOpcode::COPY), RetRegs[i])
1660 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1663 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1664 MIB.addReg(RetRegs[i], RegState::Implicit);
1669 // Attempt to emit an integer extend of SrcReg into DestReg. Both
1670 // signed and zero extensions are supported. Return false if we
1672 bool PPCFastISel::PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1673 unsigned DestReg, bool IsZExt) {
1674 if (DestVT != MVT::i32 && DestVT != MVT::i64)
1676 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 && SrcVT != MVT::i32)
1679 // Signed extensions use EXTSB, EXTSH, EXTSW.
1682 if (SrcVT == MVT::i8)
1683 Opc = (DestVT == MVT::i32) ? PPC::EXTSB : PPC::EXTSB8_32_64;
1684 else if (SrcVT == MVT::i16)
1685 Opc = (DestVT == MVT::i32) ? PPC::EXTSH : PPC::EXTSH8_32_64;
1687 assert(DestVT == MVT::i64 && "Signed extend from i32 to i32??");
1688 Opc = PPC::EXTSW_32_64;
1690 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1693 // Unsigned 32-bit extensions use RLWINM.
1694 } else if (DestVT == MVT::i32) {
1696 if (SrcVT == MVT::i8)
1699 assert(SrcVT == MVT::i16 && "Unsigned extend from i32 to i32??");
1702 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::RLWINM),
1704 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB).addImm(/*ME=*/31);
1706 // Unsigned 64-bit extensions use RLDICL (with a 32-bit source).
1709 if (SrcVT == MVT::i8)
1711 else if (SrcVT == MVT::i16)
1715 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1716 TII.get(PPC::RLDICL_32_64), DestReg)
1717 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB);
1723 // Attempt to fast-select an indirect branch instruction.
1724 bool PPCFastISel::SelectIndirectBr(const Instruction *I) {
1725 unsigned AddrReg = getRegForValue(I->getOperand(0));
1729 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::MTCTR8))
1731 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::BCTR8));
1733 const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1734 for (unsigned i = 0, e = IB->getNumSuccessors(); i != e; ++i)
1735 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[IB->getSuccessor(i)]);
1740 // Attempt to fast-select an integer truncate instruction.
1741 bool PPCFastISel::SelectTrunc(const Instruction *I) {
1742 Value *Src = I->getOperand(0);
1743 EVT SrcVT = TLI.getValueType(Src->getType(), true);
1744 EVT DestVT = TLI.getValueType(I->getType(), true);
1746 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16)
1749 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8)
1752 unsigned SrcReg = getRegForValue(Src);
1756 // The only interesting case is when we need to switch register classes.
1757 if (SrcVT == MVT::i64) {
1758 unsigned ResultReg = createResultReg(&PPC::GPRCRegClass);
1759 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1760 TII.get(TargetOpcode::COPY),
1761 ResultReg).addReg(SrcReg, 0, PPC::sub_32);
1765 updateValueMap(I, SrcReg);
1769 // Attempt to fast-select an integer extend instruction.
1770 bool PPCFastISel::SelectIntExt(const Instruction *I) {
1771 Type *DestTy = I->getType();
1772 Value *Src = I->getOperand(0);
1773 Type *SrcTy = Src->getType();
1775 bool IsZExt = isa<ZExtInst>(I);
1776 unsigned SrcReg = getRegForValue(Src);
1777 if (!SrcReg) return false;
1779 EVT SrcEVT, DestEVT;
1780 SrcEVT = TLI.getValueType(SrcTy, true);
1781 DestEVT = TLI.getValueType(DestTy, true);
1782 if (!SrcEVT.isSimple())
1784 if (!DestEVT.isSimple())
1787 MVT SrcVT = SrcEVT.getSimpleVT();
1788 MVT DestVT = DestEVT.getSimpleVT();
1790 // If we know the register class needed for the result of this
1791 // instruction, use it. Otherwise pick the register class of the
1792 // correct size that does not contain X0/R0, since we don't know
1793 // whether downstream uses permit that assignment.
1794 unsigned AssignedReg = FuncInfo.ValueMap[I];
1795 const TargetRegisterClass *RC =
1796 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1797 (DestVT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
1798 &PPC::GPRC_and_GPRC_NOR0RegClass));
1799 unsigned ResultReg = createResultReg(RC);
1801 if (!PPCEmitIntExt(SrcVT, SrcReg, DestVT, ResultReg, IsZExt))
1804 updateValueMap(I, ResultReg);
1808 // Attempt to fast-select an instruction that wasn't handled by
1809 // the table-generated machinery.
1810 bool PPCFastISel::fastSelectInstruction(const Instruction *I) {
1812 switch (I->getOpcode()) {
1813 case Instruction::Load:
1814 return SelectLoad(I);
1815 case Instruction::Store:
1816 return SelectStore(I);
1817 case Instruction::Br:
1818 return SelectBranch(I);
1819 case Instruction::IndirectBr:
1820 return SelectIndirectBr(I);
1821 case Instruction::FPExt:
1822 return SelectFPExt(I);
1823 case Instruction::FPTrunc:
1824 return SelectFPTrunc(I);
1825 case Instruction::SIToFP:
1826 return SelectIToFP(I, /*IsSigned*/ true);
1827 case Instruction::UIToFP:
1828 return SelectIToFP(I, /*IsSigned*/ false);
1829 case Instruction::FPToSI:
1830 return SelectFPToI(I, /*IsSigned*/ true);
1831 case Instruction::FPToUI:
1832 return SelectFPToI(I, /*IsSigned*/ false);
1833 case Instruction::Add:
1834 return SelectBinaryIntOp(I, ISD::ADD);
1835 case Instruction::Or:
1836 return SelectBinaryIntOp(I, ISD::OR);
1837 case Instruction::Sub:
1838 return SelectBinaryIntOp(I, ISD::SUB);
1839 case Instruction::Call:
1840 if (dyn_cast<IntrinsicInst>(I))
1842 return SelectCall(I);
1843 case Instruction::Ret:
1844 return SelectRet(I);
1845 case Instruction::Trunc:
1846 return SelectTrunc(I);
1847 case Instruction::ZExt:
1848 case Instruction::SExt:
1849 return SelectIntExt(I);
1850 // Here add other flavors of Instruction::XXX that automated
1851 // cases don't catch. For example, switches are terminators
1852 // that aren't yet handled.
1859 // Materialize a floating-point constant into a register, and return
1860 // the register number (or zero if we failed to handle it).
1861 unsigned PPCFastISel::PPCMaterializeFP(const ConstantFP *CFP, MVT VT) {
1862 // No plans to handle long double here.
1863 if (VT != MVT::f32 && VT != MVT::f64)
1866 // All FP constants are loaded from the constant pool.
1867 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
1868 assert(Align > 0 && "Unexpectedly missing alignment information!");
1869 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
1870 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
1871 CodeModel::Model CModel = TM.getCodeModel();
1873 MachineMemOperand *MMO =
1874 FuncInfo.MF->getMachineMemOperand(
1875 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
1876 (VT == MVT::f32) ? 4 : 8, Align);
1878 unsigned Opc = (VT == MVT::f32) ? PPC::LFS : PPC::LFD;
1879 unsigned TmpReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1881 // For small code model, generate a LF[SD](0, LDtocCPT(Idx, X2)).
1882 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault) {
1883 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocCPT),
1885 .addConstantPoolIndex(Idx).addReg(PPC::X2);
1886 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1887 .addImm(0).addReg(TmpReg).addMemOperand(MMO);
1889 // Otherwise we generate LF[SD](Idx[lo], ADDIStocHA(X2, Idx)).
1890 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDIStocHA),
1891 TmpReg).addReg(PPC::X2).addConstantPoolIndex(Idx);
1892 // But for large code model, we must generate a LDtocL followed
1894 if (CModel == CodeModel::Large) {
1895 unsigned TmpReg2 = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1896 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocL),
1897 TmpReg2).addConstantPoolIndex(Idx).addReg(TmpReg);
1898 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1899 .addImm(0).addReg(TmpReg2);
1901 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1902 .addConstantPoolIndex(Idx, 0, PPCII::MO_TOC_LO)
1904 .addMemOperand(MMO);
1910 // Materialize the address of a global value into a register, and return
1911 // the register number (or zero if we failed to handle it).
1912 unsigned PPCFastISel::PPCMaterializeGV(const GlobalValue *GV, MVT VT) {
1913 assert(VT == MVT::i64 && "Non-address!");
1914 const TargetRegisterClass *RC = &PPC::G8RC_and_G8RC_NOX0RegClass;
1915 unsigned DestReg = createResultReg(RC);
1917 // Global values may be plain old object addresses, TLS object
1918 // addresses, constant pool entries, or jump tables. How we generate
1919 // code for these may depend on small, medium, or large code model.
1920 CodeModel::Model CModel = TM.getCodeModel();
1922 // FIXME: Jump tables are not yet required because fast-isel doesn't
1923 // handle switches; if that changes, we need them as well. For now,
1924 // what follows assumes everything's a generic (or TLS) global address.
1926 // FIXME: We don't yet handle the complexity of TLS.
1927 if (GV->isThreadLocal())
1930 // For small code model, generate a simple TOC load.
1931 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault)
1932 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtoc),
1934 .addGlobalAddress(GV)
1937 // If the address is an externally defined symbol, a symbol with common
1938 // or externally available linkage, a non-local function address, or a
1939 // jump table address (not yet needed), or if we are generating code
1940 // for large code model, we generate:
1941 // LDtocL(GV, ADDIStocHA(%X2, GV))
1942 // Otherwise we generate:
1943 // ADDItocL(ADDIStocHA(%X2, GV), GV)
1944 // Either way, start with the ADDIStocHA:
1945 unsigned HighPartReg = createResultReg(RC);
1946 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDIStocHA),
1947 HighPartReg).addReg(PPC::X2).addGlobalAddress(GV);
1949 // If/when switches are implemented, jump tables should be handled
1950 // on the "if" path here.
1951 if (CModel == CodeModel::Large ||
1952 (GV->getType()->getElementType()->isFunctionTy() &&
1953 (GV->isDeclaration() || GV->isWeakForLinker())) ||
1954 GV->isDeclaration() || GV->hasCommonLinkage() ||
1955 GV->hasAvailableExternallyLinkage())
1956 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocL),
1957 DestReg).addGlobalAddress(GV).addReg(HighPartReg);
1959 // Otherwise generate the ADDItocL.
1960 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDItocL),
1961 DestReg).addReg(HighPartReg).addGlobalAddress(GV);
1967 // Materialize a 32-bit integer constant into a register, and return
1968 // the register number (or zero if we failed to handle it).
1969 unsigned PPCFastISel::PPCMaterialize32BitInt(int64_t Imm,
1970 const TargetRegisterClass *RC) {
1971 unsigned Lo = Imm & 0xFFFF;
1972 unsigned Hi = (Imm >> 16) & 0xFFFF;
1974 unsigned ResultReg = createResultReg(RC);
1975 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1978 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1979 TII.get(IsGPRC ? PPC::LI : PPC::LI8), ResultReg)
1982 // Both Lo and Hi have nonzero bits.
1983 unsigned TmpReg = createResultReg(RC);
1984 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1985 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), TmpReg)
1987 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1988 TII.get(IsGPRC ? PPC::ORI : PPC::ORI8), ResultReg)
1989 .addReg(TmpReg).addImm(Lo);
1992 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1993 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), ResultReg)
1999 // Materialize a 64-bit integer constant into a register, and return
2000 // the register number (or zero if we failed to handle it).
2001 unsigned PPCFastISel::PPCMaterialize64BitInt(int64_t Imm,
2002 const TargetRegisterClass *RC) {
2003 unsigned Remainder = 0;
2006 // If the value doesn't fit in 32 bits, see if we can shift it
2007 // so that it fits in 32 bits.
2008 if (!isInt<32>(Imm)) {
2009 Shift = countTrailingZeros<uint64_t>(Imm);
2010 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
2012 if (isInt<32>(ImmSh))
2021 // Handle the high-order 32 bits (if shifted) or the whole 32 bits
2022 // (if not shifted).
2023 unsigned TmpReg1 = PPCMaterialize32BitInt(Imm, RC);
2027 // If upper 32 bits were not zero, we've built them and need to shift
2031 TmpReg2 = createResultReg(RC);
2032 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::RLDICR),
2033 TmpReg2).addReg(TmpReg1).addImm(Shift).addImm(63 - Shift);
2037 unsigned TmpReg3, Hi, Lo;
2038 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
2039 TmpReg3 = createResultReg(RC);
2040 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ORIS8),
2041 TmpReg3).addReg(TmpReg2).addImm(Hi);
2045 if ((Lo = Remainder & 0xFFFF)) {
2046 unsigned ResultReg = createResultReg(RC);
2047 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ORI8),
2048 ResultReg).addReg(TmpReg3).addImm(Lo);
2056 // Materialize an integer constant into a register, and return
2057 // the register number (or zero if we failed to handle it).
2058 unsigned PPCFastISel::PPCMaterializeInt(const Constant *C, MVT VT,
2060 // If we're using CR bit registers for i1 values, handle that as a special
2062 if (VT == MVT::i1 && PPCSubTarget->useCRBits()) {
2063 const ConstantInt *CI = cast<ConstantInt>(C);
2064 unsigned ImmReg = createResultReg(&PPC::CRBITRCRegClass);
2065 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2066 TII.get(CI->isZero() ? PPC::CRUNSET : PPC::CRSET), ImmReg);
2070 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2071 VT != MVT::i8 && VT != MVT::i1)
2074 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2075 &PPC::GPRCRegClass);
2077 // If the constant is in range, use a load-immediate.
2078 const ConstantInt *CI = cast<ConstantInt>(C);
2079 if (isInt<16>(CI->getSExtValue())) {
2080 unsigned Opc = (VT == MVT::i64) ? PPC::LI8 : PPC::LI;
2081 unsigned ImmReg = createResultReg(RC);
2082 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ImmReg)
2083 .addImm( (UseSExt) ? CI->getSExtValue() : CI->getZExtValue() );
2087 // Construct the constant piecewise.
2088 int64_t Imm = CI->getZExtValue();
2091 return PPCMaterialize64BitInt(Imm, RC);
2092 else if (VT == MVT::i32)
2093 return PPCMaterialize32BitInt(Imm, RC);
2098 // Materialize a constant into a register, and return the register
2099 // number (or zero if we failed to handle it).
2100 unsigned PPCFastISel::fastMaterializeConstant(const Constant *C) {
2101 EVT CEVT = TLI.getValueType(C->getType(), true);
2103 // Only handle simple types.
2104 if (!CEVT.isSimple()) return 0;
2105 MVT VT = CEVT.getSimpleVT();
2107 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
2108 return PPCMaterializeFP(CFP, VT);
2109 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
2110 return PPCMaterializeGV(GV, VT);
2111 else if (isa<ConstantInt>(C))
2112 return PPCMaterializeInt(C, VT);
2117 // Materialize the address created by an alloca into a register, and
2118 // return the register number (or zero if we failed to handle it).
2119 unsigned PPCFastISel::fastMaterializeAlloca(const AllocaInst *AI) {
2120 // Don't handle dynamic allocas.
2121 if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
2124 if (!isLoadTypeLegal(AI->getType(), VT)) return 0;
2126 DenseMap<const AllocaInst*, int>::iterator SI =
2127 FuncInfo.StaticAllocaMap.find(AI);
2129 if (SI != FuncInfo.StaticAllocaMap.end()) {
2130 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
2131 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDI8),
2132 ResultReg).addFrameIndex(SI->second).addImm(0);
2139 // Fold loads into extends when possible.
2140 // FIXME: We can have multiple redundant extend/trunc instructions
2141 // following a load. The folding only picks up one. Extend this
2142 // to check subsequent instructions for the same pattern and remove
2143 // them. Thus ResultReg should be the def reg for the last redundant
2144 // instruction in a chain, and all intervening instructions can be
2145 // removed from parent. Change test/CodeGen/PowerPC/fast-isel-fold.ll
2146 // to add ELF64-NOT: rldicl to the appropriate tests when this works.
2147 bool PPCFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2148 const LoadInst *LI) {
2149 // Verify we have a legal type before going any further.
2151 if (!isLoadTypeLegal(LI->getType(), VT))
2154 // Combine load followed by zero- or sign-extend.
2155 bool IsZExt = false;
2156 switch(MI->getOpcode()) {
2161 case PPC::RLDICL_32_64: {
2163 unsigned MB = MI->getOperand(3).getImm();
2164 if ((VT == MVT::i8 && MB <= 56) ||
2165 (VT == MVT::i16 && MB <= 48) ||
2166 (VT == MVT::i32 && MB <= 32))
2172 case PPC::RLWINM8: {
2174 unsigned MB = MI->getOperand(3).getImm();
2175 if ((VT == MVT::i8 && MB <= 24) ||
2176 (VT == MVT::i16 && MB <= 16))
2183 case PPC::EXTSB8_32_64:
2184 /* There is no sign-extending load-byte instruction. */
2189 case PPC::EXTSH8_32_64: {
2190 if (VT != MVT::i16 && VT != MVT::i8)
2196 case PPC::EXTSW_32_64: {
2197 if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8)
2203 // See if we can handle this address.
2205 if (!PPCComputeAddress(LI->getOperand(0), Addr))
2208 unsigned ResultReg = MI->getOperand(0).getReg();
2210 if (!PPCEmitLoad(VT, ResultReg, Addr, nullptr, IsZExt))
2213 MI->eraseFromParent();
2217 // Attempt to lower call arguments in a faster way than done by
2218 // the selection DAG code.
2219 bool PPCFastISel::fastLowerArguments() {
2220 // Defer to normal argument lowering for now. It's reasonably
2221 // efficient. Consider doing something like ARM to handle the
2222 // case where all args fit in registers, no varargs, no float
2227 // Handle materializing integer constants into a register. This is not
2228 // automatically generated for PowerPC, so must be explicitly created here.
2229 unsigned PPCFastISel::fastEmit_i(MVT Ty, MVT VT, unsigned Opc, uint64_t Imm) {
2231 if (Opc != ISD::Constant)
2234 // If we're using CR bit registers for i1 values, handle that as a special
2236 if (VT == MVT::i1 && PPCSubTarget->useCRBits()) {
2237 unsigned ImmReg = createResultReg(&PPC::CRBITRCRegClass);
2238 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2239 TII.get(Imm == 0 ? PPC::CRUNSET : PPC::CRSET), ImmReg);
2243 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2244 VT != MVT::i8 && VT != MVT::i1)
2247 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2248 &PPC::GPRCRegClass);
2250 return PPCMaterialize64BitInt(Imm, RC);
2252 return PPCMaterialize32BitInt(Imm, RC);
2255 // Override for ADDI and ADDI8 to set the correct register class
2256 // on RHS operand 0. The automatic infrastructure naively assumes
2257 // GPRC for i32 and G8RC for i64; the concept of "no R0" is lost
2258 // for these cases. At the moment, none of the other automatically
2259 // generated RI instructions require special treatment. However, once
2260 // SelectSelect is implemented, "isel" requires similar handling.
2262 // Also be conservative about the output register class. Avoid
2263 // assigning R0 or X0 to the output register for GPRC and G8RC
2264 // register classes, as any such result could be used in ADDI, etc.,
2265 // where those regs have another meaning.
2266 unsigned PPCFastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
2267 const TargetRegisterClass *RC,
2268 unsigned Op0, bool Op0IsKill,
2270 if (MachineInstOpcode == PPC::ADDI)
2271 MRI.setRegClass(Op0, &PPC::GPRC_and_GPRC_NOR0RegClass);
2272 else if (MachineInstOpcode == PPC::ADDI8)
2273 MRI.setRegClass(Op0, &PPC::G8RC_and_G8RC_NOX0RegClass);
2275 const TargetRegisterClass *UseRC =
2276 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2277 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2279 return FastISel::fastEmitInst_ri(MachineInstOpcode, UseRC,
2280 Op0, Op0IsKill, Imm);
2283 // Override for instructions with one register operand to avoid use of
2284 // R0/X0. The automatic infrastructure isn't aware of the context so
2285 // we must be conservative.
2286 unsigned PPCFastISel::fastEmitInst_r(unsigned MachineInstOpcode,
2287 const TargetRegisterClass* RC,
2288 unsigned Op0, bool Op0IsKill) {
2289 const TargetRegisterClass *UseRC =
2290 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2291 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2293 return FastISel::fastEmitInst_r(MachineInstOpcode, UseRC, Op0, Op0IsKill);
2296 // Override for instructions with two register operands to avoid use
2297 // of R0/X0. The automatic infrastructure isn't aware of the context
2298 // so we must be conservative.
2299 unsigned PPCFastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
2300 const TargetRegisterClass* RC,
2301 unsigned Op0, bool Op0IsKill,
2302 unsigned Op1, bool Op1IsKill) {
2303 const TargetRegisterClass *UseRC =
2304 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2305 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2307 return FastISel::fastEmitInst_rr(MachineInstOpcode, UseRC, Op0, Op0IsKill,
2312 // Create the fast instruction selector for PowerPC64 ELF.
2313 FastISel *PPC::createFastISel(FunctionLoweringInfo &FuncInfo,
2314 const TargetLibraryInfo *LibInfo) {
2315 const TargetMachine &TM = FuncInfo.MF->getTarget();
2317 // Only available on 64-bit ELF for now.
2318 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
2319 if (Subtarget->isPPC64() && Subtarget->isSVR4ABI())
2320 return new PPCFastISel(FuncInfo, LibInfo);