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 "PPCCallingConv.h"
19 #include "PPCISelLowering.h"
20 #include "PPCMachineFunctionInfo.h"
21 #include "PPCSubtarget.h"
22 #include "PPCTargetMachine.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/FastISel.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/GetElementPtrTypeIterator.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetMachine.h"
41 //===----------------------------------------------------------------------===//
44 // fastLowerArguments: Handle simple cases.
45 // PPCMaterializeGV: Handle TLS.
46 // SelectCall: Handle function pointers.
47 // SelectCall: Handle multi-register return values.
48 // SelectCall: Optimize away nops for local calls.
49 // processCallArgs: Handle bit-converted arguments.
50 // finishCall: Handle multi-register return values.
51 // PPCComputeAddress: Handle parameter references as FrameIndex's.
52 // PPCEmitCmp: Handle immediate as operand 1.
53 // SelectCall: Handle small byval arguments.
54 // SelectIntrinsicCall: Implement.
55 // SelectSelect: Implement.
56 // Consider factoring isTypeLegal into the base class.
57 // Implement switches and jump tables.
59 //===----------------------------------------------------------------------===//
62 #define DEBUG_TYPE "ppcfastisel"
66 typedef struct Address {
79 // Innocuous defaults for our address.
81 : BaseType(RegBase), Offset(0) {
86 class PPCFastISel final : public FastISel {
88 const TargetMachine &TM;
89 const PPCSubtarget *PPCSubTarget;
90 PPCFunctionInfo *PPCFuncInfo;
91 const TargetInstrInfo &TII;
92 const TargetLowering &TLI;
96 explicit PPCFastISel(FunctionLoweringInfo &FuncInfo,
97 const TargetLibraryInfo *LibInfo)
98 : FastISel(FuncInfo, LibInfo), TM(FuncInfo.MF->getTarget()),
99 PPCSubTarget(&FuncInfo.MF->getSubtarget<PPCSubtarget>()),
100 PPCFuncInfo(FuncInfo.MF->getInfo<PPCFunctionInfo>()),
101 TII(*PPCSubTarget->getInstrInfo()),
102 TLI(*PPCSubTarget->getTargetLowering()),
103 Context(&FuncInfo.Fn->getContext()) {}
105 // Backend specific FastISel code.
107 bool fastSelectInstruction(const Instruction *I) override;
108 unsigned fastMaterializeConstant(const Constant *C) override;
109 unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
110 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
111 const LoadInst *LI) override;
112 bool fastLowerArguments() override;
113 unsigned fastEmit_i(MVT Ty, MVT RetTy, unsigned Opc, uint64_t Imm) override;
114 unsigned fastEmitInst_ri(unsigned MachineInstOpcode,
115 const TargetRegisterClass *RC,
116 unsigned Op0, bool Op0IsKill,
118 unsigned fastEmitInst_r(unsigned MachineInstOpcode,
119 const TargetRegisterClass *RC,
120 unsigned Op0, bool Op0IsKill);
121 unsigned fastEmitInst_rr(unsigned MachineInstOpcode,
122 const TargetRegisterClass *RC,
123 unsigned Op0, bool Op0IsKill,
124 unsigned Op1, bool Op1IsKill);
126 bool fastLowerCall(CallLoweringInfo &CLI) override;
128 // Instruction selection routines.
130 bool SelectLoad(const Instruction *I);
131 bool SelectStore(const Instruction *I);
132 bool SelectBranch(const Instruction *I);
133 bool SelectIndirectBr(const Instruction *I);
134 bool SelectFPExt(const Instruction *I);
135 bool SelectFPTrunc(const Instruction *I);
136 bool SelectIToFP(const Instruction *I, bool IsSigned);
137 bool SelectFPToI(const Instruction *I, bool IsSigned);
138 bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
139 bool SelectRet(const Instruction *I);
140 bool SelectTrunc(const Instruction *I);
141 bool SelectIntExt(const Instruction *I);
145 bool isTypeLegal(Type *Ty, MVT &VT);
146 bool isLoadTypeLegal(Type *Ty, MVT &VT);
147 bool isValueAvailable(const Value *V) const;
148 bool isVSFRCRegister(unsigned Register) const {
149 return MRI.getRegClass(Register)->getID() == PPC::VSFRCRegClassID;
151 bool isVSSRCRegister(unsigned Register) const {
152 return MRI.getRegClass(Register)->getID() == PPC::VSSRCRegClassID;
154 bool PPCEmitCmp(const Value *Src1Value, const Value *Src2Value,
155 bool isZExt, unsigned DestReg);
156 bool PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
157 const TargetRegisterClass *RC, bool IsZExt = true,
158 unsigned FP64LoadOpc = PPC::LFD);
159 bool PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr);
160 bool PPCComputeAddress(const Value *Obj, Address &Addr);
161 void PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
163 bool PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
164 unsigned DestReg, bool IsZExt);
165 unsigned PPCMaterializeFP(const ConstantFP *CFP, MVT VT);
166 unsigned PPCMaterializeGV(const GlobalValue *GV, MVT VT);
167 unsigned PPCMaterializeInt(const ConstantInt *CI, MVT VT,
168 bool UseSExt = true);
169 unsigned PPCMaterialize32BitInt(int64_t Imm,
170 const TargetRegisterClass *RC);
171 unsigned PPCMaterialize64BitInt(int64_t Imm,
172 const TargetRegisterClass *RC);
173 unsigned PPCMoveToIntReg(const Instruction *I, MVT VT,
174 unsigned SrcReg, bool IsSigned);
175 unsigned PPCMoveToFPReg(MVT VT, unsigned SrcReg, bool IsSigned);
177 // Call handling routines.
179 bool processCallArgs(SmallVectorImpl<Value*> &Args,
180 SmallVectorImpl<unsigned> &ArgRegs,
181 SmallVectorImpl<MVT> &ArgVTs,
182 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
183 SmallVectorImpl<unsigned> &RegArgs,
187 bool finishCall(MVT RetVT, CallLoweringInfo &CLI, unsigned &NumBytes);
188 CCAssignFn *usePPC32CCs(unsigned Flag);
191 #include "PPCGenFastISel.inc"
195 } // end anonymous namespace
197 #include "PPCGenCallingConv.inc"
199 // Function whose sole purpose is to kill compiler warnings
200 // stemming from unused functions included from PPCGenCallingConv.inc.
201 CCAssignFn *PPCFastISel::usePPC32CCs(unsigned Flag) {
203 return CC_PPC32_SVR4;
205 return CC_PPC32_SVR4_ByVal;
207 return CC_PPC32_SVR4_VarArg;
212 static Optional<PPC::Predicate> getComparePred(CmpInst::Predicate Pred) {
214 // These are not representable with any single compare.
215 case CmpInst::FCMP_FALSE:
216 case CmpInst::FCMP_UEQ:
217 case CmpInst::FCMP_UGT:
218 case CmpInst::FCMP_UGE:
219 case CmpInst::FCMP_ULT:
220 case CmpInst::FCMP_ULE:
221 case CmpInst::FCMP_UNE:
222 case CmpInst::FCMP_TRUE:
224 return Optional<PPC::Predicate>();
226 case CmpInst::FCMP_OEQ:
227 case CmpInst::ICMP_EQ:
230 case CmpInst::FCMP_OGT:
231 case CmpInst::ICMP_UGT:
232 case CmpInst::ICMP_SGT:
235 case CmpInst::FCMP_OGE:
236 case CmpInst::ICMP_UGE:
237 case CmpInst::ICMP_SGE:
240 case CmpInst::FCMP_OLT:
241 case CmpInst::ICMP_ULT:
242 case CmpInst::ICMP_SLT:
245 case CmpInst::FCMP_OLE:
246 case CmpInst::ICMP_ULE:
247 case CmpInst::ICMP_SLE:
250 case CmpInst::FCMP_ONE:
251 case CmpInst::ICMP_NE:
254 case CmpInst::FCMP_ORD:
257 case CmpInst::FCMP_UNO:
262 // Determine whether the type Ty is simple enough to be handled by
263 // fast-isel, and return its equivalent machine type in VT.
264 // FIXME: Copied directly from ARM -- factor into base class?
265 bool PPCFastISel::isTypeLegal(Type *Ty, MVT &VT) {
266 EVT Evt = TLI.getValueType(DL, Ty, true);
268 // Only handle simple types.
269 if (Evt == MVT::Other || !Evt.isSimple()) return false;
270 VT = Evt.getSimpleVT();
272 // Handle all legal types, i.e. a register that will directly hold this
274 return TLI.isTypeLegal(VT);
277 // Determine whether the type Ty is simple enough to be handled by
278 // fast-isel as a load target, and return its equivalent machine type in VT.
279 bool PPCFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
280 if (isTypeLegal(Ty, VT)) return true;
282 // If this is a type than can be sign or zero-extended to a basic operation
283 // go ahead and accept it now.
284 if (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) {
291 bool PPCFastISel::isValueAvailable(const Value *V) const {
292 if (!isa<Instruction>(V))
295 const auto *I = cast<Instruction>(V);
296 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
302 // Given a value Obj, create an Address object Addr that represents its
303 // address. Return false if we can't handle it.
304 bool PPCFastISel::PPCComputeAddress(const Value *Obj, Address &Addr) {
305 const User *U = nullptr;
306 unsigned Opcode = Instruction::UserOp1;
307 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
308 // Don't walk into other basic blocks unless the object is an alloca from
309 // another block, otherwise it may not have a virtual register assigned.
310 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
311 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
312 Opcode = I->getOpcode();
315 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
316 Opcode = C->getOpcode();
323 case Instruction::BitCast:
324 // Look through bitcasts.
325 return PPCComputeAddress(U->getOperand(0), Addr);
326 case Instruction::IntToPtr:
327 // Look past no-op inttoptrs.
328 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
329 TLI.getPointerTy(DL))
330 return PPCComputeAddress(U->getOperand(0), Addr);
332 case Instruction::PtrToInt:
333 // Look past no-op ptrtoints.
334 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
335 return PPCComputeAddress(U->getOperand(0), Addr);
337 case Instruction::GetElementPtr: {
338 Address SavedAddr = Addr;
339 long TmpOffset = Addr.Offset;
341 // Iterate through the GEP folding the constants into offsets where
343 gep_type_iterator GTI = gep_type_begin(U);
344 for (User::const_op_iterator II = U->op_begin() + 1, IE = U->op_end();
345 II != IE; ++II, ++GTI) {
346 const Value *Op = *II;
347 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
348 const StructLayout *SL = DL.getStructLayout(STy);
349 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
350 TmpOffset += SL->getElementOffset(Idx);
352 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
354 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
355 // Constant-offset addressing.
356 TmpOffset += CI->getSExtValue() * S;
359 if (canFoldAddIntoGEP(U, Op)) {
360 // A compatible add with a constant operand. Fold the constant.
362 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
363 TmpOffset += CI->getSExtValue() * S;
364 // Iterate on the other operand.
365 Op = cast<AddOperator>(Op)->getOperand(0);
369 goto unsupported_gep;
374 // Try to grab the base operand now.
375 Addr.Offset = TmpOffset;
376 if (PPCComputeAddress(U->getOperand(0), Addr)) return true;
378 // We failed, restore everything and try the other options.
384 case Instruction::Alloca: {
385 const AllocaInst *AI = cast<AllocaInst>(Obj);
386 DenseMap<const AllocaInst*, int>::iterator SI =
387 FuncInfo.StaticAllocaMap.find(AI);
388 if (SI != FuncInfo.StaticAllocaMap.end()) {
389 Addr.BaseType = Address::FrameIndexBase;
390 Addr.Base.FI = SI->second;
397 // FIXME: References to parameters fall through to the behavior
398 // below. They should be able to reference a frame index since
399 // they are stored to the stack, so we can get "ld rx, offset(r1)"
400 // instead of "addi ry, r1, offset / ld rx, 0(ry)". Obj will
401 // just contain the parameter. Try to handle this with a FI.
403 // Try to get this in a register if nothing else has worked.
404 if (Addr.Base.Reg == 0)
405 Addr.Base.Reg = getRegForValue(Obj);
407 // Prevent assignment of base register to X0, which is inappropriate
408 // for loads and stores alike.
409 if (Addr.Base.Reg != 0)
410 MRI.setRegClass(Addr.Base.Reg, &PPC::G8RC_and_G8RC_NOX0RegClass);
412 return Addr.Base.Reg != 0;
415 // Fix up some addresses that can't be used directly. For example, if
416 // an offset won't fit in an instruction field, we may need to move it
417 // into an index register.
418 void PPCFastISel::PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
419 unsigned &IndexReg) {
421 // Check whether the offset fits in the instruction field.
422 if (!isInt<16>(Addr.Offset))
425 // If this is a stack pointer and the offset needs to be simplified then
426 // put the alloca address into a register, set the base type back to
427 // register and continue. This should almost never happen.
428 if (!UseOffset && Addr.BaseType == Address::FrameIndexBase) {
429 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
430 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDI8),
431 ResultReg).addFrameIndex(Addr.Base.FI).addImm(0);
432 Addr.Base.Reg = ResultReg;
433 Addr.BaseType = Address::RegBase;
437 IntegerType *OffsetTy = ((VT == MVT::i32) ? Type::getInt32Ty(*Context)
438 : Type::getInt64Ty(*Context));
439 const ConstantInt *Offset =
440 ConstantInt::getSigned(OffsetTy, (int64_t)(Addr.Offset));
441 IndexReg = PPCMaterializeInt(Offset, MVT::i64);
442 assert(IndexReg && "Unexpected error in PPCMaterializeInt!");
446 // Emit a load instruction if possible, returning true if we succeeded,
447 // otherwise false. See commentary below for how the register class of
448 // the load is determined.
449 bool PPCFastISel::PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
450 const TargetRegisterClass *RC,
451 bool IsZExt, unsigned FP64LoadOpc) {
453 bool UseOffset = true;
455 // If ResultReg is given, it determines the register class of the load.
456 // Otherwise, RC is the register class to use. If the result of the
457 // load isn't anticipated in this block, both may be zero, in which
458 // case we must make a conservative guess. In particular, don't assign
459 // R0 or X0 to the result register, as the result may be used in a load,
460 // store, add-immediate, or isel that won't permit this. (Though
461 // perhaps the spill and reload of live-exit values would handle this?)
462 const TargetRegisterClass *UseRC =
463 (ResultReg ? MRI.getRegClass(ResultReg) :
465 (VT == MVT::f64 ? &PPC::F8RCRegClass :
466 (VT == MVT::f32 ? &PPC::F4RCRegClass :
467 (VT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
468 &PPC::GPRC_and_GPRC_NOR0RegClass)))));
470 bool Is32BitInt = UseRC->hasSuperClassEq(&PPC::GPRCRegClass);
472 switch (VT.SimpleTy) {
473 default: // e.g., vector types not handled
476 Opc = Is32BitInt ? PPC::LBZ : PPC::LBZ8;
480 (Is32BitInt ? PPC::LHZ : PPC::LHZ8) :
481 (Is32BitInt ? PPC::LHA : PPC::LHA8));
485 (Is32BitInt ? PPC::LWZ : PPC::LWZ8) :
486 (Is32BitInt ? PPC::LWA_32 : PPC::LWA));
487 if ((Opc == PPC::LWA || Opc == PPC::LWA_32) && ((Addr.Offset & 3) != 0))
492 assert(UseRC->hasSuperClassEq(&PPC::G8RCRegClass) &&
493 "64-bit load with 32-bit target??");
494 UseOffset = ((Addr.Offset & 3) == 0);
504 // If necessary, materialize the offset into a register and use
505 // the indexed form. Also handle stack pointers with special needs.
506 unsigned IndexReg = 0;
507 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
509 // If this is a potential VSX load with an offset of 0, a VSX indexed load can
511 bool IsVSSRC = (ResultReg != 0) && isVSSRCRegister(ResultReg);
512 bool IsVSFRC = (ResultReg != 0) && isVSFRCRegister(ResultReg);
513 bool Is32VSXLoad = IsVSSRC && Opc == PPC::LFS;
514 bool Is64VSXLoad = IsVSSRC && Opc == PPC::LFD;
515 if ((Is32VSXLoad || Is64VSXLoad) &&
516 (Addr.BaseType != Address::FrameIndexBase) && UseOffset &&
517 (Addr.Offset == 0)) {
522 ResultReg = createResultReg(UseRC);
524 // Note: If we still have a frame index here, we know the offset is
525 // in range, as otherwise PPCSimplifyAddress would have converted it
527 if (Addr.BaseType == Address::FrameIndexBase) {
528 // VSX only provides an indexed load.
529 if (Is32VSXLoad || Is64VSXLoad) return false;
531 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
532 MachinePointerInfo::getFixedStack(*FuncInfo.MF, Addr.Base.FI,
534 MachineMemOperand::MOLoad, MFI.getObjectSize(Addr.Base.FI),
535 MFI.getObjectAlignment(Addr.Base.FI));
537 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
538 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
540 // Base reg with offset in range.
541 } else if (UseOffset) {
542 // VSX only provides an indexed load.
543 if (Is32VSXLoad || Is64VSXLoad) return false;
545 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
546 .addImm(Addr.Offset).addReg(Addr.Base.Reg);
550 // Get the RR opcode corresponding to the RI one. FIXME: It would be
551 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
552 // is hard to get at.
554 default: llvm_unreachable("Unexpected opcode!");
555 case PPC::LBZ: Opc = PPC::LBZX; break;
556 case PPC::LBZ8: Opc = PPC::LBZX8; break;
557 case PPC::LHZ: Opc = PPC::LHZX; break;
558 case PPC::LHZ8: Opc = PPC::LHZX8; break;
559 case PPC::LHA: Opc = PPC::LHAX; break;
560 case PPC::LHA8: Opc = PPC::LHAX8; break;
561 case PPC::LWZ: Opc = PPC::LWZX; break;
562 case PPC::LWZ8: Opc = PPC::LWZX8; break;
563 case PPC::LWA: Opc = PPC::LWAX; break;
564 case PPC::LWA_32: Opc = PPC::LWAX_32; break;
565 case PPC::LD: Opc = PPC::LDX; break;
566 case PPC::LFS: Opc = IsVSSRC ? PPC::LXSSPX : PPC::LFSX; break;
567 case PPC::LFD: Opc = IsVSFRC ? PPC::LXSDX : PPC::LFDX; break;
569 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
570 .addReg(Addr.Base.Reg).addReg(IndexReg);
576 // Attempt to fast-select a load instruction.
577 bool PPCFastISel::SelectLoad(const Instruction *I) {
578 // FIXME: No atomic loads are supported.
579 if (cast<LoadInst>(I)->isAtomic())
582 // Verify we have a legal type before going any further.
584 if (!isLoadTypeLegal(I->getType(), VT))
587 // See if we can handle this address.
589 if (!PPCComputeAddress(I->getOperand(0), Addr))
592 // Look at the currently assigned register for this instruction
593 // to determine the required register class. This is necessary
594 // to constrain RA from using R0/X0 when this is not legal.
595 unsigned AssignedReg = FuncInfo.ValueMap[I];
596 const TargetRegisterClass *RC =
597 AssignedReg ? MRI.getRegClass(AssignedReg) : nullptr;
599 unsigned ResultReg = 0;
600 if (!PPCEmitLoad(VT, ResultReg, Addr, RC))
602 updateValueMap(I, ResultReg);
606 // Emit a store instruction to store SrcReg at Addr.
607 bool PPCFastISel::PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr) {
608 assert(SrcReg && "Nothing to store!");
610 bool UseOffset = true;
612 const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
613 bool Is32BitInt = RC->hasSuperClassEq(&PPC::GPRCRegClass);
615 switch (VT.SimpleTy) {
616 default: // e.g., vector types not handled
619 Opc = Is32BitInt ? PPC::STB : PPC::STB8;
622 Opc = Is32BitInt ? PPC::STH : PPC::STH8;
625 assert(Is32BitInt && "Not GPRC for i32??");
630 UseOffset = ((Addr.Offset & 3) == 0);
640 // If necessary, materialize the offset into a register and use
641 // the indexed form. Also handle stack pointers with special needs.
642 unsigned IndexReg = 0;
643 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
645 // If this is a potential VSX store with an offset of 0, a VSX indexed store
647 bool IsVSSRC = isVSSRCRegister(SrcReg);
648 bool IsVSFRC = isVSFRCRegister(SrcReg);
649 bool Is32VSXStore = IsVSSRC && Opc == PPC::STFS;
650 bool Is64VSXStore = IsVSFRC && Opc == PPC::STFD;
651 if ((Is32VSXStore || Is64VSXStore) &&
652 (Addr.BaseType != Address::FrameIndexBase) && UseOffset &&
653 (Addr.Offset == 0)) {
657 // Note: If we still have a frame index here, we know the offset is
658 // in range, as otherwise PPCSimplifyAddress would have converted it
660 if (Addr.BaseType == Address::FrameIndexBase) {
661 // VSX only provides an indexed store.
662 if (Is32VSXStore || Is64VSXStore) return false;
664 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
665 MachinePointerInfo::getFixedStack(*FuncInfo.MF, Addr.Base.FI,
667 MachineMemOperand::MOStore, MFI.getObjectSize(Addr.Base.FI),
668 MFI.getObjectAlignment(Addr.Base.FI));
670 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
673 .addFrameIndex(Addr.Base.FI)
676 // Base reg with offset in range.
677 } else if (UseOffset) {
678 // VSX only provides an indexed store.
679 if (Is32VSXStore || Is64VSXStore) return false;
681 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
682 .addReg(SrcReg).addImm(Addr.Offset).addReg(Addr.Base.Reg);
686 // Get the RR opcode corresponding to the RI one. FIXME: It would be
687 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
688 // is hard to get at.
690 default: llvm_unreachable("Unexpected opcode!");
691 case PPC::STB: Opc = PPC::STBX; break;
692 case PPC::STH : Opc = PPC::STHX; break;
693 case PPC::STW : Opc = PPC::STWX; break;
694 case PPC::STB8: Opc = PPC::STBX8; break;
695 case PPC::STH8: Opc = PPC::STHX8; break;
696 case PPC::STW8: Opc = PPC::STWX8; break;
697 case PPC::STD: Opc = PPC::STDX; break;
698 case PPC::STFS: Opc = IsVSSRC ? PPC::STXSSPX : PPC::STFSX; break;
699 case PPC::STFD: Opc = IsVSFRC ? PPC::STXSDX : PPC::STFDX; break;
702 auto MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
705 // If we have an index register defined we use it in the store inst,
706 // otherwise we use X0 as base as it makes the vector instructions to
707 // use zero in the computation of the effective address regardless the
708 // content of the register.
710 MIB.addReg(Addr.Base.Reg).addReg(IndexReg);
712 MIB.addReg(PPC::ZERO8).addReg(Addr.Base.Reg);
718 // Attempt to fast-select a store instruction.
719 bool PPCFastISel::SelectStore(const Instruction *I) {
720 Value *Op0 = I->getOperand(0);
723 // FIXME: No atomics loads are supported.
724 if (cast<StoreInst>(I)->isAtomic())
727 // Verify we have a legal type before going any further.
729 if (!isLoadTypeLegal(Op0->getType(), VT))
732 // Get the value to be stored into a register.
733 SrcReg = getRegForValue(Op0);
737 // See if we can handle this address.
739 if (!PPCComputeAddress(I->getOperand(1), Addr))
742 if (!PPCEmitStore(VT, SrcReg, Addr))
748 // Attempt to fast-select a branch instruction.
749 bool PPCFastISel::SelectBranch(const Instruction *I) {
750 const BranchInst *BI = cast<BranchInst>(I);
751 MachineBasicBlock *BrBB = FuncInfo.MBB;
752 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
753 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
755 // For now, just try the simplest case where it's fed by a compare.
756 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
757 if (isValueAvailable(CI)) {
758 Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
762 PPC::Predicate PPCPred = OptPPCPred.getValue();
764 // Take advantage of fall-through opportunities.
765 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
767 PPCPred = PPC::InvertPredicate(PPCPred);
770 unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
772 if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
776 BuildMI(*BrBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::BCC))
777 .addImm(PPCPred).addReg(CondReg).addMBB(TBB);
778 fastEmitBranch(FBB, DbgLoc);
779 FuncInfo.MBB->addSuccessor(TBB);
782 } else if (const ConstantInt *CI =
783 dyn_cast<ConstantInt>(BI->getCondition())) {
784 uint64_t Imm = CI->getZExtValue();
785 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
786 fastEmitBranch(Target, DbgLoc);
790 // FIXME: ARM looks for a case where the block containing the compare
791 // has been split from the block containing the branch. If this happens,
792 // there is a vreg available containing the result of the compare. I'm
793 // not sure we can do much, as we've lost the predicate information with
794 // the compare instruction -- we have a 4-bit CR but don't know which bit
799 // Attempt to emit a compare of the two source values. Signed and unsigned
800 // comparisons are supported. Return false if we can't handle it.
801 bool PPCFastISel::PPCEmitCmp(const Value *SrcValue1, const Value *SrcValue2,
802 bool IsZExt, unsigned DestReg) {
803 Type *Ty = SrcValue1->getType();
804 EVT SrcEVT = TLI.getValueType(DL, Ty, true);
805 if (!SrcEVT.isSimple())
807 MVT SrcVT = SrcEVT.getSimpleVT();
809 if (SrcVT == MVT::i1 && PPCSubTarget->useCRBits())
812 // See if operand 2 is an immediate encodeable in the compare.
813 // FIXME: Operands are not in canonical order at -O0, so an immediate
814 // operand in position 1 is a lost opportunity for now. We are
815 // similar to ARM in this regard.
819 // Only 16-bit integer constants can be represented in compares for
820 // PowerPC. Others will be materialized into a register.
821 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(SrcValue2)) {
822 if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
823 SrcVT == MVT::i8 || SrcVT == MVT::i1) {
824 const APInt &CIVal = ConstInt->getValue();
825 Imm = (IsZExt) ? (long)CIVal.getZExtValue() : (long)CIVal.getSExtValue();
826 if ((IsZExt && isUInt<16>(Imm)) || (!IsZExt && isInt<16>(Imm)))
832 bool NeedsExt = false;
833 switch (SrcVT.SimpleTy) {
834 default: return false;
836 CmpOpc = PPC::FCMPUS;
839 CmpOpc = PPC::FCMPUD;
845 // Intentional fall-through.
848 CmpOpc = IsZExt ? PPC::CMPLW : PPC::CMPW;
850 CmpOpc = IsZExt ? PPC::CMPLWI : PPC::CMPWI;
854 CmpOpc = IsZExt ? PPC::CMPLD : PPC::CMPD;
856 CmpOpc = IsZExt ? PPC::CMPLDI : PPC::CMPDI;
860 unsigned SrcReg1 = getRegForValue(SrcValue1);
864 unsigned SrcReg2 = 0;
866 SrcReg2 = getRegForValue(SrcValue2);
872 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
873 if (!PPCEmitIntExt(SrcVT, SrcReg1, MVT::i32, ExtReg, IsZExt))
878 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
879 if (!PPCEmitIntExt(SrcVT, SrcReg2, MVT::i32, ExtReg, IsZExt))
886 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc), DestReg)
887 .addReg(SrcReg1).addReg(SrcReg2);
889 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc), DestReg)
890 .addReg(SrcReg1).addImm(Imm);
895 // Attempt to fast-select a floating-point extend instruction.
896 bool PPCFastISel::SelectFPExt(const Instruction *I) {
897 Value *Src = I->getOperand(0);
898 EVT SrcVT = TLI.getValueType(DL, Src->getType(), true);
899 EVT DestVT = TLI.getValueType(DL, I->getType(), true);
901 if (SrcVT != MVT::f32 || DestVT != MVT::f64)
904 unsigned SrcReg = getRegForValue(Src);
908 // No code is generated for a FP extend.
909 updateValueMap(I, SrcReg);
913 // Attempt to fast-select a floating-point truncate instruction.
914 bool PPCFastISel::SelectFPTrunc(const Instruction *I) {
915 Value *Src = I->getOperand(0);
916 EVT SrcVT = TLI.getValueType(DL, Src->getType(), true);
917 EVT DestVT = TLI.getValueType(DL, I->getType(), true);
919 if (SrcVT != MVT::f64 || DestVT != MVT::f32)
922 unsigned SrcReg = getRegForValue(Src);
926 // Round the result to single precision.
927 unsigned DestReg = createResultReg(&PPC::F4RCRegClass);
928 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::FRSP), DestReg)
931 updateValueMap(I, DestReg);
935 // Move an i32 or i64 value in a GPR to an f64 value in an FPR.
936 // FIXME: When direct register moves are implemented (see PowerISA 2.07),
937 // those should be used instead of moving via a stack slot when the
938 // subtarget permits.
939 // FIXME: The code here is sloppy for the 4-byte case. Can use a 4-byte
940 // stack slot and 4-byte store/load sequence. Or just sext the 4-byte
941 // case to 8 bytes which produces tighter code but wastes stack space.
942 unsigned PPCFastISel::PPCMoveToFPReg(MVT SrcVT, unsigned SrcReg,
945 // If necessary, extend 32-bit int to 64-bit.
946 if (SrcVT == MVT::i32) {
947 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
948 if (!PPCEmitIntExt(MVT::i32, SrcReg, MVT::i64, TmpReg, !IsSigned))
953 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
955 Addr.BaseType = Address::FrameIndexBase;
956 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
958 // Store the value from the GPR.
959 if (!PPCEmitStore(MVT::i64, SrcReg, Addr))
962 // Load the integer value into an FPR. The kind of load used depends
963 // on a number of conditions.
964 unsigned LoadOpc = PPC::LFD;
966 if (SrcVT == MVT::i32) {
968 LoadOpc = PPC::LFIWZX;
969 Addr.Offset = (PPCSubTarget->isLittleEndian()) ? 0 : 4;
970 } else if (PPCSubTarget->hasLFIWAX()) {
971 LoadOpc = PPC::LFIWAX;
972 Addr.Offset = (PPCSubTarget->isLittleEndian()) ? 0 : 4;
976 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
977 unsigned ResultReg = 0;
978 if (!PPCEmitLoad(MVT::f64, ResultReg, Addr, RC, !IsSigned, LoadOpc))
984 // Attempt to fast-select an integer-to-floating-point conversion.
985 // FIXME: Once fast-isel has better support for VSX, conversions using
986 // direct moves should be implemented.
987 bool PPCFastISel::SelectIToFP(const Instruction *I, bool IsSigned) {
989 Type *DstTy = I->getType();
990 if (!isTypeLegal(DstTy, DstVT))
993 if (DstVT != MVT::f32 && DstVT != MVT::f64)
996 Value *Src = I->getOperand(0);
997 EVT SrcEVT = TLI.getValueType(DL, Src->getType(), true);
998 if (!SrcEVT.isSimple())
1001 MVT SrcVT = SrcEVT.getSimpleVT();
1003 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 &&
1004 SrcVT != MVT::i32 && SrcVT != MVT::i64)
1007 unsigned SrcReg = getRegForValue(Src);
1011 // We can only lower an unsigned convert if we have the newer
1012 // floating-point conversion operations.
1013 if (!IsSigned && !PPCSubTarget->hasFPCVT())
1016 // FIXME: For now we require the newer floating-point conversion operations
1017 // (which are present only on P7 and A2 server models) when converting
1018 // to single-precision float. Otherwise we have to generate a lot of
1019 // fiddly code to avoid double rounding. If necessary, the fiddly code
1020 // can be found in PPCTargetLowering::LowerINT_TO_FP().
1021 if (DstVT == MVT::f32 && !PPCSubTarget->hasFPCVT())
1024 // Extend the input if necessary.
1025 if (SrcVT == MVT::i8 || SrcVT == MVT::i16) {
1026 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
1027 if (!PPCEmitIntExt(SrcVT, SrcReg, MVT::i64, TmpReg, !IsSigned))
1033 // Move the integer value to an FPR.
1034 unsigned FPReg = PPCMoveToFPReg(SrcVT, SrcReg, IsSigned);
1038 // Determine the opcode for the conversion.
1039 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
1040 unsigned DestReg = createResultReg(RC);
1043 if (DstVT == MVT::f32)
1044 Opc = IsSigned ? PPC::FCFIDS : PPC::FCFIDUS;
1046 Opc = IsSigned ? PPC::FCFID : PPC::FCFIDU;
1048 // Generate the convert.
1049 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1052 updateValueMap(I, DestReg);
1056 // Move the floating-point value in SrcReg into an integer destination
1057 // register, and return the register (or zero if we can't handle it).
1058 // FIXME: When direct register moves are implemented (see PowerISA 2.07),
1059 // those should be used instead of moving via a stack slot when the
1060 // subtarget permits.
1061 unsigned PPCFastISel::PPCMoveToIntReg(const Instruction *I, MVT VT,
1062 unsigned SrcReg, bool IsSigned) {
1063 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
1064 // Note that if have STFIWX available, we could use a 4-byte stack
1065 // slot for i32, but this being fast-isel we'll just go with the
1066 // easiest code gen possible.
1068 Addr.BaseType = Address::FrameIndexBase;
1069 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
1071 // Store the value from the FPR.
1072 if (!PPCEmitStore(MVT::f64, SrcReg, Addr))
1075 // Reload it into a GPR. If we want an i32, modify the address
1076 // to have a 4-byte offset so we load from the right place.
1080 // Look at the currently assigned register for this instruction
1081 // to determine the required register class.
1082 unsigned AssignedReg = FuncInfo.ValueMap[I];
1083 const TargetRegisterClass *RC =
1084 AssignedReg ? MRI.getRegClass(AssignedReg) : nullptr;
1086 unsigned ResultReg = 0;
1087 if (!PPCEmitLoad(VT, ResultReg, Addr, RC, !IsSigned))
1093 // Attempt to fast-select a floating-point-to-integer conversion.
1094 // FIXME: Once fast-isel has better support for VSX, conversions using
1095 // direct moves should be implemented.
1096 bool PPCFastISel::SelectFPToI(const Instruction *I, bool IsSigned) {
1098 Type *DstTy = I->getType();
1099 if (!isTypeLegal(DstTy, DstVT))
1102 if (DstVT != MVT::i32 && DstVT != MVT::i64)
1105 // If we don't have FCTIDUZ and we need it, punt to SelectionDAG.
1106 if (DstVT == MVT::i64 && !IsSigned && !PPCSubTarget->hasFPCVT())
1109 Value *Src = I->getOperand(0);
1110 Type *SrcTy = Src->getType();
1111 if (!isTypeLegal(SrcTy, SrcVT))
1114 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
1117 unsigned SrcReg = getRegForValue(Src);
1121 // Convert f32 to f64 if necessary. This is just a meaningless copy
1122 // to get the register class right. COPY_TO_REGCLASS is needed since
1123 // a COPY from F4RC to F8RC is converted to a F4RC-F4RC copy downstream.
1124 const TargetRegisterClass *InRC = MRI.getRegClass(SrcReg);
1125 if (InRC == &PPC::F4RCRegClass) {
1126 unsigned TmpReg = createResultReg(&PPC::F8RCRegClass);
1127 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1128 TII.get(TargetOpcode::COPY_TO_REGCLASS), TmpReg)
1129 .addReg(SrcReg).addImm(PPC::F8RCRegClassID);
1133 // Determine the opcode for the conversion, which takes place
1134 // entirely within FPRs.
1135 unsigned DestReg = createResultReg(&PPC::F8RCRegClass);
1138 if (DstVT == MVT::i32)
1142 Opc = PPCSubTarget->hasFPCVT() ? PPC::FCTIWUZ : PPC::FCTIDZ;
1144 Opc = IsSigned ? PPC::FCTIDZ : PPC::FCTIDUZ;
1146 // Generate the convert.
1147 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1150 // Now move the integer value from a float register to an integer register.
1151 unsigned IntReg = PPCMoveToIntReg(I, DstVT, DestReg, IsSigned);
1155 updateValueMap(I, IntReg);
1159 // Attempt to fast-select a binary integer operation that isn't already
1160 // handled automatically.
1161 bool PPCFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1162 EVT DestVT = TLI.getValueType(DL, I->getType(), true);
1164 // We can get here in the case when we have a binary operation on a non-legal
1165 // type and the target independent selector doesn't know how to handle it.
1166 if (DestVT != MVT::i16 && DestVT != MVT::i8)
1169 // Look at the currently assigned register for this instruction
1170 // to determine the required register class. If there is no register,
1171 // make a conservative choice (don't assign R0).
1172 unsigned AssignedReg = FuncInfo.ValueMap[I];
1173 const TargetRegisterClass *RC =
1174 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1175 &PPC::GPRC_and_GPRC_NOR0RegClass);
1176 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1179 switch (ISDOpcode) {
1180 default: return false;
1182 Opc = IsGPRC ? PPC::ADD4 : PPC::ADD8;
1185 Opc = IsGPRC ? PPC::OR : PPC::OR8;
1188 Opc = IsGPRC ? PPC::SUBF : PPC::SUBF8;
1192 unsigned ResultReg = createResultReg(RC ? RC : &PPC::G8RCRegClass);
1193 unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1194 if (SrcReg1 == 0) return false;
1196 // Handle case of small immediate operand.
1197 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(1))) {
1198 const APInt &CIVal = ConstInt->getValue();
1199 int Imm = (int)CIVal.getSExtValue();
1201 if (isInt<16>(Imm)) {
1204 llvm_unreachable("Missing case!");
1207 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1211 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1224 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1233 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1240 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
1244 updateValueMap(I, ResultReg);
1251 unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1252 if (SrcReg2 == 0) return false;
1254 // Reverse operands for subtract-from.
1255 if (ISDOpcode == ISD::SUB)
1256 std::swap(SrcReg1, SrcReg2);
1258 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1259 .addReg(SrcReg1).addReg(SrcReg2);
1260 updateValueMap(I, ResultReg);
1264 // Handle arguments to a call that we're attempting to fast-select.
1265 // Return false if the arguments are too complex for us at the moment.
1266 bool PPCFastISel::processCallArgs(SmallVectorImpl<Value*> &Args,
1267 SmallVectorImpl<unsigned> &ArgRegs,
1268 SmallVectorImpl<MVT> &ArgVTs,
1269 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1270 SmallVectorImpl<unsigned> &RegArgs,
1274 SmallVector<CCValAssign, 16> ArgLocs;
1275 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, *Context);
1277 // Reserve space for the linkage area on the stack.
1278 unsigned LinkageSize = PPCSubTarget->getFrameLowering()->getLinkageSize();
1279 CCInfo.AllocateStack(LinkageSize, 8);
1281 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_PPC64_ELF_FIS);
1283 // Bail out if we can't handle any of the arguments.
1284 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1285 CCValAssign &VA = ArgLocs[I];
1286 MVT ArgVT = ArgVTs[VA.getValNo()];
1288 // Skip vector arguments for now, as well as long double and
1289 // uint128_t, and anything that isn't passed in a register.
1290 if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64 || ArgVT == MVT::i1 ||
1291 !VA.isRegLoc() || VA.needsCustom())
1294 // Skip bit-converted arguments for now.
1295 if (VA.getLocInfo() == CCValAssign::BCvt)
1299 // Get a count of how many bytes are to be pushed onto the stack.
1300 NumBytes = CCInfo.getNextStackOffset();
1302 // The prolog code of the callee may store up to 8 GPR argument registers to
1303 // the stack, allowing va_start to index over them in memory if its varargs.
1304 // Because we cannot tell if this is needed on the caller side, we have to
1305 // conservatively assume that it is needed. As such, make sure we have at
1306 // least enough stack space for the caller to store the 8 GPRs.
1307 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
1308 NumBytes = std::max(NumBytes, LinkageSize + 64);
1310 // Issue CALLSEQ_START.
1311 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1312 TII.get(TII.getCallFrameSetupOpcode()))
1315 // Prepare to assign register arguments. Every argument uses up a
1316 // GPR protocol register even if it's passed in a floating-point
1317 // register (unless we're using the fast calling convention).
1318 unsigned NextGPR = PPC::X3;
1319 unsigned NextFPR = PPC::F1;
1321 // Process arguments.
1322 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1323 CCValAssign &VA = ArgLocs[I];
1324 unsigned Arg = ArgRegs[VA.getValNo()];
1325 MVT ArgVT = ArgVTs[VA.getValNo()];
1327 // Handle argument promotion and bitcasts.
1328 switch (VA.getLocInfo()) {
1330 llvm_unreachable("Unknown loc info!");
1331 case CCValAssign::Full:
1333 case CCValAssign::SExt: {
1334 MVT DestVT = VA.getLocVT();
1335 const TargetRegisterClass *RC =
1336 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1337 unsigned TmpReg = createResultReg(RC);
1338 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/false))
1339 llvm_unreachable("Failed to emit a sext!");
1344 case CCValAssign::AExt:
1345 case CCValAssign::ZExt: {
1346 MVT DestVT = VA.getLocVT();
1347 const TargetRegisterClass *RC =
1348 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1349 unsigned TmpReg = createResultReg(RC);
1350 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/true))
1351 llvm_unreachable("Failed to emit a zext!");
1356 case CCValAssign::BCvt: {
1357 // FIXME: Not yet handled.
1358 llvm_unreachable("Should have bailed before getting here!");
1363 // Copy this argument to the appropriate register.
1365 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) {
1367 if (CC != CallingConv::Fast)
1372 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1373 TII.get(TargetOpcode::COPY), ArgReg).addReg(Arg);
1374 RegArgs.push_back(ArgReg);
1380 // For a call that we've determined we can fast-select, finish the
1381 // call sequence and generate a copy to obtain the return value (if any).
1382 bool PPCFastISel::finishCall(MVT RetVT, CallLoweringInfo &CLI, unsigned &NumBytes) {
1383 CallingConv::ID CC = CLI.CallConv;
1385 // Issue CallSEQ_END.
1386 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1387 TII.get(TII.getCallFrameDestroyOpcode()))
1388 .addImm(NumBytes).addImm(0);
1390 // Next, generate a copy to obtain the return value.
1391 // FIXME: No multi-register return values yet, though I don't foresee
1392 // any real difficulties there.
1393 if (RetVT != MVT::isVoid) {
1394 SmallVector<CCValAssign, 16> RVLocs;
1395 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
1396 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1397 CCValAssign &VA = RVLocs[0];
1398 assert(RVLocs.size() == 1 && "No support for multi-reg return values!");
1399 assert(VA.isRegLoc() && "Can only return in registers!");
1401 MVT DestVT = VA.getValVT();
1402 MVT CopyVT = DestVT;
1404 // Ints smaller than a register still arrive in a full 64-bit
1405 // register, so make sure we recognize this.
1406 if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32)
1409 unsigned SourcePhysReg = VA.getLocReg();
1410 unsigned ResultReg = 0;
1412 if (RetVT == CopyVT) {
1413 const TargetRegisterClass *CpyRC = TLI.getRegClassFor(CopyVT);
1414 ResultReg = createResultReg(CpyRC);
1416 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1417 TII.get(TargetOpcode::COPY), ResultReg)
1418 .addReg(SourcePhysReg);
1420 // If necessary, round the floating result to single precision.
1421 } else if (CopyVT == MVT::f64) {
1422 ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1423 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::FRSP),
1424 ResultReg).addReg(SourcePhysReg);
1426 // If only the low half of a general register is needed, generate
1427 // a GPRC copy instead of a G8RC copy. (EXTRACT_SUBREG can't be
1428 // used along the fast-isel path (not lowered), and downstream logic
1429 // also doesn't like a direct subreg copy on a physical reg.)
1430 } else if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32) {
1431 ResultReg = createResultReg(&PPC::GPRCRegClass);
1432 // Convert physical register from G8RC to GPRC.
1433 SourcePhysReg -= PPC::X0 - PPC::R0;
1434 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1435 TII.get(TargetOpcode::COPY), ResultReg)
1436 .addReg(SourcePhysReg);
1439 assert(ResultReg && "ResultReg unset!");
1440 CLI.InRegs.push_back(SourcePhysReg);
1441 CLI.ResultReg = ResultReg;
1442 CLI.NumResultRegs = 1;
1448 bool PPCFastISel::fastLowerCall(CallLoweringInfo &CLI) {
1449 CallingConv::ID CC = CLI.CallConv;
1450 bool IsTailCall = CLI.IsTailCall;
1451 bool IsVarArg = CLI.IsVarArg;
1452 const Value *Callee = CLI.Callee;
1453 const MCSymbol *Symbol = CLI.Symbol;
1455 if (!Callee && !Symbol)
1458 // Allow SelectionDAG isel to handle tail calls.
1462 // Let SDISel handle vararg functions.
1466 // Handle simple calls for now, with legal return types and
1467 // those that can be extended.
1468 Type *RetTy = CLI.RetTy;
1470 if (RetTy->isVoidTy())
1471 RetVT = MVT::isVoid;
1472 else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
1475 else if (RetVT == MVT::i1 && PPCSubTarget->useCRBits())
1476 // We can't handle boolean returns when CR bits are in use.
1479 // FIXME: No multi-register return values yet.
1480 if (RetVT != MVT::isVoid && RetVT != MVT::i8 && RetVT != MVT::i16 &&
1481 RetVT != MVT::i32 && RetVT != MVT::i64 && RetVT != MVT::f32 &&
1482 RetVT != MVT::f64) {
1483 SmallVector<CCValAssign, 16> RVLocs;
1484 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs, *Context);
1485 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1486 if (RVLocs.size() > 1)
1490 // Bail early if more than 8 arguments, as we only currently
1491 // handle arguments passed in registers.
1492 unsigned NumArgs = CLI.OutVals.size();
1496 // Set up the argument vectors.
1497 SmallVector<Value*, 8> Args;
1498 SmallVector<unsigned, 8> ArgRegs;
1499 SmallVector<MVT, 8> ArgVTs;
1500 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1502 Args.reserve(NumArgs);
1503 ArgRegs.reserve(NumArgs);
1504 ArgVTs.reserve(NumArgs);
1505 ArgFlags.reserve(NumArgs);
1507 for (unsigned i = 0, ie = NumArgs; i != ie; ++i) {
1508 // Only handle easy calls for now. It would be reasonably easy
1509 // to handle <= 8-byte structures passed ByVal in registers, but we
1510 // have to ensure they are right-justified in the register.
1511 ISD::ArgFlagsTy Flags = CLI.OutFlags[i];
1512 if (Flags.isInReg() || Flags.isSRet() || Flags.isNest() || Flags.isByVal())
1515 Value *ArgValue = CLI.OutVals[i];
1516 Type *ArgTy = ArgValue->getType();
1518 if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8)
1521 if (ArgVT.isVector())
1524 unsigned Arg = getRegForValue(ArgValue);
1528 Args.push_back(ArgValue);
1529 ArgRegs.push_back(Arg);
1530 ArgVTs.push_back(ArgVT);
1531 ArgFlags.push_back(Flags);
1534 // Process the arguments.
1535 SmallVector<unsigned, 8> RegArgs;
1538 if (!processCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
1539 RegArgs, CC, NumBytes, IsVarArg))
1542 MachineInstrBuilder MIB;
1543 // FIXME: No handling for function pointers yet. This requires
1544 // implementing the function descriptor (OPD) setup.
1545 const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1547 // patchpoints are a special case; they always dispatch to a pointer value.
1548 // However, we don't actually want to generate the indirect call sequence
1549 // here (that will be generated, as necessary, during asm printing), and
1550 // the call we generate here will be erased by FastISel::selectPatchpoint,
1551 // so don't try very hard...
1552 if (CLI.IsPatchPoint)
1553 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::NOP));
1557 // Build direct call with NOP for TOC restore.
1558 // FIXME: We can and should optimize away the NOP for local calls.
1559 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1560 TII.get(PPC::BL8_NOP));
1562 MIB.addGlobalAddress(GV);
1565 // Add implicit physical register uses to the call.
1566 for (unsigned II = 0, IE = RegArgs.size(); II != IE; ++II)
1567 MIB.addReg(RegArgs[II], RegState::Implicit);
1569 // Direct calls, in both the ELF V1 and V2 ABIs, need the TOC register live
1571 PPCFuncInfo->setUsesTOCBasePtr();
1572 MIB.addReg(PPC::X2, RegState::Implicit);
1574 // Add a register mask with the call-preserved registers. Proper
1575 // defs for return values will be added by setPhysRegsDeadExcept().
1576 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
1580 // Finish off the call including any return values.
1581 return finishCall(RetVT, CLI, NumBytes);
1584 // Attempt to fast-select a return instruction.
1585 bool PPCFastISel::SelectRet(const Instruction *I) {
1587 if (!FuncInfo.CanLowerReturn)
1590 const ReturnInst *Ret = cast<ReturnInst>(I);
1591 const Function &F = *I->getParent()->getParent();
1593 // Build a list of return value registers.
1594 SmallVector<unsigned, 4> RetRegs;
1595 CallingConv::ID CC = F.getCallingConv();
1597 if (Ret->getNumOperands() > 0) {
1598 SmallVector<ISD::OutputArg, 4> Outs;
1599 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
1601 // Analyze operands of the call, assigning locations to each operand.
1602 SmallVector<CCValAssign, 16> ValLocs;
1603 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, *Context);
1604 CCInfo.AnalyzeReturn(Outs, RetCC_PPC64_ELF_FIS);
1605 const Value *RV = Ret->getOperand(0);
1607 // FIXME: Only one output register for now.
1608 if (ValLocs.size() > 1)
1611 // Special case for returning a constant integer of any size - materialize
1612 // the constant as an i64 and copy it to the return register.
1613 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RV)) {
1614 CCValAssign &VA = ValLocs[0];
1616 unsigned RetReg = VA.getLocReg();
1617 // We still need to worry about properly extending the sign. For example,
1618 // we could have only a single bit or a constant that needs zero
1619 // extension rather than sign extension. Make sure we pass the return
1620 // value extension property to integer materialization.
1622 PPCMaterializeInt(CI, MVT::i64, VA.getLocInfo() == CCValAssign::SExt);
1624 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1625 TII.get(TargetOpcode::COPY), RetReg).addReg(SrcReg);
1627 RetRegs.push_back(RetReg);
1630 unsigned Reg = getRegForValue(RV);
1635 // Copy the result values into the output registers.
1636 for (unsigned i = 0; i < ValLocs.size(); ++i) {
1638 CCValAssign &VA = ValLocs[i];
1639 assert(VA.isRegLoc() && "Can only return in registers!");
1640 RetRegs.push_back(VA.getLocReg());
1641 unsigned SrcReg = Reg + VA.getValNo();
1643 EVT RVEVT = TLI.getValueType(DL, RV->getType());
1644 if (!RVEVT.isSimple())
1646 MVT RVVT = RVEVT.getSimpleVT();
1647 MVT DestVT = VA.getLocVT();
1649 if (RVVT != DestVT && RVVT != MVT::i8 &&
1650 RVVT != MVT::i16 && RVVT != MVT::i32)
1653 if (RVVT != DestVT) {
1654 switch (VA.getLocInfo()) {
1656 llvm_unreachable("Unknown loc info!");
1657 case CCValAssign::Full:
1658 llvm_unreachable("Full value assign but types don't match?");
1659 case CCValAssign::AExt:
1660 case CCValAssign::ZExt: {
1661 const TargetRegisterClass *RC =
1662 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1663 unsigned TmpReg = createResultReg(RC);
1664 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, true))
1669 case CCValAssign::SExt: {
1670 const TargetRegisterClass *RC =
1671 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1672 unsigned TmpReg = createResultReg(RC);
1673 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, false))
1681 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1682 TII.get(TargetOpcode::COPY), RetRegs[i])
1688 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1689 TII.get(PPC::BLR8));
1691 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1692 MIB.addReg(RetRegs[i], RegState::Implicit);
1697 // Attempt to emit an integer extend of SrcReg into DestReg. Both
1698 // signed and zero extensions are supported. Return false if we
1700 bool PPCFastISel::PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1701 unsigned DestReg, bool IsZExt) {
1702 if (DestVT != MVT::i32 && DestVT != MVT::i64)
1704 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 && SrcVT != MVT::i32)
1707 // Signed extensions use EXTSB, EXTSH, EXTSW.
1710 if (SrcVT == MVT::i8)
1711 Opc = (DestVT == MVT::i32) ? PPC::EXTSB : PPC::EXTSB8_32_64;
1712 else if (SrcVT == MVT::i16)
1713 Opc = (DestVT == MVT::i32) ? PPC::EXTSH : PPC::EXTSH8_32_64;
1715 assert(DestVT == MVT::i64 && "Signed extend from i32 to i32??");
1716 Opc = PPC::EXTSW_32_64;
1718 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1721 // Unsigned 32-bit extensions use RLWINM.
1722 } else if (DestVT == MVT::i32) {
1724 if (SrcVT == MVT::i8)
1727 assert(SrcVT == MVT::i16 && "Unsigned extend from i32 to i32??");
1730 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::RLWINM),
1732 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB).addImm(/*ME=*/31);
1734 // Unsigned 64-bit extensions use RLDICL (with a 32-bit source).
1737 if (SrcVT == MVT::i8)
1739 else if (SrcVT == MVT::i16)
1743 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1744 TII.get(PPC::RLDICL_32_64), DestReg)
1745 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB);
1751 // Attempt to fast-select an indirect branch instruction.
1752 bool PPCFastISel::SelectIndirectBr(const Instruction *I) {
1753 unsigned AddrReg = getRegForValue(I->getOperand(0));
1757 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::MTCTR8))
1759 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::BCTR8));
1761 const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1762 for (const BasicBlock *SuccBB : IB->successors())
1763 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[SuccBB]);
1768 // Attempt to fast-select an integer truncate instruction.
1769 bool PPCFastISel::SelectTrunc(const Instruction *I) {
1770 Value *Src = I->getOperand(0);
1771 EVT SrcVT = TLI.getValueType(DL, Src->getType(), true);
1772 EVT DestVT = TLI.getValueType(DL, I->getType(), true);
1774 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16)
1777 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8)
1780 unsigned SrcReg = getRegForValue(Src);
1784 // The only interesting case is when we need to switch register classes.
1785 if (SrcVT == MVT::i64) {
1786 unsigned ResultReg = createResultReg(&PPC::GPRCRegClass);
1787 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1788 TII.get(TargetOpcode::COPY),
1789 ResultReg).addReg(SrcReg, 0, PPC::sub_32);
1793 updateValueMap(I, SrcReg);
1797 // Attempt to fast-select an integer extend instruction.
1798 bool PPCFastISel::SelectIntExt(const Instruction *I) {
1799 Type *DestTy = I->getType();
1800 Value *Src = I->getOperand(0);
1801 Type *SrcTy = Src->getType();
1803 bool IsZExt = isa<ZExtInst>(I);
1804 unsigned SrcReg = getRegForValue(Src);
1805 if (!SrcReg) return false;
1807 EVT SrcEVT, DestEVT;
1808 SrcEVT = TLI.getValueType(DL, SrcTy, true);
1809 DestEVT = TLI.getValueType(DL, DestTy, true);
1810 if (!SrcEVT.isSimple())
1812 if (!DestEVT.isSimple())
1815 MVT SrcVT = SrcEVT.getSimpleVT();
1816 MVT DestVT = DestEVT.getSimpleVT();
1818 // If we know the register class needed for the result of this
1819 // instruction, use it. Otherwise pick the register class of the
1820 // correct size that does not contain X0/R0, since we don't know
1821 // whether downstream uses permit that assignment.
1822 unsigned AssignedReg = FuncInfo.ValueMap[I];
1823 const TargetRegisterClass *RC =
1824 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1825 (DestVT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
1826 &PPC::GPRC_and_GPRC_NOR0RegClass));
1827 unsigned ResultReg = createResultReg(RC);
1829 if (!PPCEmitIntExt(SrcVT, SrcReg, DestVT, ResultReg, IsZExt))
1832 updateValueMap(I, ResultReg);
1836 // Attempt to fast-select an instruction that wasn't handled by
1837 // the table-generated machinery.
1838 bool PPCFastISel::fastSelectInstruction(const Instruction *I) {
1840 switch (I->getOpcode()) {
1841 case Instruction::Load:
1842 return SelectLoad(I);
1843 case Instruction::Store:
1844 return SelectStore(I);
1845 case Instruction::Br:
1846 return SelectBranch(I);
1847 case Instruction::IndirectBr:
1848 return SelectIndirectBr(I);
1849 case Instruction::FPExt:
1850 return SelectFPExt(I);
1851 case Instruction::FPTrunc:
1852 return SelectFPTrunc(I);
1853 case Instruction::SIToFP:
1854 return SelectIToFP(I, /*IsSigned*/ true);
1855 case Instruction::UIToFP:
1856 return SelectIToFP(I, /*IsSigned*/ false);
1857 case Instruction::FPToSI:
1858 return SelectFPToI(I, /*IsSigned*/ true);
1859 case Instruction::FPToUI:
1860 return SelectFPToI(I, /*IsSigned*/ false);
1861 case Instruction::Add:
1862 return SelectBinaryIntOp(I, ISD::ADD);
1863 case Instruction::Or:
1864 return SelectBinaryIntOp(I, ISD::OR);
1865 case Instruction::Sub:
1866 return SelectBinaryIntOp(I, ISD::SUB);
1867 case Instruction::Call:
1868 return selectCall(I);
1869 case Instruction::Ret:
1870 return SelectRet(I);
1871 case Instruction::Trunc:
1872 return SelectTrunc(I);
1873 case Instruction::ZExt:
1874 case Instruction::SExt:
1875 return SelectIntExt(I);
1876 // Here add other flavors of Instruction::XXX that automated
1877 // cases don't catch. For example, switches are terminators
1878 // that aren't yet handled.
1885 // Materialize a floating-point constant into a register, and return
1886 // the register number (or zero if we failed to handle it).
1887 unsigned PPCFastISel::PPCMaterializeFP(const ConstantFP *CFP, MVT VT) {
1888 // No plans to handle long double here.
1889 if (VT != MVT::f32 && VT != MVT::f64)
1892 // All FP constants are loaded from the constant pool.
1893 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
1894 assert(Align > 0 && "Unexpectedly missing alignment information!");
1895 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
1896 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
1897 CodeModel::Model CModel = TM.getCodeModel();
1899 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
1900 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
1901 MachineMemOperand::MOLoad, (VT == MVT::f32) ? 4 : 8, Align);
1903 unsigned Opc = (VT == MVT::f32) ? PPC::LFS : PPC::LFD;
1904 unsigned TmpReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1906 PPCFuncInfo->setUsesTOCBasePtr();
1907 // For small code model, generate a LF[SD](0, LDtocCPT(Idx, X2)).
1908 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault) {
1909 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocCPT),
1911 .addConstantPoolIndex(Idx).addReg(PPC::X2);
1912 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1913 .addImm(0).addReg(TmpReg).addMemOperand(MMO);
1915 // Otherwise we generate LF[SD](Idx[lo], ADDIStocHA(X2, Idx)).
1916 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDIStocHA),
1917 TmpReg).addReg(PPC::X2).addConstantPoolIndex(Idx);
1918 // But for large code model, we must generate a LDtocL followed
1920 if (CModel == CodeModel::Large) {
1921 unsigned TmpReg2 = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1922 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocL),
1923 TmpReg2).addConstantPoolIndex(Idx).addReg(TmpReg);
1924 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1925 .addImm(0).addReg(TmpReg2);
1927 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1928 .addConstantPoolIndex(Idx, 0, PPCII::MO_TOC_LO)
1930 .addMemOperand(MMO);
1936 // Materialize the address of a global value into a register, and return
1937 // the register number (or zero if we failed to handle it).
1938 unsigned PPCFastISel::PPCMaterializeGV(const GlobalValue *GV, MVT VT) {
1939 assert(VT == MVT::i64 && "Non-address!");
1940 const TargetRegisterClass *RC = &PPC::G8RC_and_G8RC_NOX0RegClass;
1941 unsigned DestReg = createResultReg(RC);
1943 // Global values may be plain old object addresses, TLS object
1944 // addresses, constant pool entries, or jump tables. How we generate
1945 // code for these may depend on small, medium, or large code model.
1946 CodeModel::Model CModel = TM.getCodeModel();
1948 // FIXME: Jump tables are not yet required because fast-isel doesn't
1949 // handle switches; if that changes, we need them as well. For now,
1950 // what follows assumes everything's a generic (or TLS) global address.
1952 // FIXME: We don't yet handle the complexity of TLS.
1953 if (GV->isThreadLocal())
1956 PPCFuncInfo->setUsesTOCBasePtr();
1957 // For small code model, generate a simple TOC load.
1958 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault)
1959 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtoc),
1961 .addGlobalAddress(GV)
1964 // If the address is an externally defined symbol, a symbol with common
1965 // or externally available linkage, a non-local function address, or a
1966 // jump table address (not yet needed), or if we are generating code
1967 // for large code model, we generate:
1968 // LDtocL(GV, ADDIStocHA(%X2, GV))
1969 // Otherwise we generate:
1970 // ADDItocL(ADDIStocHA(%X2, GV), GV)
1971 // Either way, start with the ADDIStocHA:
1972 unsigned HighPartReg = createResultReg(RC);
1973 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDIStocHA),
1974 HighPartReg).addReg(PPC::X2).addGlobalAddress(GV);
1976 // If/when switches are implemented, jump tables should be handled
1977 // on the "if" path here.
1978 if (CModel == CodeModel::Large ||
1979 (GV->getType()->getElementType()->isFunctionTy() &&
1980 !GV->isStrongDefinitionForLinker()) ||
1981 GV->isDeclaration() || GV->hasCommonLinkage() ||
1982 GV->hasAvailableExternallyLinkage())
1983 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocL),
1984 DestReg).addGlobalAddress(GV).addReg(HighPartReg);
1986 // Otherwise generate the ADDItocL.
1987 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDItocL),
1988 DestReg).addReg(HighPartReg).addGlobalAddress(GV);
1994 // Materialize a 32-bit integer constant into a register, and return
1995 // the register number (or zero if we failed to handle it).
1996 unsigned PPCFastISel::PPCMaterialize32BitInt(int64_t Imm,
1997 const TargetRegisterClass *RC) {
1998 unsigned Lo = Imm & 0xFFFF;
1999 unsigned Hi = (Imm >> 16) & 0xFFFF;
2001 unsigned ResultReg = createResultReg(RC);
2002 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
2005 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2006 TII.get(IsGPRC ? PPC::LI : PPC::LI8), ResultReg)
2009 // Both Lo and Hi have nonzero bits.
2010 unsigned TmpReg = createResultReg(RC);
2011 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2012 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), TmpReg)
2014 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2015 TII.get(IsGPRC ? PPC::ORI : PPC::ORI8), ResultReg)
2016 .addReg(TmpReg).addImm(Lo);
2019 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2020 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), ResultReg)
2026 // Materialize a 64-bit integer constant into a register, and return
2027 // the register number (or zero if we failed to handle it).
2028 unsigned PPCFastISel::PPCMaterialize64BitInt(int64_t Imm,
2029 const TargetRegisterClass *RC) {
2030 unsigned Remainder = 0;
2033 // If the value doesn't fit in 32 bits, see if we can shift it
2034 // so that it fits in 32 bits.
2035 if (!isInt<32>(Imm)) {
2036 Shift = countTrailingZeros<uint64_t>(Imm);
2037 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
2039 if (isInt<32>(ImmSh))
2048 // Handle the high-order 32 bits (if shifted) or the whole 32 bits
2049 // (if not shifted).
2050 unsigned TmpReg1 = PPCMaterialize32BitInt(Imm, RC);
2054 // If upper 32 bits were not zero, we've built them and need to shift
2058 TmpReg2 = createResultReg(RC);
2059 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::RLDICR),
2060 TmpReg2).addReg(TmpReg1).addImm(Shift).addImm(63 - Shift);
2064 unsigned TmpReg3, Hi, Lo;
2065 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
2066 TmpReg3 = createResultReg(RC);
2067 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ORIS8),
2068 TmpReg3).addReg(TmpReg2).addImm(Hi);
2072 if ((Lo = Remainder & 0xFFFF)) {
2073 unsigned ResultReg = createResultReg(RC);
2074 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ORI8),
2075 ResultReg).addReg(TmpReg3).addImm(Lo);
2083 // Materialize an integer constant into a register, and return
2084 // the register number (or zero if we failed to handle it).
2085 unsigned PPCFastISel::PPCMaterializeInt(const ConstantInt *CI, MVT VT,
2087 // If we're using CR bit registers for i1 values, handle that as a special
2089 if (VT == MVT::i1 && PPCSubTarget->useCRBits()) {
2090 unsigned ImmReg = createResultReg(&PPC::CRBITRCRegClass);
2091 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2092 TII.get(CI->isZero() ? PPC::CRUNSET : PPC::CRSET), ImmReg);
2096 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2097 VT != MVT::i8 && VT != MVT::i1)
2100 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2101 &PPC::GPRCRegClass);
2103 // If the constant is in range, use a load-immediate.
2104 if (UseSExt && isInt<16>(CI->getSExtValue())) {
2105 unsigned Opc = (VT == MVT::i64) ? PPC::LI8 : PPC::LI;
2106 unsigned ImmReg = createResultReg(RC);
2107 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ImmReg)
2108 .addImm(CI->getSExtValue());
2110 } else if (!UseSExt && isUInt<16>(CI->getZExtValue())) {
2111 unsigned Opc = (VT == MVT::i64) ? PPC::LI8 : PPC::LI;
2112 unsigned ImmReg = createResultReg(RC);
2113 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ImmReg)
2114 .addImm(CI->getZExtValue());
2118 // Construct the constant piecewise.
2119 int64_t Imm = CI->getZExtValue();
2122 return PPCMaterialize64BitInt(Imm, RC);
2123 else if (VT == MVT::i32)
2124 return PPCMaterialize32BitInt(Imm, RC);
2129 // Materialize a constant into a register, and return the register
2130 // number (or zero if we failed to handle it).
2131 unsigned PPCFastISel::fastMaterializeConstant(const Constant *C) {
2132 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
2134 // Only handle simple types.
2135 if (!CEVT.isSimple()) return 0;
2136 MVT VT = CEVT.getSimpleVT();
2138 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
2139 return PPCMaterializeFP(CFP, VT);
2140 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
2141 return PPCMaterializeGV(GV, VT);
2142 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
2143 return PPCMaterializeInt(CI, VT, VT != MVT::i1);
2148 // Materialize the address created by an alloca into a register, and
2149 // return the register number (or zero if we failed to handle it).
2150 unsigned PPCFastISel::fastMaterializeAlloca(const AllocaInst *AI) {
2151 // Don't handle dynamic allocas.
2152 if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
2155 if (!isLoadTypeLegal(AI->getType(), VT)) return 0;
2157 DenseMap<const AllocaInst*, int>::iterator SI =
2158 FuncInfo.StaticAllocaMap.find(AI);
2160 if (SI != FuncInfo.StaticAllocaMap.end()) {
2161 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
2162 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDI8),
2163 ResultReg).addFrameIndex(SI->second).addImm(0);
2170 // Fold loads into extends when possible.
2171 // FIXME: We can have multiple redundant extend/trunc instructions
2172 // following a load. The folding only picks up one. Extend this
2173 // to check subsequent instructions for the same pattern and remove
2174 // them. Thus ResultReg should be the def reg for the last redundant
2175 // instruction in a chain, and all intervening instructions can be
2176 // removed from parent. Change test/CodeGen/PowerPC/fast-isel-fold.ll
2177 // to add ELF64-NOT: rldicl to the appropriate tests when this works.
2178 bool PPCFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2179 const LoadInst *LI) {
2180 // Verify we have a legal type before going any further.
2182 if (!isLoadTypeLegal(LI->getType(), VT))
2185 // Combine load followed by zero- or sign-extend.
2186 bool IsZExt = false;
2187 switch(MI->getOpcode()) {
2192 case PPC::RLDICL_32_64: {
2194 unsigned MB = MI->getOperand(3).getImm();
2195 if ((VT == MVT::i8 && MB <= 56) ||
2196 (VT == MVT::i16 && MB <= 48) ||
2197 (VT == MVT::i32 && MB <= 32))
2203 case PPC::RLWINM8: {
2205 unsigned MB = MI->getOperand(3).getImm();
2206 if ((VT == MVT::i8 && MB <= 24) ||
2207 (VT == MVT::i16 && MB <= 16))
2214 case PPC::EXTSB8_32_64:
2215 /* There is no sign-extending load-byte instruction. */
2220 case PPC::EXTSH8_32_64: {
2221 if (VT != MVT::i16 && VT != MVT::i8)
2227 case PPC::EXTSW_32_64: {
2228 if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8)
2234 // See if we can handle this address.
2236 if (!PPCComputeAddress(LI->getOperand(0), Addr))
2239 unsigned ResultReg = MI->getOperand(0).getReg();
2241 if (!PPCEmitLoad(VT, ResultReg, Addr, nullptr, IsZExt))
2244 MI->eraseFromParent();
2248 // Attempt to lower call arguments in a faster way than done by
2249 // the selection DAG code.
2250 bool PPCFastISel::fastLowerArguments() {
2251 // Defer to normal argument lowering for now. It's reasonably
2252 // efficient. Consider doing something like ARM to handle the
2253 // case where all args fit in registers, no varargs, no float
2258 // Handle materializing integer constants into a register. This is not
2259 // automatically generated for PowerPC, so must be explicitly created here.
2260 unsigned PPCFastISel::fastEmit_i(MVT Ty, MVT VT, unsigned Opc, uint64_t Imm) {
2262 if (Opc != ISD::Constant)
2265 // If we're using CR bit registers for i1 values, handle that as a special
2267 if (VT == MVT::i1 && PPCSubTarget->useCRBits()) {
2268 unsigned ImmReg = createResultReg(&PPC::CRBITRCRegClass);
2269 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2270 TII.get(Imm == 0 ? PPC::CRUNSET : PPC::CRSET), ImmReg);
2274 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2275 VT != MVT::i8 && VT != MVT::i1)
2278 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2279 &PPC::GPRCRegClass);
2281 return PPCMaterialize64BitInt(Imm, RC);
2283 return PPCMaterialize32BitInt(Imm, RC);
2286 // Override for ADDI and ADDI8 to set the correct register class
2287 // on RHS operand 0. The automatic infrastructure naively assumes
2288 // GPRC for i32 and G8RC for i64; the concept of "no R0" is lost
2289 // for these cases. At the moment, none of the other automatically
2290 // generated RI instructions require special treatment. However, once
2291 // SelectSelect is implemented, "isel" requires similar handling.
2293 // Also be conservative about the output register class. Avoid
2294 // assigning R0 or X0 to the output register for GPRC and G8RC
2295 // register classes, as any such result could be used in ADDI, etc.,
2296 // where those regs have another meaning.
2297 unsigned PPCFastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
2298 const TargetRegisterClass *RC,
2299 unsigned Op0, bool Op0IsKill,
2301 if (MachineInstOpcode == PPC::ADDI)
2302 MRI.setRegClass(Op0, &PPC::GPRC_and_GPRC_NOR0RegClass);
2303 else if (MachineInstOpcode == PPC::ADDI8)
2304 MRI.setRegClass(Op0, &PPC::G8RC_and_G8RC_NOX0RegClass);
2306 const TargetRegisterClass *UseRC =
2307 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2308 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2310 return FastISel::fastEmitInst_ri(MachineInstOpcode, UseRC,
2311 Op0, Op0IsKill, Imm);
2314 // Override for instructions with one register operand to avoid use of
2315 // R0/X0. The automatic infrastructure isn't aware of the context so
2316 // we must be conservative.
2317 unsigned PPCFastISel::fastEmitInst_r(unsigned MachineInstOpcode,
2318 const TargetRegisterClass* RC,
2319 unsigned Op0, bool Op0IsKill) {
2320 const TargetRegisterClass *UseRC =
2321 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2322 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2324 return FastISel::fastEmitInst_r(MachineInstOpcode, UseRC, Op0, Op0IsKill);
2327 // Override for instructions with two register operands to avoid use
2328 // of R0/X0. The automatic infrastructure isn't aware of the context
2329 // so we must be conservative.
2330 unsigned PPCFastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
2331 const TargetRegisterClass* RC,
2332 unsigned Op0, bool Op0IsKill,
2333 unsigned Op1, bool Op1IsKill) {
2334 const TargetRegisterClass *UseRC =
2335 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2336 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2338 return FastISel::fastEmitInst_rr(MachineInstOpcode, UseRC, Op0, Op0IsKill,
2343 // Create the fast instruction selector for PowerPC64 ELF.
2344 FastISel *PPC::createFastISel(FunctionLoweringInfo &FuncInfo,
2345 const TargetLibraryInfo *LibInfo) {
2346 // Only available on 64-bit ELF for now.
2347 const PPCSubtarget &Subtarget = FuncInfo.MF->getSubtarget<PPCSubtarget>();
2348 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI())
2349 return new PPCFastISel(FuncInfo, LibInfo);