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 PPCEmitCmp(const Value *Src1Value, const Value *Src2Value,
152 bool isZExt, unsigned DestReg);
153 bool PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
154 const TargetRegisterClass *RC, bool IsZExt = true,
155 unsigned FP64LoadOpc = PPC::LFD);
156 bool PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr);
157 bool PPCComputeAddress(const Value *Obj, Address &Addr);
158 void PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
160 bool PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
161 unsigned DestReg, bool IsZExt);
162 unsigned PPCMaterializeFP(const ConstantFP *CFP, MVT VT);
163 unsigned PPCMaterializeGV(const GlobalValue *GV, MVT VT);
164 unsigned PPCMaterializeInt(const Constant *C, MVT VT, bool UseSExt = true);
165 unsigned PPCMaterialize32BitInt(int64_t Imm,
166 const TargetRegisterClass *RC);
167 unsigned PPCMaterialize64BitInt(int64_t Imm,
168 const TargetRegisterClass *RC);
169 unsigned PPCMoveToIntReg(const Instruction *I, MVT VT,
170 unsigned SrcReg, bool IsSigned);
171 unsigned PPCMoveToFPReg(MVT VT, unsigned SrcReg, bool IsSigned);
173 // Call handling routines.
175 bool processCallArgs(SmallVectorImpl<Value*> &Args,
176 SmallVectorImpl<unsigned> &ArgRegs,
177 SmallVectorImpl<MVT> &ArgVTs,
178 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
179 SmallVectorImpl<unsigned> &RegArgs,
183 bool finishCall(MVT RetVT, CallLoweringInfo &CLI, unsigned &NumBytes);
184 CCAssignFn *usePPC32CCs(unsigned Flag);
187 #include "PPCGenFastISel.inc"
191 } // end anonymous namespace
193 #include "PPCGenCallingConv.inc"
195 // Function whose sole purpose is to kill compiler warnings
196 // stemming from unused functions included from PPCGenCallingConv.inc.
197 CCAssignFn *PPCFastISel::usePPC32CCs(unsigned Flag) {
199 return CC_PPC32_SVR4;
201 return CC_PPC32_SVR4_ByVal;
203 return CC_PPC32_SVR4_VarArg;
208 static Optional<PPC::Predicate> getComparePred(CmpInst::Predicate Pred) {
210 // These are not representable with any single compare.
211 case CmpInst::FCMP_FALSE:
212 case CmpInst::FCMP_UEQ:
213 case CmpInst::FCMP_UGT:
214 case CmpInst::FCMP_UGE:
215 case CmpInst::FCMP_ULT:
216 case CmpInst::FCMP_ULE:
217 case CmpInst::FCMP_UNE:
218 case CmpInst::FCMP_TRUE:
220 return Optional<PPC::Predicate>();
222 case CmpInst::FCMP_OEQ:
223 case CmpInst::ICMP_EQ:
226 case CmpInst::FCMP_OGT:
227 case CmpInst::ICMP_UGT:
228 case CmpInst::ICMP_SGT:
231 case CmpInst::FCMP_OGE:
232 case CmpInst::ICMP_UGE:
233 case CmpInst::ICMP_SGE:
236 case CmpInst::FCMP_OLT:
237 case CmpInst::ICMP_ULT:
238 case CmpInst::ICMP_SLT:
241 case CmpInst::FCMP_OLE:
242 case CmpInst::ICMP_ULE:
243 case CmpInst::ICMP_SLE:
246 case CmpInst::FCMP_ONE:
247 case CmpInst::ICMP_NE:
250 case CmpInst::FCMP_ORD:
253 case CmpInst::FCMP_UNO:
258 // Determine whether the type Ty is simple enough to be handled by
259 // fast-isel, and return its equivalent machine type in VT.
260 // FIXME: Copied directly from ARM -- factor into base class?
261 bool PPCFastISel::isTypeLegal(Type *Ty, MVT &VT) {
262 EVT Evt = TLI.getValueType(Ty, true);
264 // Only handle simple types.
265 if (Evt == MVT::Other || !Evt.isSimple()) return false;
266 VT = Evt.getSimpleVT();
268 // Handle all legal types, i.e. a register that will directly hold this
270 return TLI.isTypeLegal(VT);
273 // Determine whether the type Ty is simple enough to be handled by
274 // fast-isel as a load target, and return its equivalent machine type in VT.
275 bool PPCFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
276 if (isTypeLegal(Ty, VT)) return true;
278 // If this is a type than can be sign or zero-extended to a basic operation
279 // go ahead and accept it now.
280 if (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) {
287 bool PPCFastISel::isValueAvailable(const Value *V) const {
288 if (!isa<Instruction>(V))
291 const auto *I = cast<Instruction>(V);
292 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
298 // Given a value Obj, create an Address object Addr that represents its
299 // address. Return false if we can't handle it.
300 bool PPCFastISel::PPCComputeAddress(const Value *Obj, Address &Addr) {
301 const User *U = nullptr;
302 unsigned Opcode = Instruction::UserOp1;
303 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
304 // Don't walk into other basic blocks unless the object is an alloca from
305 // another block, otherwise it may not have a virtual register assigned.
306 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
307 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
308 Opcode = I->getOpcode();
311 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
312 Opcode = C->getOpcode();
319 case Instruction::BitCast:
320 // Look through bitcasts.
321 return PPCComputeAddress(U->getOperand(0), Addr);
322 case Instruction::IntToPtr:
323 // Look past no-op inttoptrs.
324 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
325 return PPCComputeAddress(U->getOperand(0), Addr);
327 case Instruction::PtrToInt:
328 // Look past no-op ptrtoints.
329 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
330 return PPCComputeAddress(U->getOperand(0), Addr);
332 case Instruction::GetElementPtr: {
333 Address SavedAddr = Addr;
334 long TmpOffset = Addr.Offset;
336 // Iterate through the GEP folding the constants into offsets where
338 gep_type_iterator GTI = gep_type_begin(U);
339 for (User::const_op_iterator II = U->op_begin() + 1, IE = U->op_end();
340 II != IE; ++II, ++GTI) {
341 const Value *Op = *II;
342 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
343 const StructLayout *SL = DL.getStructLayout(STy);
344 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
345 TmpOffset += SL->getElementOffset(Idx);
347 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
349 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
350 // Constant-offset addressing.
351 TmpOffset += CI->getSExtValue() * S;
354 if (canFoldAddIntoGEP(U, Op)) {
355 // A compatible add with a constant operand. Fold the constant.
357 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
358 TmpOffset += CI->getSExtValue() * S;
359 // Iterate on the other operand.
360 Op = cast<AddOperator>(Op)->getOperand(0);
364 goto unsupported_gep;
369 // Try to grab the base operand now.
370 Addr.Offset = TmpOffset;
371 if (PPCComputeAddress(U->getOperand(0), Addr)) return true;
373 // We failed, restore everything and try the other options.
379 case Instruction::Alloca: {
380 const AllocaInst *AI = cast<AllocaInst>(Obj);
381 DenseMap<const AllocaInst*, int>::iterator SI =
382 FuncInfo.StaticAllocaMap.find(AI);
383 if (SI != FuncInfo.StaticAllocaMap.end()) {
384 Addr.BaseType = Address::FrameIndexBase;
385 Addr.Base.FI = SI->second;
392 // FIXME: References to parameters fall through to the behavior
393 // below. They should be able to reference a frame index since
394 // they are stored to the stack, so we can get "ld rx, offset(r1)"
395 // instead of "addi ry, r1, offset / ld rx, 0(ry)". Obj will
396 // just contain the parameter. Try to handle this with a FI.
398 // Try to get this in a register if nothing else has worked.
399 if (Addr.Base.Reg == 0)
400 Addr.Base.Reg = getRegForValue(Obj);
402 // Prevent assignment of base register to X0, which is inappropriate
403 // for loads and stores alike.
404 if (Addr.Base.Reg != 0)
405 MRI.setRegClass(Addr.Base.Reg, &PPC::G8RC_and_G8RC_NOX0RegClass);
407 return Addr.Base.Reg != 0;
410 // Fix up some addresses that can't be used directly. For example, if
411 // an offset won't fit in an instruction field, we may need to move it
412 // into an index register.
413 void PPCFastISel::PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
414 unsigned &IndexReg) {
416 // Check whether the offset fits in the instruction field.
417 if (!isInt<16>(Addr.Offset))
420 // If this is a stack pointer and the offset needs to be simplified then
421 // put the alloca address into a register, set the base type back to
422 // register and continue. This should almost never happen.
423 if (!UseOffset && Addr.BaseType == Address::FrameIndexBase) {
424 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
425 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDI8),
426 ResultReg).addFrameIndex(Addr.Base.FI).addImm(0);
427 Addr.Base.Reg = ResultReg;
428 Addr.BaseType = Address::RegBase;
432 IntegerType *OffsetTy = ((VT == MVT::i32) ? Type::getInt32Ty(*Context)
433 : Type::getInt64Ty(*Context));
434 const ConstantInt *Offset =
435 ConstantInt::getSigned(OffsetTy, (int64_t)(Addr.Offset));
436 IndexReg = PPCMaterializeInt(Offset, MVT::i64);
437 assert(IndexReg && "Unexpected error in PPCMaterializeInt!");
441 // Emit a load instruction if possible, returning true if we succeeded,
442 // otherwise false. See commentary below for how the register class of
443 // the load is determined.
444 bool PPCFastISel::PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
445 const TargetRegisterClass *RC,
446 bool IsZExt, unsigned FP64LoadOpc) {
448 bool UseOffset = true;
450 // If ResultReg is given, it determines the register class of the load.
451 // Otherwise, RC is the register class to use. If the result of the
452 // load isn't anticipated in this block, both may be zero, in which
453 // case we must make a conservative guess. In particular, don't assign
454 // R0 or X0 to the result register, as the result may be used in a load,
455 // store, add-immediate, or isel that won't permit this. (Though
456 // perhaps the spill and reload of live-exit values would handle this?)
457 const TargetRegisterClass *UseRC =
458 (ResultReg ? MRI.getRegClass(ResultReg) :
460 (VT == MVT::f64 ? &PPC::F8RCRegClass :
461 (VT == MVT::f32 ? &PPC::F4RCRegClass :
462 (VT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
463 &PPC::GPRC_and_GPRC_NOR0RegClass)))));
465 bool Is32BitInt = UseRC->hasSuperClassEq(&PPC::GPRCRegClass);
467 switch (VT.SimpleTy) {
468 default: // e.g., vector types not handled
471 Opc = Is32BitInt ? PPC::LBZ : PPC::LBZ8;
475 (Is32BitInt ? PPC::LHZ : PPC::LHZ8) :
476 (Is32BitInt ? PPC::LHA : PPC::LHA8));
480 (Is32BitInt ? PPC::LWZ : PPC::LWZ8) :
481 (Is32BitInt ? PPC::LWA_32 : PPC::LWA));
482 if ((Opc == PPC::LWA || Opc == PPC::LWA_32) && ((Addr.Offset & 3) != 0))
487 assert(UseRC->hasSuperClassEq(&PPC::G8RCRegClass) &&
488 "64-bit load with 32-bit target??");
489 UseOffset = ((Addr.Offset & 3) == 0);
499 // If necessary, materialize the offset into a register and use
500 // the indexed form. Also handle stack pointers with special needs.
501 unsigned IndexReg = 0;
502 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
504 // If this is a potential VSX load with an offset of 0, a VSX indexed load can
506 bool IsVSFRC = (ResultReg != 0) && isVSFRCRegister(ResultReg);
507 if (IsVSFRC && (Opc == PPC::LFD) &&
508 (Addr.BaseType != Address::FrameIndexBase) && UseOffset &&
509 (Addr.Offset == 0)) {
514 ResultReg = createResultReg(UseRC);
516 // Note: If we still have a frame index here, we know the offset is
517 // in range, as otherwise PPCSimplifyAddress would have converted it
519 if (Addr.BaseType == Address::FrameIndexBase) {
520 // VSX only provides an indexed load.
521 if (IsVSFRC && Opc == PPC::LFD) return false;
523 MachineMemOperand *MMO =
524 FuncInfo.MF->getMachineMemOperand(
525 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
526 MachineMemOperand::MOLoad, MFI.getObjectSize(Addr.Base.FI),
527 MFI.getObjectAlignment(Addr.Base.FI));
529 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
530 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
532 // Base reg with offset in range.
533 } else if (UseOffset) {
534 // VSX only provides an indexed load.
535 if (IsVSFRC && Opc == PPC::LFD) return false;
537 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
538 .addImm(Addr.Offset).addReg(Addr.Base.Reg);
542 // Get the RR opcode corresponding to the RI one. FIXME: It would be
543 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
544 // is hard to get at.
546 default: llvm_unreachable("Unexpected opcode!");
547 case PPC::LBZ: Opc = PPC::LBZX; break;
548 case PPC::LBZ8: Opc = PPC::LBZX8; break;
549 case PPC::LHZ: Opc = PPC::LHZX; break;
550 case PPC::LHZ8: Opc = PPC::LHZX8; break;
551 case PPC::LHA: Opc = PPC::LHAX; break;
552 case PPC::LHA8: Opc = PPC::LHAX8; break;
553 case PPC::LWZ: Opc = PPC::LWZX; break;
554 case PPC::LWZ8: Opc = PPC::LWZX8; break;
555 case PPC::LWA: Opc = PPC::LWAX; break;
556 case PPC::LWA_32: Opc = PPC::LWAX_32; break;
557 case PPC::LD: Opc = PPC::LDX; break;
558 case PPC::LFS: Opc = PPC::LFSX; break;
559 case PPC::LFD: Opc = IsVSFRC ? PPC::LXSDX : PPC::LFDX; break;
561 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
562 .addReg(Addr.Base.Reg).addReg(IndexReg);
568 // Attempt to fast-select a load instruction.
569 bool PPCFastISel::SelectLoad(const Instruction *I) {
570 // FIXME: No atomic loads are supported.
571 if (cast<LoadInst>(I)->isAtomic())
574 // Verify we have a legal type before going any further.
576 if (!isLoadTypeLegal(I->getType(), VT))
579 // See if we can handle this address.
581 if (!PPCComputeAddress(I->getOperand(0), Addr))
584 // Look at the currently assigned register for this instruction
585 // to determine the required register class. This is necessary
586 // to constrain RA from using R0/X0 when this is not legal.
587 unsigned AssignedReg = FuncInfo.ValueMap[I];
588 const TargetRegisterClass *RC =
589 AssignedReg ? MRI.getRegClass(AssignedReg) : nullptr;
591 unsigned ResultReg = 0;
592 if (!PPCEmitLoad(VT, ResultReg, Addr, RC))
594 updateValueMap(I, ResultReg);
598 // Emit a store instruction to store SrcReg at Addr.
599 bool PPCFastISel::PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr) {
600 assert(SrcReg && "Nothing to store!");
602 bool UseOffset = true;
604 const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
605 bool Is32BitInt = RC->hasSuperClassEq(&PPC::GPRCRegClass);
607 switch (VT.SimpleTy) {
608 default: // e.g., vector types not handled
611 Opc = Is32BitInt ? PPC::STB : PPC::STB8;
614 Opc = Is32BitInt ? PPC::STH : PPC::STH8;
617 assert(Is32BitInt && "Not GPRC for i32??");
622 UseOffset = ((Addr.Offset & 3) == 0);
632 // If necessary, materialize the offset into a register and use
633 // the indexed form. Also handle stack pointers with special needs.
634 unsigned IndexReg = 0;
635 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
637 // If this is a potential VSX store with an offset of 0, a VSX indexed store
639 bool IsVSFRC = isVSFRCRegister(SrcReg);
640 if (IsVSFRC && (Opc == PPC::STFD) &&
641 (Addr.BaseType != Address::FrameIndexBase) && UseOffset &&
642 (Addr.Offset == 0)) {
646 // Note: If we still have a frame index here, we know the offset is
647 // in range, as otherwise PPCSimplifyAddress would have converted it
649 if (Addr.BaseType == Address::FrameIndexBase) {
650 // VSX only provides an indexed store.
651 if (IsVSFRC && Opc == PPC::STFD) return false;
653 MachineMemOperand *MMO =
654 FuncInfo.MF->getMachineMemOperand(
655 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
656 MachineMemOperand::MOStore, MFI.getObjectSize(Addr.Base.FI),
657 MFI.getObjectAlignment(Addr.Base.FI));
659 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
662 .addFrameIndex(Addr.Base.FI)
665 // Base reg with offset in range.
666 } else if (UseOffset) {
667 // VSX only provides an indexed store.
668 if (IsVSFRC && Opc == PPC::STFD) return false;
670 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
671 .addReg(SrcReg).addImm(Addr.Offset).addReg(Addr.Base.Reg);
675 // Get the RR opcode corresponding to the RI one. FIXME: It would be
676 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
677 // is hard to get at.
679 default: llvm_unreachable("Unexpected opcode!");
680 case PPC::STB: Opc = PPC::STBX; break;
681 case PPC::STH : Opc = PPC::STHX; break;
682 case PPC::STW : Opc = PPC::STWX; break;
683 case PPC::STB8: Opc = PPC::STBX8; break;
684 case PPC::STH8: Opc = PPC::STHX8; break;
685 case PPC::STW8: Opc = PPC::STWX8; break;
686 case PPC::STD: Opc = PPC::STDX; break;
687 case PPC::STFS: Opc = PPC::STFSX; break;
688 case PPC::STFD: Opc = IsVSFRC ? PPC::STXSDX : PPC::STFDX; break;
691 auto MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
694 // If we have an index register defined we use it in the store inst,
695 // otherwise we use X0 as base as it makes the vector instructions to
696 // use zero in the computation of the effective address regardless the
697 // content of the register.
699 MIB.addReg(Addr.Base.Reg).addReg(IndexReg);
701 MIB.addReg(PPC::ZERO8).addReg(Addr.Base.Reg);
707 // Attempt to fast-select a store instruction.
708 bool PPCFastISel::SelectStore(const Instruction *I) {
709 Value *Op0 = I->getOperand(0);
712 // FIXME: No atomics loads are supported.
713 if (cast<StoreInst>(I)->isAtomic())
716 // Verify we have a legal type before going any further.
718 if (!isLoadTypeLegal(Op0->getType(), VT))
721 // Get the value to be stored into a register.
722 SrcReg = getRegForValue(Op0);
726 // See if we can handle this address.
728 if (!PPCComputeAddress(I->getOperand(1), Addr))
731 if (!PPCEmitStore(VT, SrcReg, Addr))
737 // Attempt to fast-select a branch instruction.
738 bool PPCFastISel::SelectBranch(const Instruction *I) {
739 const BranchInst *BI = cast<BranchInst>(I);
740 MachineBasicBlock *BrBB = FuncInfo.MBB;
741 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
742 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
744 // For now, just try the simplest case where it's fed by a compare.
745 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
746 if (isValueAvailable(CI)) {
747 Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
751 PPC::Predicate PPCPred = OptPPCPred.getValue();
753 // Take advantage of fall-through opportunities.
754 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
756 PPCPred = PPC::InvertPredicate(PPCPred);
759 unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
761 if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
765 BuildMI(*BrBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::BCC))
766 .addImm(PPCPred).addReg(CondReg).addMBB(TBB);
767 fastEmitBranch(FBB, DbgLoc);
768 FuncInfo.MBB->addSuccessor(TBB);
771 } else if (const ConstantInt *CI =
772 dyn_cast<ConstantInt>(BI->getCondition())) {
773 uint64_t Imm = CI->getZExtValue();
774 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
775 fastEmitBranch(Target, DbgLoc);
779 // FIXME: ARM looks for a case where the block containing the compare
780 // has been split from the block containing the branch. If this happens,
781 // there is a vreg available containing the result of the compare. I'm
782 // not sure we can do much, as we've lost the predicate information with
783 // the compare instruction -- we have a 4-bit CR but don't know which bit
788 // Attempt to emit a compare of the two source values. Signed and unsigned
789 // comparisons are supported. Return false if we can't handle it.
790 bool PPCFastISel::PPCEmitCmp(const Value *SrcValue1, const Value *SrcValue2,
791 bool IsZExt, unsigned DestReg) {
792 Type *Ty = SrcValue1->getType();
793 EVT SrcEVT = TLI.getValueType(Ty, true);
794 if (!SrcEVT.isSimple())
796 MVT SrcVT = SrcEVT.getSimpleVT();
798 if (SrcVT == MVT::i1 && PPCSubTarget->useCRBits())
801 // See if operand 2 is an immediate encodeable in the compare.
802 // FIXME: Operands are not in canonical order at -O0, so an immediate
803 // operand in position 1 is a lost opportunity for now. We are
804 // similar to ARM in this regard.
808 // Only 16-bit integer constants can be represented in compares for
809 // PowerPC. Others will be materialized into a register.
810 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(SrcValue2)) {
811 if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
812 SrcVT == MVT::i8 || SrcVT == MVT::i1) {
813 const APInt &CIVal = ConstInt->getValue();
814 Imm = (IsZExt) ? (long)CIVal.getZExtValue() : (long)CIVal.getSExtValue();
815 if ((IsZExt && isUInt<16>(Imm)) || (!IsZExt && isInt<16>(Imm)))
821 bool NeedsExt = false;
822 switch (SrcVT.SimpleTy) {
823 default: return false;
825 CmpOpc = PPC::FCMPUS;
828 CmpOpc = PPC::FCMPUD;
834 // Intentional fall-through.
837 CmpOpc = IsZExt ? PPC::CMPLW : PPC::CMPW;
839 CmpOpc = IsZExt ? PPC::CMPLWI : PPC::CMPWI;
843 CmpOpc = IsZExt ? PPC::CMPLD : PPC::CMPD;
845 CmpOpc = IsZExt ? PPC::CMPLDI : PPC::CMPDI;
849 unsigned SrcReg1 = getRegForValue(SrcValue1);
853 unsigned SrcReg2 = 0;
855 SrcReg2 = getRegForValue(SrcValue2);
861 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
862 if (!PPCEmitIntExt(SrcVT, SrcReg1, MVT::i32, ExtReg, IsZExt))
867 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
868 if (!PPCEmitIntExt(SrcVT, SrcReg2, MVT::i32, ExtReg, IsZExt))
875 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc), DestReg)
876 .addReg(SrcReg1).addReg(SrcReg2);
878 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc), DestReg)
879 .addReg(SrcReg1).addImm(Imm);
884 // Attempt to fast-select a floating-point extend instruction.
885 bool PPCFastISel::SelectFPExt(const Instruction *I) {
886 Value *Src = I->getOperand(0);
887 EVT SrcVT = TLI.getValueType(Src->getType(), true);
888 EVT DestVT = TLI.getValueType(I->getType(), true);
890 if (SrcVT != MVT::f32 || DestVT != MVT::f64)
893 unsigned SrcReg = getRegForValue(Src);
897 // No code is generated for a FP extend.
898 updateValueMap(I, SrcReg);
902 // Attempt to fast-select a floating-point truncate instruction.
903 bool PPCFastISel::SelectFPTrunc(const Instruction *I) {
904 Value *Src = I->getOperand(0);
905 EVT SrcVT = TLI.getValueType(Src->getType(), true);
906 EVT DestVT = TLI.getValueType(I->getType(), true);
908 if (SrcVT != MVT::f64 || DestVT != MVT::f32)
911 unsigned SrcReg = getRegForValue(Src);
915 // Round the result to single precision.
916 unsigned DestReg = createResultReg(&PPC::F4RCRegClass);
917 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::FRSP), DestReg)
920 updateValueMap(I, DestReg);
924 // Move an i32 or i64 value in a GPR to an f64 value in an FPR.
925 // FIXME: When direct register moves are implemented (see PowerISA 2.07),
926 // those should be used instead of moving via a stack slot when the
927 // subtarget permits.
928 // FIXME: The code here is sloppy for the 4-byte case. Can use a 4-byte
929 // stack slot and 4-byte store/load sequence. Or just sext the 4-byte
930 // case to 8 bytes which produces tighter code but wastes stack space.
931 unsigned PPCFastISel::PPCMoveToFPReg(MVT SrcVT, unsigned SrcReg,
934 // If necessary, extend 32-bit int to 64-bit.
935 if (SrcVT == MVT::i32) {
936 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
937 if (!PPCEmitIntExt(MVT::i32, SrcReg, MVT::i64, TmpReg, !IsSigned))
942 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
944 Addr.BaseType = Address::FrameIndexBase;
945 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
947 // Store the value from the GPR.
948 if (!PPCEmitStore(MVT::i64, SrcReg, Addr))
951 // Load the integer value into an FPR. The kind of load used depends
952 // on a number of conditions.
953 unsigned LoadOpc = PPC::LFD;
955 if (SrcVT == MVT::i32) {
957 LoadOpc = PPC::LFIWZX;
958 Addr.Offset = (PPCSubTarget->isLittleEndian()) ? 0 : 4;
959 } else if (PPCSubTarget->hasLFIWAX()) {
960 LoadOpc = PPC::LFIWAX;
961 Addr.Offset = (PPCSubTarget->isLittleEndian()) ? 0 : 4;
965 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
966 unsigned ResultReg = 0;
967 if (!PPCEmitLoad(MVT::f64, ResultReg, Addr, RC, !IsSigned, LoadOpc))
973 // Attempt to fast-select an integer-to-floating-point conversion.
974 // FIXME: Once fast-isel has better support for VSX, conversions using
975 // direct moves should be implemented.
976 bool PPCFastISel::SelectIToFP(const Instruction *I, bool IsSigned) {
978 Type *DstTy = I->getType();
979 if (!isTypeLegal(DstTy, DstVT))
982 if (DstVT != MVT::f32 && DstVT != MVT::f64)
985 Value *Src = I->getOperand(0);
986 EVT SrcEVT = TLI.getValueType(Src->getType(), true);
987 if (!SrcEVT.isSimple())
990 MVT SrcVT = SrcEVT.getSimpleVT();
992 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 &&
993 SrcVT != MVT::i32 && SrcVT != MVT::i64)
996 unsigned SrcReg = getRegForValue(Src);
1000 // We can only lower an unsigned convert if we have the newer
1001 // floating-point conversion operations.
1002 if (!IsSigned && !PPCSubTarget->hasFPCVT())
1005 // FIXME: For now we require the newer floating-point conversion operations
1006 // (which are present only on P7 and A2 server models) when converting
1007 // to single-precision float. Otherwise we have to generate a lot of
1008 // fiddly code to avoid double rounding. If necessary, the fiddly code
1009 // can be found in PPCTargetLowering::LowerINT_TO_FP().
1010 if (DstVT == MVT::f32 && !PPCSubTarget->hasFPCVT())
1013 // Extend the input if necessary.
1014 if (SrcVT == MVT::i8 || SrcVT == MVT::i16) {
1015 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
1016 if (!PPCEmitIntExt(SrcVT, SrcReg, MVT::i64, TmpReg, !IsSigned))
1022 // Move the integer value to an FPR.
1023 unsigned FPReg = PPCMoveToFPReg(SrcVT, SrcReg, IsSigned);
1027 // Determine the opcode for the conversion.
1028 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
1029 unsigned DestReg = createResultReg(RC);
1032 if (DstVT == MVT::f32)
1033 Opc = IsSigned ? PPC::FCFIDS : PPC::FCFIDUS;
1035 Opc = IsSigned ? PPC::FCFID : PPC::FCFIDU;
1037 // Generate the convert.
1038 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1041 updateValueMap(I, DestReg);
1045 // Move the floating-point value in SrcReg into an integer destination
1046 // register, and return the register (or zero if we can't handle it).
1047 // FIXME: When direct register moves are implemented (see PowerISA 2.07),
1048 // those should be used instead of moving via a stack slot when the
1049 // subtarget permits.
1050 unsigned PPCFastISel::PPCMoveToIntReg(const Instruction *I, MVT VT,
1051 unsigned SrcReg, bool IsSigned) {
1052 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
1053 // Note that if have STFIWX available, we could use a 4-byte stack
1054 // slot for i32, but this being fast-isel we'll just go with the
1055 // easiest code gen possible.
1057 Addr.BaseType = Address::FrameIndexBase;
1058 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
1060 // Store the value from the FPR.
1061 if (!PPCEmitStore(MVT::f64, SrcReg, Addr))
1064 // Reload it into a GPR. If we want an i32, modify the address
1065 // to have a 4-byte offset so we load from the right place.
1069 // Look at the currently assigned register for this instruction
1070 // to determine the required register class.
1071 unsigned AssignedReg = FuncInfo.ValueMap[I];
1072 const TargetRegisterClass *RC =
1073 AssignedReg ? MRI.getRegClass(AssignedReg) : nullptr;
1075 unsigned ResultReg = 0;
1076 if (!PPCEmitLoad(VT, ResultReg, Addr, RC, !IsSigned))
1082 // Attempt to fast-select a floating-point-to-integer conversion.
1083 // FIXME: Once fast-isel has better support for VSX, conversions using
1084 // direct moves should be implemented.
1085 bool PPCFastISel::SelectFPToI(const Instruction *I, bool IsSigned) {
1087 Type *DstTy = I->getType();
1088 if (!isTypeLegal(DstTy, DstVT))
1091 if (DstVT != MVT::i32 && DstVT != MVT::i64)
1094 // If we don't have FCTIDUZ and we need it, punt to SelectionDAG.
1095 if (DstVT == MVT::i64 && !IsSigned && !PPCSubTarget->hasFPCVT())
1098 Value *Src = I->getOperand(0);
1099 Type *SrcTy = Src->getType();
1100 if (!isTypeLegal(SrcTy, SrcVT))
1103 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
1106 unsigned SrcReg = getRegForValue(Src);
1110 // Convert f32 to f64 if necessary. This is just a meaningless copy
1111 // to get the register class right. COPY_TO_REGCLASS is needed since
1112 // a COPY from F4RC to F8RC is converted to a F4RC-F4RC copy downstream.
1113 const TargetRegisterClass *InRC = MRI.getRegClass(SrcReg);
1114 if (InRC == &PPC::F4RCRegClass) {
1115 unsigned TmpReg = createResultReg(&PPC::F8RCRegClass);
1116 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1117 TII.get(TargetOpcode::COPY_TO_REGCLASS), TmpReg)
1118 .addReg(SrcReg).addImm(PPC::F8RCRegClassID);
1122 // Determine the opcode for the conversion, which takes place
1123 // entirely within FPRs.
1124 unsigned DestReg = createResultReg(&PPC::F8RCRegClass);
1127 if (DstVT == MVT::i32)
1131 Opc = PPCSubTarget->hasFPCVT() ? PPC::FCTIWUZ : PPC::FCTIDZ;
1133 Opc = IsSigned ? PPC::FCTIDZ : PPC::FCTIDUZ;
1135 // Generate the convert.
1136 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1139 // Now move the integer value from a float register to an integer register.
1140 unsigned IntReg = PPCMoveToIntReg(I, DstVT, DestReg, IsSigned);
1144 updateValueMap(I, IntReg);
1148 // Attempt to fast-select a binary integer operation that isn't already
1149 // handled automatically.
1150 bool PPCFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1151 EVT DestVT = TLI.getValueType(I->getType(), true);
1153 // We can get here in the case when we have a binary operation on a non-legal
1154 // type and the target independent selector doesn't know how to handle it.
1155 if (DestVT != MVT::i16 && DestVT != MVT::i8)
1158 // Look at the currently assigned register for this instruction
1159 // to determine the required register class. If there is no register,
1160 // make a conservative choice (don't assign R0).
1161 unsigned AssignedReg = FuncInfo.ValueMap[I];
1162 const TargetRegisterClass *RC =
1163 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1164 &PPC::GPRC_and_GPRC_NOR0RegClass);
1165 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1168 switch (ISDOpcode) {
1169 default: return false;
1171 Opc = IsGPRC ? PPC::ADD4 : PPC::ADD8;
1174 Opc = IsGPRC ? PPC::OR : PPC::OR8;
1177 Opc = IsGPRC ? PPC::SUBF : PPC::SUBF8;
1181 unsigned ResultReg = createResultReg(RC ? RC : &PPC::G8RCRegClass);
1182 unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1183 if (SrcReg1 == 0) return false;
1185 // Handle case of small immediate operand.
1186 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(1))) {
1187 const APInt &CIVal = ConstInt->getValue();
1188 int Imm = (int)CIVal.getSExtValue();
1190 if (isInt<16>(Imm)) {
1193 llvm_unreachable("Missing case!");
1196 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1200 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1213 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1222 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1229 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
1233 updateValueMap(I, ResultReg);
1240 unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1241 if (SrcReg2 == 0) return false;
1243 // Reverse operands for subtract-from.
1244 if (ISDOpcode == ISD::SUB)
1245 std::swap(SrcReg1, SrcReg2);
1247 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1248 .addReg(SrcReg1).addReg(SrcReg2);
1249 updateValueMap(I, ResultReg);
1253 // Handle arguments to a call that we're attempting to fast-select.
1254 // Return false if the arguments are too complex for us at the moment.
1255 bool PPCFastISel::processCallArgs(SmallVectorImpl<Value*> &Args,
1256 SmallVectorImpl<unsigned> &ArgRegs,
1257 SmallVectorImpl<MVT> &ArgVTs,
1258 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1259 SmallVectorImpl<unsigned> &RegArgs,
1263 SmallVector<CCValAssign, 16> ArgLocs;
1264 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, *Context);
1266 // Reserve space for the linkage area on the stack.
1267 unsigned LinkageSize = PPCSubTarget->getFrameLowering()->getLinkageSize();
1268 CCInfo.AllocateStack(LinkageSize, 8);
1270 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_PPC64_ELF_FIS);
1272 // Bail out if we can't handle any of the arguments.
1273 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1274 CCValAssign &VA = ArgLocs[I];
1275 MVT ArgVT = ArgVTs[VA.getValNo()];
1277 // Skip vector arguments for now, as well as long double and
1278 // uint128_t, and anything that isn't passed in a register.
1279 if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64 || ArgVT == MVT::i1 ||
1280 !VA.isRegLoc() || VA.needsCustom())
1283 // Skip bit-converted arguments for now.
1284 if (VA.getLocInfo() == CCValAssign::BCvt)
1288 // Get a count of how many bytes are to be pushed onto the stack.
1289 NumBytes = CCInfo.getNextStackOffset();
1291 // The prolog code of the callee may store up to 8 GPR argument registers to
1292 // the stack, allowing va_start to index over them in memory if its varargs.
1293 // Because we cannot tell if this is needed on the caller side, we have to
1294 // conservatively assume that it is needed. As such, make sure we have at
1295 // least enough stack space for the caller to store the 8 GPRs.
1296 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
1297 NumBytes = std::max(NumBytes, LinkageSize + 64);
1299 // Issue CALLSEQ_START.
1300 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1301 TII.get(TII.getCallFrameSetupOpcode()))
1304 // Prepare to assign register arguments. Every argument uses up a
1305 // GPR protocol register even if it's passed in a floating-point
1306 // register (unless we're using the fast calling convention).
1307 unsigned NextGPR = PPC::X3;
1308 unsigned NextFPR = PPC::F1;
1310 // Process arguments.
1311 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1312 CCValAssign &VA = ArgLocs[I];
1313 unsigned Arg = ArgRegs[VA.getValNo()];
1314 MVT ArgVT = ArgVTs[VA.getValNo()];
1316 // Handle argument promotion and bitcasts.
1317 switch (VA.getLocInfo()) {
1319 llvm_unreachable("Unknown loc info!");
1320 case CCValAssign::Full:
1322 case CCValAssign::SExt: {
1323 MVT DestVT = VA.getLocVT();
1324 const TargetRegisterClass *RC =
1325 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1326 unsigned TmpReg = createResultReg(RC);
1327 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/false))
1328 llvm_unreachable("Failed to emit a sext!");
1333 case CCValAssign::AExt:
1334 case CCValAssign::ZExt: {
1335 MVT DestVT = VA.getLocVT();
1336 const TargetRegisterClass *RC =
1337 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1338 unsigned TmpReg = createResultReg(RC);
1339 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/true))
1340 llvm_unreachable("Failed to emit a zext!");
1345 case CCValAssign::BCvt: {
1346 // FIXME: Not yet handled.
1347 llvm_unreachable("Should have bailed before getting here!");
1352 // Copy this argument to the appropriate register.
1354 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) {
1356 if (CC != CallingConv::Fast)
1361 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1362 TII.get(TargetOpcode::COPY), ArgReg).addReg(Arg);
1363 RegArgs.push_back(ArgReg);
1369 // For a call that we've determined we can fast-select, finish the
1370 // call sequence and generate a copy to obtain the return value (if any).
1371 bool PPCFastISel::finishCall(MVT RetVT, CallLoweringInfo &CLI, unsigned &NumBytes) {
1372 CallingConv::ID CC = CLI.CallConv;
1374 // Issue CallSEQ_END.
1375 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1376 TII.get(TII.getCallFrameDestroyOpcode()))
1377 .addImm(NumBytes).addImm(0);
1379 // Next, generate a copy to obtain the return value.
1380 // FIXME: No multi-register return values yet, though I don't foresee
1381 // any real difficulties there.
1382 if (RetVT != MVT::isVoid) {
1383 SmallVector<CCValAssign, 16> RVLocs;
1384 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
1385 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1386 CCValAssign &VA = RVLocs[0];
1387 assert(RVLocs.size() == 1 && "No support for multi-reg return values!");
1388 assert(VA.isRegLoc() && "Can only return in registers!");
1390 MVT DestVT = VA.getValVT();
1391 MVT CopyVT = DestVT;
1393 // Ints smaller than a register still arrive in a full 64-bit
1394 // register, so make sure we recognize this.
1395 if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32)
1398 unsigned SourcePhysReg = VA.getLocReg();
1399 unsigned ResultReg = 0;
1401 if (RetVT == CopyVT) {
1402 const TargetRegisterClass *CpyRC = TLI.getRegClassFor(CopyVT);
1403 ResultReg = createResultReg(CpyRC);
1405 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1406 TII.get(TargetOpcode::COPY), ResultReg)
1407 .addReg(SourcePhysReg);
1409 // If necessary, round the floating result to single precision.
1410 } else if (CopyVT == MVT::f64) {
1411 ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1412 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::FRSP),
1413 ResultReg).addReg(SourcePhysReg);
1415 // If only the low half of a general register is needed, generate
1416 // a GPRC copy instead of a G8RC copy. (EXTRACT_SUBREG can't be
1417 // used along the fast-isel path (not lowered), and downstream logic
1418 // also doesn't like a direct subreg copy on a physical reg.)
1419 } else if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32) {
1420 ResultReg = createResultReg(&PPC::GPRCRegClass);
1421 // Convert physical register from G8RC to GPRC.
1422 SourcePhysReg -= PPC::X0 - PPC::R0;
1423 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1424 TII.get(TargetOpcode::COPY), ResultReg)
1425 .addReg(SourcePhysReg);
1428 assert(ResultReg && "ResultReg unset!");
1429 CLI.InRegs.push_back(SourcePhysReg);
1430 CLI.ResultReg = ResultReg;
1431 CLI.NumResultRegs = 1;
1437 bool PPCFastISel::fastLowerCall(CallLoweringInfo &CLI) {
1438 CallingConv::ID CC = CLI.CallConv;
1439 bool IsTailCall = CLI.IsTailCall;
1440 bool IsVarArg = CLI.IsVarArg;
1441 const Value *Callee = CLI.Callee;
1442 const char *SymName = CLI.SymName;
1444 if (!Callee && !SymName)
1447 // Allow SelectionDAG isel to handle tail calls.
1451 // Let SDISel handle vararg functions.
1455 // Handle simple calls for now, with legal return types and
1456 // those that can be extended.
1457 Type *RetTy = CLI.RetTy;
1459 if (RetTy->isVoidTy())
1460 RetVT = MVT::isVoid;
1461 else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
1464 else if (RetVT == MVT::i1 && PPCSubTarget->useCRBits())
1465 // We can't handle boolean returns when CR bits are in use.
1468 // FIXME: No multi-register return values yet.
1469 if (RetVT != MVT::isVoid && RetVT != MVT::i8 && RetVT != MVT::i16 &&
1470 RetVT != MVT::i32 && RetVT != MVT::i64 && RetVT != MVT::f32 &&
1471 RetVT != MVT::f64) {
1472 SmallVector<CCValAssign, 16> RVLocs;
1473 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs, *Context);
1474 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1475 if (RVLocs.size() > 1)
1479 // Bail early if more than 8 arguments, as we only currently
1480 // handle arguments passed in registers.
1481 unsigned NumArgs = CLI.OutVals.size();
1485 // Set up the argument vectors.
1486 SmallVector<Value*, 8> Args;
1487 SmallVector<unsigned, 8> ArgRegs;
1488 SmallVector<MVT, 8> ArgVTs;
1489 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1491 Args.reserve(NumArgs);
1492 ArgRegs.reserve(NumArgs);
1493 ArgVTs.reserve(NumArgs);
1494 ArgFlags.reserve(NumArgs);
1496 for (unsigned i = 0, ie = NumArgs; i != ie; ++i) {
1497 // Only handle easy calls for now. It would be reasonably easy
1498 // to handle <= 8-byte structures passed ByVal in registers, but we
1499 // have to ensure they are right-justified in the register.
1500 ISD::ArgFlagsTy Flags = CLI.OutFlags[i];
1501 if (Flags.isInReg() || Flags.isSRet() || Flags.isNest() || Flags.isByVal())
1504 Value *ArgValue = CLI.OutVals[i];
1505 Type *ArgTy = ArgValue->getType();
1507 if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8)
1510 if (ArgVT.isVector())
1513 unsigned Arg = getRegForValue(ArgValue);
1517 Args.push_back(ArgValue);
1518 ArgRegs.push_back(Arg);
1519 ArgVTs.push_back(ArgVT);
1520 ArgFlags.push_back(Flags);
1523 // Process the arguments.
1524 SmallVector<unsigned, 8> RegArgs;
1527 if (!processCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
1528 RegArgs, CC, NumBytes, IsVarArg))
1531 MachineInstrBuilder MIB;
1532 // FIXME: No handling for function pointers yet. This requires
1533 // implementing the function descriptor (OPD) setup.
1534 const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1536 // patchpoints are a special case; they always dispatch to a pointer value.
1537 // However, we don't actually want to generate the indirect call sequence
1538 // here (that will be generated, as necessary, during asm printing), and
1539 // the call we generate here will be erased by FastISel::selectPatchpoint,
1540 // so don't try very hard...
1541 if (CLI.IsPatchPoint)
1542 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::NOP));
1546 // Build direct call with NOP for TOC restore.
1547 // FIXME: We can and should optimize away the NOP for local calls.
1548 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1549 TII.get(PPC::BL8_NOP));
1551 MIB.addGlobalAddress(GV);
1554 // Add implicit physical register uses to the call.
1555 for (unsigned II = 0, IE = RegArgs.size(); II != IE; ++II)
1556 MIB.addReg(RegArgs[II], RegState::Implicit);
1558 // Direct calls, in both the ELF V1 and V2 ABIs, need the TOC register live
1560 PPCFuncInfo->setUsesTOCBasePtr();
1561 MIB.addReg(PPC::X2, RegState::Implicit);
1563 // Add a register mask with the call-preserved registers. Proper
1564 // defs for return values will be added by setPhysRegsDeadExcept().
1565 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
1569 // Finish off the call including any return values.
1570 return finishCall(RetVT, CLI, NumBytes);
1573 // Attempt to fast-select a return instruction.
1574 bool PPCFastISel::SelectRet(const Instruction *I) {
1576 if (!FuncInfo.CanLowerReturn)
1579 const ReturnInst *Ret = cast<ReturnInst>(I);
1580 const Function &F = *I->getParent()->getParent();
1582 // Build a list of return value registers.
1583 SmallVector<unsigned, 4> RetRegs;
1584 CallingConv::ID CC = F.getCallingConv();
1586 if (Ret->getNumOperands() > 0) {
1587 SmallVector<ISD::OutputArg, 4> Outs;
1588 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1590 // Analyze operands of the call, assigning locations to each operand.
1591 SmallVector<CCValAssign, 16> ValLocs;
1592 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, *Context);
1593 CCInfo.AnalyzeReturn(Outs, RetCC_PPC64_ELF_FIS);
1594 const Value *RV = Ret->getOperand(0);
1596 // FIXME: Only one output register for now.
1597 if (ValLocs.size() > 1)
1600 // Special case for returning a constant integer of any size.
1601 // Materialize the constant as an i64 and copy it to the return
1602 // register. We still need to worry about properly extending the sign. E.g:
1603 // If the constant has only one bit, it means it is a boolean. Therefore
1604 // we can't use PPCMaterializeInt because it extends the sign which will
1605 // cause negations of the returned value to be incorrect as they are
1606 // implemented as the flip of the least significant bit.
1607 if (isa<ConstantInt>(*RV)) {
1608 const Constant *C = cast<Constant>(RV);
1610 CCValAssign &VA = ValLocs[0];
1612 unsigned RetReg = VA.getLocReg();
1613 unsigned SrcReg = PPCMaterializeInt(C, MVT::i64,
1614 VA.getLocInfo() == CCValAssign::SExt);
1616 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1617 TII.get(TargetOpcode::COPY), RetReg).addReg(SrcReg);
1619 RetRegs.push_back(RetReg);
1622 unsigned Reg = getRegForValue(RV);
1627 // Copy the result values into the output registers.
1628 for (unsigned i = 0; i < ValLocs.size(); ++i) {
1630 CCValAssign &VA = ValLocs[i];
1631 assert(VA.isRegLoc() && "Can only return in registers!");
1632 RetRegs.push_back(VA.getLocReg());
1633 unsigned SrcReg = Reg + VA.getValNo();
1635 EVT RVEVT = TLI.getValueType(RV->getType());
1636 if (!RVEVT.isSimple())
1638 MVT RVVT = RVEVT.getSimpleVT();
1639 MVT DestVT = VA.getLocVT();
1641 if (RVVT != DestVT && RVVT != MVT::i8 &&
1642 RVVT != MVT::i16 && RVVT != MVT::i32)
1645 if (RVVT != DestVT) {
1646 switch (VA.getLocInfo()) {
1648 llvm_unreachable("Unknown loc info!");
1649 case CCValAssign::Full:
1650 llvm_unreachable("Full value assign but types don't match?");
1651 case CCValAssign::AExt:
1652 case CCValAssign::ZExt: {
1653 const TargetRegisterClass *RC =
1654 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1655 unsigned TmpReg = createResultReg(RC);
1656 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, true))
1661 case CCValAssign::SExt: {
1662 const TargetRegisterClass *RC =
1663 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1664 unsigned TmpReg = createResultReg(RC);
1665 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, false))
1673 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1674 TII.get(TargetOpcode::COPY), RetRegs[i])
1680 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1681 TII.get(PPC::BLR8));
1683 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1684 MIB.addReg(RetRegs[i], RegState::Implicit);
1689 // Attempt to emit an integer extend of SrcReg into DestReg. Both
1690 // signed and zero extensions are supported. Return false if we
1692 bool PPCFastISel::PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1693 unsigned DestReg, bool IsZExt) {
1694 if (DestVT != MVT::i32 && DestVT != MVT::i64)
1696 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 && SrcVT != MVT::i32)
1699 // Signed extensions use EXTSB, EXTSH, EXTSW.
1702 if (SrcVT == MVT::i8)
1703 Opc = (DestVT == MVT::i32) ? PPC::EXTSB : PPC::EXTSB8_32_64;
1704 else if (SrcVT == MVT::i16)
1705 Opc = (DestVT == MVT::i32) ? PPC::EXTSH : PPC::EXTSH8_32_64;
1707 assert(DestVT == MVT::i64 && "Signed extend from i32 to i32??");
1708 Opc = PPC::EXTSW_32_64;
1710 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1713 // Unsigned 32-bit extensions use RLWINM.
1714 } else if (DestVT == MVT::i32) {
1716 if (SrcVT == MVT::i8)
1719 assert(SrcVT == MVT::i16 && "Unsigned extend from i32 to i32??");
1722 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::RLWINM),
1724 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB).addImm(/*ME=*/31);
1726 // Unsigned 64-bit extensions use RLDICL (with a 32-bit source).
1729 if (SrcVT == MVT::i8)
1731 else if (SrcVT == MVT::i16)
1735 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1736 TII.get(PPC::RLDICL_32_64), DestReg)
1737 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB);
1743 // Attempt to fast-select an indirect branch instruction.
1744 bool PPCFastISel::SelectIndirectBr(const Instruction *I) {
1745 unsigned AddrReg = getRegForValue(I->getOperand(0));
1749 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::MTCTR8))
1751 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::BCTR8));
1753 const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1754 for (unsigned i = 0, e = IB->getNumSuccessors(); i != e; ++i)
1755 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[IB->getSuccessor(i)]);
1760 // Attempt to fast-select an integer truncate instruction.
1761 bool PPCFastISel::SelectTrunc(const Instruction *I) {
1762 Value *Src = I->getOperand(0);
1763 EVT SrcVT = TLI.getValueType(Src->getType(), true);
1764 EVT DestVT = TLI.getValueType(I->getType(), true);
1766 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16)
1769 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8)
1772 unsigned SrcReg = getRegForValue(Src);
1776 // The only interesting case is when we need to switch register classes.
1777 if (SrcVT == MVT::i64) {
1778 unsigned ResultReg = createResultReg(&PPC::GPRCRegClass);
1779 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1780 TII.get(TargetOpcode::COPY),
1781 ResultReg).addReg(SrcReg, 0, PPC::sub_32);
1785 updateValueMap(I, SrcReg);
1789 // Attempt to fast-select an integer extend instruction.
1790 bool PPCFastISel::SelectIntExt(const Instruction *I) {
1791 Type *DestTy = I->getType();
1792 Value *Src = I->getOperand(0);
1793 Type *SrcTy = Src->getType();
1795 bool IsZExt = isa<ZExtInst>(I);
1796 unsigned SrcReg = getRegForValue(Src);
1797 if (!SrcReg) return false;
1799 EVT SrcEVT, DestEVT;
1800 SrcEVT = TLI.getValueType(SrcTy, true);
1801 DestEVT = TLI.getValueType(DestTy, true);
1802 if (!SrcEVT.isSimple())
1804 if (!DestEVT.isSimple())
1807 MVT SrcVT = SrcEVT.getSimpleVT();
1808 MVT DestVT = DestEVT.getSimpleVT();
1810 // If we know the register class needed for the result of this
1811 // instruction, use it. Otherwise pick the register class of the
1812 // correct size that does not contain X0/R0, since we don't know
1813 // whether downstream uses permit that assignment.
1814 unsigned AssignedReg = FuncInfo.ValueMap[I];
1815 const TargetRegisterClass *RC =
1816 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1817 (DestVT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
1818 &PPC::GPRC_and_GPRC_NOR0RegClass));
1819 unsigned ResultReg = createResultReg(RC);
1821 if (!PPCEmitIntExt(SrcVT, SrcReg, DestVT, ResultReg, IsZExt))
1824 updateValueMap(I, ResultReg);
1828 // Attempt to fast-select an instruction that wasn't handled by
1829 // the table-generated machinery.
1830 bool PPCFastISel::fastSelectInstruction(const Instruction *I) {
1832 switch (I->getOpcode()) {
1833 case Instruction::Load:
1834 return SelectLoad(I);
1835 case Instruction::Store:
1836 return SelectStore(I);
1837 case Instruction::Br:
1838 return SelectBranch(I);
1839 case Instruction::IndirectBr:
1840 return SelectIndirectBr(I);
1841 case Instruction::FPExt:
1842 return SelectFPExt(I);
1843 case Instruction::FPTrunc:
1844 return SelectFPTrunc(I);
1845 case Instruction::SIToFP:
1846 return SelectIToFP(I, /*IsSigned*/ true);
1847 case Instruction::UIToFP:
1848 return SelectIToFP(I, /*IsSigned*/ false);
1849 case Instruction::FPToSI:
1850 return SelectFPToI(I, /*IsSigned*/ true);
1851 case Instruction::FPToUI:
1852 return SelectFPToI(I, /*IsSigned*/ false);
1853 case Instruction::Add:
1854 return SelectBinaryIntOp(I, ISD::ADD);
1855 case Instruction::Or:
1856 return SelectBinaryIntOp(I, ISD::OR);
1857 case Instruction::Sub:
1858 return SelectBinaryIntOp(I, ISD::SUB);
1859 case Instruction::Call:
1860 return selectCall(I);
1861 case Instruction::Ret:
1862 return SelectRet(I);
1863 case Instruction::Trunc:
1864 return SelectTrunc(I);
1865 case Instruction::ZExt:
1866 case Instruction::SExt:
1867 return SelectIntExt(I);
1868 // Here add other flavors of Instruction::XXX that automated
1869 // cases don't catch. For example, switches are terminators
1870 // that aren't yet handled.
1877 // Materialize a floating-point constant into a register, and return
1878 // the register number (or zero if we failed to handle it).
1879 unsigned PPCFastISel::PPCMaterializeFP(const ConstantFP *CFP, MVT VT) {
1880 // No plans to handle long double here.
1881 if (VT != MVT::f32 && VT != MVT::f64)
1884 // All FP constants are loaded from the constant pool.
1885 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
1886 assert(Align > 0 && "Unexpectedly missing alignment information!");
1887 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
1888 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
1889 CodeModel::Model CModel = TM.getCodeModel();
1891 MachineMemOperand *MMO =
1892 FuncInfo.MF->getMachineMemOperand(
1893 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
1894 (VT == MVT::f32) ? 4 : 8, Align);
1896 unsigned Opc = (VT == MVT::f32) ? PPC::LFS : PPC::LFD;
1897 unsigned TmpReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1899 PPCFuncInfo->setUsesTOCBasePtr();
1900 // For small code model, generate a LF[SD](0, LDtocCPT(Idx, X2)).
1901 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault) {
1902 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocCPT),
1904 .addConstantPoolIndex(Idx).addReg(PPC::X2);
1905 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1906 .addImm(0).addReg(TmpReg).addMemOperand(MMO);
1908 // Otherwise we generate LF[SD](Idx[lo], ADDIStocHA(X2, Idx)).
1909 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDIStocHA),
1910 TmpReg).addReg(PPC::X2).addConstantPoolIndex(Idx);
1911 // But for large code model, we must generate a LDtocL followed
1913 if (CModel == CodeModel::Large) {
1914 unsigned TmpReg2 = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1915 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocL),
1916 TmpReg2).addConstantPoolIndex(Idx).addReg(TmpReg);
1917 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1918 .addImm(0).addReg(TmpReg2);
1920 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1921 .addConstantPoolIndex(Idx, 0, PPCII::MO_TOC_LO)
1923 .addMemOperand(MMO);
1929 // Materialize the address of a global value into a register, and return
1930 // the register number (or zero if we failed to handle it).
1931 unsigned PPCFastISel::PPCMaterializeGV(const GlobalValue *GV, MVT VT) {
1932 assert(VT == MVT::i64 && "Non-address!");
1933 const TargetRegisterClass *RC = &PPC::G8RC_and_G8RC_NOX0RegClass;
1934 unsigned DestReg = createResultReg(RC);
1936 // Global values may be plain old object addresses, TLS object
1937 // addresses, constant pool entries, or jump tables. How we generate
1938 // code for these may depend on small, medium, or large code model.
1939 CodeModel::Model CModel = TM.getCodeModel();
1941 // FIXME: Jump tables are not yet required because fast-isel doesn't
1942 // handle switches; if that changes, we need them as well. For now,
1943 // what follows assumes everything's a generic (or TLS) global address.
1945 // FIXME: We don't yet handle the complexity of TLS.
1946 if (GV->isThreadLocal())
1949 PPCFuncInfo->setUsesTOCBasePtr();
1950 // For small code model, generate a simple TOC load.
1951 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault)
1952 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtoc),
1954 .addGlobalAddress(GV)
1957 // If the address is an externally defined symbol, a symbol with common
1958 // or externally available linkage, a non-local function address, or a
1959 // jump table address (not yet needed), or if we are generating code
1960 // for large code model, we generate:
1961 // LDtocL(GV, ADDIStocHA(%X2, GV))
1962 // Otherwise we generate:
1963 // ADDItocL(ADDIStocHA(%X2, GV), GV)
1964 // Either way, start with the ADDIStocHA:
1965 unsigned HighPartReg = createResultReg(RC);
1966 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDIStocHA),
1967 HighPartReg).addReg(PPC::X2).addGlobalAddress(GV);
1969 // If/when switches are implemented, jump tables should be handled
1970 // on the "if" path here.
1971 if (CModel == CodeModel::Large ||
1972 (GV->getType()->getElementType()->isFunctionTy() &&
1973 (GV->isDeclaration() || GV->isWeakForLinker())) ||
1974 GV->isDeclaration() || GV->hasCommonLinkage() ||
1975 GV->hasAvailableExternallyLinkage())
1976 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocL),
1977 DestReg).addGlobalAddress(GV).addReg(HighPartReg);
1979 // Otherwise generate the ADDItocL.
1980 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDItocL),
1981 DestReg).addReg(HighPartReg).addGlobalAddress(GV);
1987 // Materialize a 32-bit integer constant into a register, and return
1988 // the register number (or zero if we failed to handle it).
1989 unsigned PPCFastISel::PPCMaterialize32BitInt(int64_t Imm,
1990 const TargetRegisterClass *RC) {
1991 unsigned Lo = Imm & 0xFFFF;
1992 unsigned Hi = (Imm >> 16) & 0xFFFF;
1994 unsigned ResultReg = createResultReg(RC);
1995 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1998 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1999 TII.get(IsGPRC ? PPC::LI : PPC::LI8), ResultReg)
2002 // Both Lo and Hi have nonzero bits.
2003 unsigned TmpReg = createResultReg(RC);
2004 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2005 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), TmpReg)
2007 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2008 TII.get(IsGPRC ? PPC::ORI : PPC::ORI8), ResultReg)
2009 .addReg(TmpReg).addImm(Lo);
2012 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2013 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), ResultReg)
2019 // Materialize a 64-bit integer constant into a register, and return
2020 // the register number (or zero if we failed to handle it).
2021 unsigned PPCFastISel::PPCMaterialize64BitInt(int64_t Imm,
2022 const TargetRegisterClass *RC) {
2023 unsigned Remainder = 0;
2026 // If the value doesn't fit in 32 bits, see if we can shift it
2027 // so that it fits in 32 bits.
2028 if (!isInt<32>(Imm)) {
2029 Shift = countTrailingZeros<uint64_t>(Imm);
2030 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
2032 if (isInt<32>(ImmSh))
2041 // Handle the high-order 32 bits (if shifted) or the whole 32 bits
2042 // (if not shifted).
2043 unsigned TmpReg1 = PPCMaterialize32BitInt(Imm, RC);
2047 // If upper 32 bits were not zero, we've built them and need to shift
2051 TmpReg2 = createResultReg(RC);
2052 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::RLDICR),
2053 TmpReg2).addReg(TmpReg1).addImm(Shift).addImm(63 - Shift);
2057 unsigned TmpReg3, Hi, Lo;
2058 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
2059 TmpReg3 = createResultReg(RC);
2060 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ORIS8),
2061 TmpReg3).addReg(TmpReg2).addImm(Hi);
2065 if ((Lo = Remainder & 0xFFFF)) {
2066 unsigned ResultReg = createResultReg(RC);
2067 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ORI8),
2068 ResultReg).addReg(TmpReg3).addImm(Lo);
2076 // Materialize an integer constant into a register, and return
2077 // the register number (or zero if we failed to handle it).
2078 unsigned PPCFastISel::PPCMaterializeInt(const Constant *C, MVT VT,
2080 // If we're using CR bit registers for i1 values, handle that as a special
2082 if (VT == MVT::i1 && PPCSubTarget->useCRBits()) {
2083 const ConstantInt *CI = cast<ConstantInt>(C);
2084 unsigned ImmReg = createResultReg(&PPC::CRBITRCRegClass);
2085 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2086 TII.get(CI->isZero() ? PPC::CRUNSET : PPC::CRSET), ImmReg);
2090 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2091 VT != MVT::i8 && VT != MVT::i1)
2094 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2095 &PPC::GPRCRegClass);
2097 // If the constant is in range, use a load-immediate.
2098 const ConstantInt *CI = cast<ConstantInt>(C);
2099 if (isInt<16>(CI->getSExtValue())) {
2100 unsigned Opc = (VT == MVT::i64) ? PPC::LI8 : PPC::LI;
2101 unsigned ImmReg = createResultReg(RC);
2102 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ImmReg)
2103 .addImm( (UseSExt) ? CI->getSExtValue() : CI->getZExtValue() );
2107 // Construct the constant piecewise.
2108 int64_t Imm = CI->getZExtValue();
2111 return PPCMaterialize64BitInt(Imm, RC);
2112 else if (VT == MVT::i32)
2113 return PPCMaterialize32BitInt(Imm, RC);
2118 // Materialize a constant into a register, and return the register
2119 // number (or zero if we failed to handle it).
2120 unsigned PPCFastISel::fastMaterializeConstant(const Constant *C) {
2121 EVT CEVT = TLI.getValueType(C->getType(), true);
2123 // Only handle simple types.
2124 if (!CEVT.isSimple()) return 0;
2125 MVT VT = CEVT.getSimpleVT();
2127 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
2128 return PPCMaterializeFP(CFP, VT);
2129 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
2130 return PPCMaterializeGV(GV, VT);
2131 else if (isa<ConstantInt>(C))
2132 return PPCMaterializeInt(C, VT, VT != MVT::i1);
2137 // Materialize the address created by an alloca into a register, and
2138 // return the register number (or zero if we failed to handle it).
2139 unsigned PPCFastISel::fastMaterializeAlloca(const AllocaInst *AI) {
2140 // Don't handle dynamic allocas.
2141 if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
2144 if (!isLoadTypeLegal(AI->getType(), VT)) return 0;
2146 DenseMap<const AllocaInst*, int>::iterator SI =
2147 FuncInfo.StaticAllocaMap.find(AI);
2149 if (SI != FuncInfo.StaticAllocaMap.end()) {
2150 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
2151 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDI8),
2152 ResultReg).addFrameIndex(SI->second).addImm(0);
2159 // Fold loads into extends when possible.
2160 // FIXME: We can have multiple redundant extend/trunc instructions
2161 // following a load. The folding only picks up one. Extend this
2162 // to check subsequent instructions for the same pattern and remove
2163 // them. Thus ResultReg should be the def reg for the last redundant
2164 // instruction in a chain, and all intervening instructions can be
2165 // removed from parent. Change test/CodeGen/PowerPC/fast-isel-fold.ll
2166 // to add ELF64-NOT: rldicl to the appropriate tests when this works.
2167 bool PPCFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2168 const LoadInst *LI) {
2169 // Verify we have a legal type before going any further.
2171 if (!isLoadTypeLegal(LI->getType(), VT))
2174 // Combine load followed by zero- or sign-extend.
2175 bool IsZExt = false;
2176 switch(MI->getOpcode()) {
2181 case PPC::RLDICL_32_64: {
2183 unsigned MB = MI->getOperand(3).getImm();
2184 if ((VT == MVT::i8 && MB <= 56) ||
2185 (VT == MVT::i16 && MB <= 48) ||
2186 (VT == MVT::i32 && MB <= 32))
2192 case PPC::RLWINM8: {
2194 unsigned MB = MI->getOperand(3).getImm();
2195 if ((VT == MVT::i8 && MB <= 24) ||
2196 (VT == MVT::i16 && MB <= 16))
2203 case PPC::EXTSB8_32_64:
2204 /* There is no sign-extending load-byte instruction. */
2209 case PPC::EXTSH8_32_64: {
2210 if (VT != MVT::i16 && VT != MVT::i8)
2216 case PPC::EXTSW_32_64: {
2217 if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8)
2223 // See if we can handle this address.
2225 if (!PPCComputeAddress(LI->getOperand(0), Addr))
2228 unsigned ResultReg = MI->getOperand(0).getReg();
2230 if (!PPCEmitLoad(VT, ResultReg, Addr, nullptr, IsZExt))
2233 MI->eraseFromParent();
2237 // Attempt to lower call arguments in a faster way than done by
2238 // the selection DAG code.
2239 bool PPCFastISel::fastLowerArguments() {
2240 // Defer to normal argument lowering for now. It's reasonably
2241 // efficient. Consider doing something like ARM to handle the
2242 // case where all args fit in registers, no varargs, no float
2247 // Handle materializing integer constants into a register. This is not
2248 // automatically generated for PowerPC, so must be explicitly created here.
2249 unsigned PPCFastISel::fastEmit_i(MVT Ty, MVT VT, unsigned Opc, uint64_t Imm) {
2251 if (Opc != ISD::Constant)
2254 // If we're using CR bit registers for i1 values, handle that as a special
2256 if (VT == MVT::i1 && PPCSubTarget->useCRBits()) {
2257 unsigned ImmReg = createResultReg(&PPC::CRBITRCRegClass);
2258 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2259 TII.get(Imm == 0 ? PPC::CRUNSET : PPC::CRSET), ImmReg);
2263 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2264 VT != MVT::i8 && VT != MVT::i1)
2267 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2268 &PPC::GPRCRegClass);
2270 return PPCMaterialize64BitInt(Imm, RC);
2272 return PPCMaterialize32BitInt(Imm, RC);
2275 // Override for ADDI and ADDI8 to set the correct register class
2276 // on RHS operand 0. The automatic infrastructure naively assumes
2277 // GPRC for i32 and G8RC for i64; the concept of "no R0" is lost
2278 // for these cases. At the moment, none of the other automatically
2279 // generated RI instructions require special treatment. However, once
2280 // SelectSelect is implemented, "isel" requires similar handling.
2282 // Also be conservative about the output register class. Avoid
2283 // assigning R0 or X0 to the output register for GPRC and G8RC
2284 // register classes, as any such result could be used in ADDI, etc.,
2285 // where those regs have another meaning.
2286 unsigned PPCFastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
2287 const TargetRegisterClass *RC,
2288 unsigned Op0, bool Op0IsKill,
2290 if (MachineInstOpcode == PPC::ADDI)
2291 MRI.setRegClass(Op0, &PPC::GPRC_and_GPRC_NOR0RegClass);
2292 else if (MachineInstOpcode == PPC::ADDI8)
2293 MRI.setRegClass(Op0, &PPC::G8RC_and_G8RC_NOX0RegClass);
2295 const TargetRegisterClass *UseRC =
2296 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2297 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2299 return FastISel::fastEmitInst_ri(MachineInstOpcode, UseRC,
2300 Op0, Op0IsKill, Imm);
2303 // Override for instructions with one register operand to avoid use of
2304 // R0/X0. The automatic infrastructure isn't aware of the context so
2305 // we must be conservative.
2306 unsigned PPCFastISel::fastEmitInst_r(unsigned MachineInstOpcode,
2307 const TargetRegisterClass* RC,
2308 unsigned Op0, bool Op0IsKill) {
2309 const TargetRegisterClass *UseRC =
2310 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2311 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2313 return FastISel::fastEmitInst_r(MachineInstOpcode, UseRC, Op0, Op0IsKill);
2316 // Override for instructions with two register operands to avoid use
2317 // of R0/X0. The automatic infrastructure isn't aware of the context
2318 // so we must be conservative.
2319 unsigned PPCFastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
2320 const TargetRegisterClass* RC,
2321 unsigned Op0, bool Op0IsKill,
2322 unsigned Op1, bool Op1IsKill) {
2323 const TargetRegisterClass *UseRC =
2324 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2325 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2327 return FastISel::fastEmitInst_rr(MachineInstOpcode, UseRC, Op0, Op0IsKill,
2332 // Create the fast instruction selector for PowerPC64 ELF.
2333 FastISel *PPC::createFastISel(FunctionLoweringInfo &FuncInfo,
2334 const TargetLibraryInfo *LibInfo) {
2335 // Only available on 64-bit ELF for now.
2336 const PPCSubtarget &Subtarget = FuncInfo.MF->getSubtarget<PPCSubtarget>();
2337 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI())
2338 return new PPCFastISel(FuncInfo, LibInfo);