blob: 14a4b31710b4da189fca9d35c86509803076b637 [file] [log] [blame]
Bill Schmidt646cd792013-07-30 00:50:39 +00001//===-- PPCFastISel.cpp - PowerPC FastISel implementation -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "ppcfastisel"
17#include "PPC.h"
18#include "PPCISelLowering.h"
19#include "PPCSubtarget.h"
20#include "PPCTargetMachine.h"
21#include "MCTargetDesc/PPCPredicates.h"
22#include "llvm/ADT/Optional.h"
23#include "llvm/CodeGen/CallingConvLower.h"
24#include "llvm/CodeGen/FastISel.h"
25#include "llvm/CodeGen/FunctionLoweringInfo.h"
26#include "llvm/CodeGen/MachineConstantPool.h"
27#include "llvm/CodeGen/MachineFrameInfo.h"
28#include "llvm/CodeGen/MachineInstrBuilder.h"
29#include "llvm/CodeGen/MachineRegisterInfo.h"
30#include "llvm/IR/CallingConv.h"
31#include "llvm/IR/GlobalAlias.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Operator.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/GetElementPtrTypeIterator.h"
37#include "llvm/Target/TargetLowering.h"
38#include "llvm/Target/TargetMachine.h"
39
40using namespace llvm;
41
42namespace {
43
44typedef struct Address {
45 enum {
46 RegBase,
47 FrameIndexBase
48 } BaseType;
49
50 union {
51 unsigned Reg;
52 int FI;
53 } Base;
54
Bill Schmidt72489682013-08-30 02:29:45 +000055 long Offset;
Bill Schmidt646cd792013-07-30 00:50:39 +000056
57 // Innocuous defaults for our address.
58 Address()
59 : BaseType(RegBase), Offset(0) {
60 Base.Reg = 0;
61 }
62} Address;
63
64class PPCFastISel : public FastISel {
65
66 const TargetMachine &TM;
67 const TargetInstrInfo &TII;
68 const TargetLowering &TLI;
69 const PPCSubtarget &PPCSubTarget;
70 LLVMContext *Context;
71
72 public:
73 explicit PPCFastISel(FunctionLoweringInfo &FuncInfo,
74 const TargetLibraryInfo *LibInfo)
75 : FastISel(FuncInfo, LibInfo),
76 TM(FuncInfo.MF->getTarget()),
77 TII(*TM.getInstrInfo()),
78 TLI(*TM.getTargetLowering()),
79 PPCSubTarget(
80 *((static_cast<const PPCTargetMachine *>(&TM))->getSubtargetImpl())
81 ),
82 Context(&FuncInfo.Fn->getContext()) { }
83
84 // Backend specific FastISel code.
85 private:
86 virtual bool TargetSelectInstruction(const Instruction *I);
87 virtual unsigned TargetMaterializeConstant(const Constant *C);
88 virtual unsigned TargetMaterializeAlloca(const AllocaInst *AI);
89 virtual bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
90 const LoadInst *LI);
91 virtual bool FastLowerArguments();
Bill Schmidt3fad2bc2013-08-25 22:33:42 +000092 virtual unsigned FastEmit_i(MVT Ty, MVT RetTy, unsigned Opc, uint64_t Imm);
Bill Schmidt72489682013-08-30 02:29:45 +000093 virtual unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
94 const TargetRegisterClass *RC,
95 unsigned Op0, bool Op0IsKill,
96 uint64_t Imm);
97 virtual unsigned FastEmitInst_r(unsigned MachineInstOpcode,
98 const TargetRegisterClass *RC,
99 unsigned Op0, bool Op0IsKill);
100 virtual unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
101 const TargetRegisterClass *RC,
102 unsigned Op0, bool Op0IsKill,
103 unsigned Op1, bool Op1IsKill);
Bill Schmidt3fad2bc2013-08-25 22:33:42 +0000104
105 // Instruction selection routines.
106 private:
Bill Schmidt72489682013-08-30 02:29:45 +0000107 bool SelectLoad(const Instruction *I);
108 bool SelectStore(const Instruction *I);
Bill Schmidt3fad2bc2013-08-25 22:33:42 +0000109 bool SelectBranch(const Instruction *I);
110 bool SelectIndirectBr(const Instruction *I);
Bill Schmidt72489682013-08-30 02:29:45 +0000111 bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
Bill Schmidt055d2072013-08-26 19:42:51 +0000112 bool SelectRet(const Instruction *I);
113 bool SelectIntExt(const Instruction *I);
Bill Schmidt646cd792013-07-30 00:50:39 +0000114
115 // Utility routines.
116 private:
Bill Schmidt72489682013-08-30 02:29:45 +0000117 bool isTypeLegal(Type *Ty, MVT &VT);
118 bool isLoadTypeLegal(Type *Ty, MVT &VT);
Bill Schmidt3fad2bc2013-08-25 22:33:42 +0000119 bool PPCEmitCmp(const Value *Src1Value, const Value *Src2Value,
120 bool isZExt, unsigned DestReg);
Bill Schmidt72489682013-08-30 02:29:45 +0000121 bool PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
122 const TargetRegisterClass *RC, bool IsZExt = true,
123 unsigned FP64LoadOpc = PPC::LFD);
124 bool PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr);
125 bool PPCComputeAddress(const Value *Obj, Address &Addr);
126 void PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
127 unsigned &IndexReg);
Bill Schmidt3fad2bc2013-08-25 22:33:42 +0000128 bool PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
129 unsigned DestReg, bool IsZExt);
Bill Schmidt646cd792013-07-30 00:50:39 +0000130 unsigned PPCMaterializeFP(const ConstantFP *CFP, MVT VT);
Bill Schmidt72489682013-08-30 02:29:45 +0000131 unsigned PPCMaterializeGV(const GlobalValue *GV, MVT VT);
Bill Schmidt646cd792013-07-30 00:50:39 +0000132 unsigned PPCMaterializeInt(const Constant *C, MVT VT);
133 unsigned PPCMaterialize32BitInt(int64_t Imm,
134 const TargetRegisterClass *RC);
135 unsigned PPCMaterialize64BitInt(int64_t Imm,
136 const TargetRegisterClass *RC);
137
Bill Schmidt055d2072013-08-26 19:42:51 +0000138 // Call handling routines.
139 private:
140 CCAssignFn *usePPC32CCs(unsigned Flag);
141
Bill Schmidt646cd792013-07-30 00:50:39 +0000142 private:
143 #include "PPCGenFastISel.inc"
144
145};
146
147} // end anonymous namespace
148
Bill Schmidt055d2072013-08-26 19:42:51 +0000149#include "PPCGenCallingConv.inc"
150
151// Function whose sole purpose is to kill compiler warnings
152// stemming from unused functions included from PPCGenCallingConv.inc.
153CCAssignFn *PPCFastISel::usePPC32CCs(unsigned Flag) {
154 if (Flag == 1)
155 return CC_PPC32_SVR4;
156 else if (Flag == 2)
157 return CC_PPC32_SVR4_ByVal;
158 else if (Flag == 3)
159 return CC_PPC32_SVR4_VarArg;
160 else
161 return RetCC_PPC;
162}
163
Bill Schmidt3fad2bc2013-08-25 22:33:42 +0000164static Optional<PPC::Predicate> getComparePred(CmpInst::Predicate Pred) {
165 switch (Pred) {
166 // These are not representable with any single compare.
167 case CmpInst::FCMP_FALSE:
168 case CmpInst::FCMP_UEQ:
169 case CmpInst::FCMP_UGT:
170 case CmpInst::FCMP_UGE:
171 case CmpInst::FCMP_ULT:
172 case CmpInst::FCMP_ULE:
173 case CmpInst::FCMP_UNE:
174 case CmpInst::FCMP_TRUE:
175 default:
176 return Optional<PPC::Predicate>();
177
178 case CmpInst::FCMP_OEQ:
179 case CmpInst::ICMP_EQ:
180 return PPC::PRED_EQ;
181
182 case CmpInst::FCMP_OGT:
183 case CmpInst::ICMP_UGT:
184 case CmpInst::ICMP_SGT:
185 return PPC::PRED_GT;
186
187 case CmpInst::FCMP_OGE:
188 case CmpInst::ICMP_UGE:
189 case CmpInst::ICMP_SGE:
190 return PPC::PRED_GE;
191
192 case CmpInst::FCMP_OLT:
193 case CmpInst::ICMP_ULT:
194 case CmpInst::ICMP_SLT:
195 return PPC::PRED_LT;
196
197 case CmpInst::FCMP_OLE:
198 case CmpInst::ICMP_ULE:
199 case CmpInst::ICMP_SLE:
200 return PPC::PRED_LE;
201
202 case CmpInst::FCMP_ONE:
203 case CmpInst::ICMP_NE:
204 return PPC::PRED_NE;
205
206 case CmpInst::FCMP_ORD:
207 return PPC::PRED_NU;
208
209 case CmpInst::FCMP_UNO:
210 return PPC::PRED_UN;
211 }
212}
213
Bill Schmidt72489682013-08-30 02:29:45 +0000214// Determine whether the type Ty is simple enough to be handled by
215// fast-isel, and return its equivalent machine type in VT.
216// FIXME: Copied directly from ARM -- factor into base class?
217bool PPCFastISel::isTypeLegal(Type *Ty, MVT &VT) {
218 EVT Evt = TLI.getValueType(Ty, true);
219
220 // Only handle simple types.
221 if (Evt == MVT::Other || !Evt.isSimple()) return false;
222 VT = Evt.getSimpleVT();
223
224 // Handle all legal types, i.e. a register that will directly hold this
225 // value.
226 return TLI.isTypeLegal(VT);
227}
228
229// Determine whether the type Ty is simple enough to be handled by
230// fast-isel as a load target, and return its equivalent machine type in VT.
231bool PPCFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
232 if (isTypeLegal(Ty, VT)) return true;
233
234 // If this is a type than can be sign or zero-extended to a basic operation
235 // go ahead and accept it now.
236 if (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) {
237 return true;
238 }
239
240 return false;
241}
242
243// Given a value Obj, create an Address object Addr that represents its
244// address. Return false if we can't handle it.
245bool PPCFastISel::PPCComputeAddress(const Value *Obj, Address &Addr) {
246 const User *U = NULL;
247 unsigned Opcode = Instruction::UserOp1;
248 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
249 // Don't walk into other basic blocks unless the object is an alloca from
250 // another block, otherwise it may not have a virtual register assigned.
251 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
252 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
253 Opcode = I->getOpcode();
254 U = I;
255 }
256 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
257 Opcode = C->getOpcode();
258 U = C;
259 }
260
261 switch (Opcode) {
262 default:
263 break;
264 case Instruction::BitCast:
265 // Look through bitcasts.
266 return PPCComputeAddress(U->getOperand(0), Addr);
267 case Instruction::IntToPtr:
268 // Look past no-op inttoptrs.
269 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
270 return PPCComputeAddress(U->getOperand(0), Addr);
271 break;
272 case Instruction::PtrToInt:
273 // Look past no-op ptrtoints.
274 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
275 return PPCComputeAddress(U->getOperand(0), Addr);
276 break;
277 case Instruction::GetElementPtr: {
278 Address SavedAddr = Addr;
279 long TmpOffset = Addr.Offset;
280
281 // Iterate through the GEP folding the constants into offsets where
282 // we can.
283 gep_type_iterator GTI = gep_type_begin(U);
284 for (User::const_op_iterator II = U->op_begin() + 1, IE = U->op_end();
285 II != IE; ++II, ++GTI) {
286 const Value *Op = *II;
287 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
288 const StructLayout *SL = TD.getStructLayout(STy);
289 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
290 TmpOffset += SL->getElementOffset(Idx);
291 } else {
292 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
293 for (;;) {
294 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
295 // Constant-offset addressing.
296 TmpOffset += CI->getSExtValue() * S;
297 break;
298 }
299 if (isa<AddOperator>(Op) &&
300 (!isa<Instruction>(Op) ||
301 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
302 == FuncInfo.MBB) &&
303 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
304 // An add (in the same block) with a constant operand. Fold the
305 // constant.
306 ConstantInt *CI =
307 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
308 TmpOffset += CI->getSExtValue() * S;
309 // Iterate on the other operand.
310 Op = cast<AddOperator>(Op)->getOperand(0);
311 continue;
312 }
313 // Unsupported
314 goto unsupported_gep;
315 }
316 }
317 }
318
319 // Try to grab the base operand now.
320 Addr.Offset = TmpOffset;
321 if (PPCComputeAddress(U->getOperand(0), Addr)) return true;
322
323 // We failed, restore everything and try the other options.
324 Addr = SavedAddr;
325
326 unsupported_gep:
327 break;
328 }
329 case Instruction::Alloca: {
330 const AllocaInst *AI = cast<AllocaInst>(Obj);
331 DenseMap<const AllocaInst*, int>::iterator SI =
332 FuncInfo.StaticAllocaMap.find(AI);
333 if (SI != FuncInfo.StaticAllocaMap.end()) {
334 Addr.BaseType = Address::FrameIndexBase;
335 Addr.Base.FI = SI->second;
336 return true;
337 }
338 break;
339 }
340 }
341
342 // FIXME: References to parameters fall through to the behavior
343 // below. They should be able to reference a frame index since
344 // they are stored to the stack, so we can get "ld rx, offset(r1)"
345 // instead of "addi ry, r1, offset / ld rx, 0(ry)". Obj will
346 // just contain the parameter. Try to handle this with a FI.
347
348 // Try to get this in a register if nothing else has worked.
349 if (Addr.Base.Reg == 0)
350 Addr.Base.Reg = getRegForValue(Obj);
351
352 // Prevent assignment of base register to X0, which is inappropriate
353 // for loads and stores alike.
354 if (Addr.Base.Reg != 0)
355 MRI.setRegClass(Addr.Base.Reg, &PPC::G8RC_and_G8RC_NOX0RegClass);
356
357 return Addr.Base.Reg != 0;
358}
359
360// Fix up some addresses that can't be used directly. For example, if
361// an offset won't fit in an instruction field, we may need to move it
362// into an index register.
363void PPCFastISel::PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
364 unsigned &IndexReg) {
365
366 // Check whether the offset fits in the instruction field.
367 if (!isInt<16>(Addr.Offset))
368 UseOffset = false;
369
370 // If this is a stack pointer and the offset needs to be simplified then
371 // put the alloca address into a register, set the base type back to
372 // register and continue. This should almost never happen.
373 if (!UseOffset && Addr.BaseType == Address::FrameIndexBase) {
374 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
375 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDI8),
376 ResultReg).addFrameIndex(Addr.Base.FI).addImm(0);
377 Addr.Base.Reg = ResultReg;
378 Addr.BaseType = Address::RegBase;
379 }
380
381 if (!UseOffset) {
382 IntegerType *OffsetTy = ((VT == MVT::i32) ? Type::getInt32Ty(*Context)
383 : Type::getInt64Ty(*Context));
384 const ConstantInt *Offset =
385 ConstantInt::getSigned(OffsetTy, (int64_t)(Addr.Offset));
386 IndexReg = PPCMaterializeInt(Offset, MVT::i64);
387 assert(IndexReg && "Unexpected error in PPCMaterializeInt!");
388 }
389}
390
391// Emit a load instruction if possible, returning true if we succeeded,
392// otherwise false. See commentary below for how the register class of
393// the load is determined.
394bool PPCFastISel::PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
395 const TargetRegisterClass *RC,
396 bool IsZExt, unsigned FP64LoadOpc) {
397 unsigned Opc;
398 bool UseOffset = true;
399
400 // If ResultReg is given, it determines the register class of the load.
401 // Otherwise, RC is the register class to use. If the result of the
402 // load isn't anticipated in this block, both may be zero, in which
403 // case we must make a conservative guess. In particular, don't assign
404 // R0 or X0 to the result register, as the result may be used in a load,
405 // store, add-immediate, or isel that won't permit this. (Though
406 // perhaps the spill and reload of live-exit values would handle this?)
407 const TargetRegisterClass *UseRC =
408 (ResultReg ? MRI.getRegClass(ResultReg) :
409 (RC ? RC :
410 (VT == MVT::f64 ? &PPC::F8RCRegClass :
411 (VT == MVT::f32 ? &PPC::F4RCRegClass :
412 (VT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
413 &PPC::GPRC_and_GPRC_NOR0RegClass)))));
414
415 bool Is32BitInt = UseRC->hasSuperClassEq(&PPC::GPRCRegClass);
416
417 switch (VT.SimpleTy) {
418 default: // e.g., vector types not handled
419 return false;
420 case MVT::i8:
421 Opc = Is32BitInt ? PPC::LBZ : PPC::LBZ8;
422 break;
423 case MVT::i16:
424 Opc = (IsZExt ?
425 (Is32BitInt ? PPC::LHZ : PPC::LHZ8) :
426 (Is32BitInt ? PPC::LHA : PPC::LHA8));
427 break;
428 case MVT::i32:
429 Opc = (IsZExt ?
430 (Is32BitInt ? PPC::LWZ : PPC::LWZ8) :
431 (Is32BitInt ? PPC::LWA_32 : PPC::LWA));
432 if ((Opc == PPC::LWA || Opc == PPC::LWA_32) && ((Addr.Offset & 3) != 0))
433 UseOffset = false;
434 break;
435 case MVT::i64:
436 Opc = PPC::LD;
437 assert(UseRC->hasSuperClassEq(&PPC::G8RCRegClass) &&
438 "64-bit load with 32-bit target??");
439 UseOffset = ((Addr.Offset & 3) == 0);
440 break;
441 case MVT::f32:
442 Opc = PPC::LFS;
443 break;
444 case MVT::f64:
445 Opc = FP64LoadOpc;
446 break;
447 }
448
449 // If necessary, materialize the offset into a register and use
450 // the indexed form. Also handle stack pointers with special needs.
451 unsigned IndexReg = 0;
452 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
453 if (ResultReg == 0)
454 ResultReg = createResultReg(UseRC);
455
456 // Note: If we still have a frame index here, we know the offset is
457 // in range, as otherwise PPCSimplifyAddress would have converted it
458 // into a RegBase.
459 if (Addr.BaseType == Address::FrameIndexBase) {
460
461 MachineMemOperand *MMO =
462 FuncInfo.MF->getMachineMemOperand(
463 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
464 MachineMemOperand::MOLoad, MFI.getObjectSize(Addr.Base.FI),
465 MFI.getObjectAlignment(Addr.Base.FI));
466
467 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
468 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
469
470 // Base reg with offset in range.
471 } else if (UseOffset) {
472
473 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
474 .addImm(Addr.Offset).addReg(Addr.Base.Reg);
475
476 // Indexed form.
477 } else {
478 // Get the RR opcode corresponding to the RI one. FIXME: It would be
479 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
480 // is hard to get at.
481 switch (Opc) {
482 default: llvm_unreachable("Unexpected opcode!");
483 case PPC::LBZ: Opc = PPC::LBZX; break;
484 case PPC::LBZ8: Opc = PPC::LBZX8; break;
485 case PPC::LHZ: Opc = PPC::LHZX; break;
486 case PPC::LHZ8: Opc = PPC::LHZX8; break;
487 case PPC::LHA: Opc = PPC::LHAX; break;
488 case PPC::LHA8: Opc = PPC::LHAX8; break;
489 case PPC::LWZ: Opc = PPC::LWZX; break;
490 case PPC::LWZ8: Opc = PPC::LWZX8; break;
491 case PPC::LWA: Opc = PPC::LWAX; break;
492 case PPC::LWA_32: Opc = PPC::LWAX_32; break;
493 case PPC::LD: Opc = PPC::LDX; break;
494 case PPC::LFS: Opc = PPC::LFSX; break;
495 case PPC::LFD: Opc = PPC::LFDX; break;
496 }
497 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
498 .addReg(Addr.Base.Reg).addReg(IndexReg);
499 }
500
501 return true;
502}
503
504// Attempt to fast-select a load instruction.
505bool PPCFastISel::SelectLoad(const Instruction *I) {
506 // FIXME: No atomic loads are supported.
507 if (cast<LoadInst>(I)->isAtomic())
508 return false;
509
510 // Verify we have a legal type before going any further.
511 MVT VT;
512 if (!isLoadTypeLegal(I->getType(), VT))
513 return false;
514
515 // See if we can handle this address.
516 Address Addr;
517 if (!PPCComputeAddress(I->getOperand(0), Addr))
518 return false;
519
520 // Look at the currently assigned register for this instruction
521 // to determine the required register class. This is necessary
522 // to constrain RA from using R0/X0 when this is not legal.
523 unsigned AssignedReg = FuncInfo.ValueMap[I];
524 const TargetRegisterClass *RC =
525 AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
526
527 unsigned ResultReg = 0;
528 if (!PPCEmitLoad(VT, ResultReg, Addr, RC))
529 return false;
530 UpdateValueMap(I, ResultReg);
531 return true;
532}
533
534// Emit a store instruction to store SrcReg at Addr.
535bool PPCFastISel::PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr) {
536 assert(SrcReg && "Nothing to store!");
537 unsigned Opc;
538 bool UseOffset = true;
539
540 const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
541 bool Is32BitInt = RC->hasSuperClassEq(&PPC::GPRCRegClass);
542
543 switch (VT.SimpleTy) {
544 default: // e.g., vector types not handled
545 return false;
546 case MVT::i8:
547 Opc = Is32BitInt ? PPC::STB : PPC::STB8;
548 break;
549 case MVT::i16:
550 Opc = Is32BitInt ? PPC::STH : PPC::STH8;
551 break;
552 case MVT::i32:
553 assert(Is32BitInt && "Not GPRC for i32??");
554 Opc = PPC::STW;
555 break;
556 case MVT::i64:
557 Opc = PPC::STD;
558 UseOffset = ((Addr.Offset & 3) == 0);
559 break;
560 case MVT::f32:
561 Opc = PPC::STFS;
562 break;
563 case MVT::f64:
564 Opc = PPC::STFD;
565 break;
566 }
567
568 // If necessary, materialize the offset into a register and use
569 // the indexed form. Also handle stack pointers with special needs.
570 unsigned IndexReg = 0;
571 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
572
573 // Note: If we still have a frame index here, we know the offset is
574 // in range, as otherwise PPCSimplifyAddress would have converted it
575 // into a RegBase.
576 if (Addr.BaseType == Address::FrameIndexBase) {
577 MachineMemOperand *MMO =
578 FuncInfo.MF->getMachineMemOperand(
579 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
580 MachineMemOperand::MOStore, MFI.getObjectSize(Addr.Base.FI),
581 MFI.getObjectAlignment(Addr.Base.FI));
582
583 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc)).addReg(SrcReg)
584 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
585
586 // Base reg with offset in range.
Bill Schmidt40433e52013-08-30 03:07:11 +0000587 } else if (UseOffset)
Bill Schmidt72489682013-08-30 02:29:45 +0000588 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
589 .addReg(SrcReg).addImm(Addr.Offset).addReg(Addr.Base.Reg);
590
591 // Indexed form.
Bill Schmidt40433e52013-08-30 03:07:11 +0000592 else {
Bill Schmidt72489682013-08-30 02:29:45 +0000593 // Get the RR opcode corresponding to the RI one. FIXME: It would be
594 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
595 // is hard to get at.
596 switch (Opc) {
597 default: llvm_unreachable("Unexpected opcode!");
598 case PPC::STB: Opc = PPC::STBX; break;
599 case PPC::STH : Opc = PPC::STHX; break;
600 case PPC::STW : Opc = PPC::STWX; break;
601 case PPC::STB8: Opc = PPC::STBX8; break;
602 case PPC::STH8: Opc = PPC::STHX8; break;
603 case PPC::STW8: Opc = PPC::STWX8; break;
604 case PPC::STD: Opc = PPC::STDX; break;
605 case PPC::STFS: Opc = PPC::STFSX; break;
606 case PPC::STFD: Opc = PPC::STFDX; break;
607 }
608 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
609 .addReg(SrcReg).addReg(Addr.Base.Reg).addReg(IndexReg);
610 }
611
612 return true;
613}
614
615// Attempt to fast-select a store instruction.
616bool PPCFastISel::SelectStore(const Instruction *I) {
617 Value *Op0 = I->getOperand(0);
618 unsigned SrcReg = 0;
619
620 // FIXME: No atomics loads are supported.
621 if (cast<StoreInst>(I)->isAtomic())
622 return false;
623
624 // Verify we have a legal type before going any further.
625 MVT VT;
626 if (!isLoadTypeLegal(Op0->getType(), VT))
627 return false;
628
629 // Get the value to be stored into a register.
630 SrcReg = getRegForValue(Op0);
631 if (SrcReg == 0)
632 return false;
633
634 // See if we can handle this address.
635 Address Addr;
636 if (!PPCComputeAddress(I->getOperand(1), Addr))
637 return false;
638
639 if (!PPCEmitStore(VT, SrcReg, Addr))
640 return false;
641
642 return true;
643}
644
Bill Schmidt3fad2bc2013-08-25 22:33:42 +0000645// Attempt to fast-select a branch instruction.
646bool PPCFastISel::SelectBranch(const Instruction *I) {
647 const BranchInst *BI = cast<BranchInst>(I);
648 MachineBasicBlock *BrBB = FuncInfo.MBB;
649 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
650 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
651
652 // For now, just try the simplest case where it's fed by a compare.
653 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
654 Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
655 if (!OptPPCPred)
656 return false;
657
658 PPC::Predicate PPCPred = OptPPCPred.getValue();
659
660 // Take advantage of fall-through opportunities.
661 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
662 std::swap(TBB, FBB);
663 PPCPred = PPC::InvertPredicate(PPCPred);
664 }
665
666 unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
667
668 if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
669 CondReg))
670 return false;
671
672 BuildMI(*BrBB, FuncInfo.InsertPt, DL, TII.get(PPC::BCC))
673 .addImm(PPCPred).addReg(CondReg).addMBB(TBB);
674 FastEmitBranch(FBB, DL);
675 FuncInfo.MBB->addSuccessor(TBB);
676 return true;
677
678 } else if (const ConstantInt *CI =
679 dyn_cast<ConstantInt>(BI->getCondition())) {
680 uint64_t Imm = CI->getZExtValue();
681 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
682 FastEmitBranch(Target, DL);
683 return true;
684 }
685
686 // FIXME: ARM looks for a case where the block containing the compare
687 // has been split from the block containing the branch. If this happens,
688 // there is a vreg available containing the result of the compare. I'm
689 // not sure we can do much, as we've lost the predicate information with
690 // the compare instruction -- we have a 4-bit CR but don't know which bit
691 // to test here.
692 return false;
693}
694
695// Attempt to emit a compare of the two source values. Signed and unsigned
696// comparisons are supported. Return false if we can't handle it.
697bool PPCFastISel::PPCEmitCmp(const Value *SrcValue1, const Value *SrcValue2,
698 bool IsZExt, unsigned DestReg) {
699 Type *Ty = SrcValue1->getType();
700 EVT SrcEVT = TLI.getValueType(Ty, true);
701 if (!SrcEVT.isSimple())
702 return false;
703 MVT SrcVT = SrcEVT.getSimpleVT();
704
705 // See if operand 2 is an immediate encodeable in the compare.
706 // FIXME: Operands are not in canonical order at -O0, so an immediate
707 // operand in position 1 is a lost opportunity for now. We are
708 // similar to ARM in this regard.
709 long Imm = 0;
710 bool UseImm = false;
711
712 // Only 16-bit integer constants can be represented in compares for
713 // PowerPC. Others will be materialized into a register.
714 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(SrcValue2)) {
715 if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
716 SrcVT == MVT::i8 || SrcVT == MVT::i1) {
717 const APInt &CIVal = ConstInt->getValue();
718 Imm = (IsZExt) ? (long)CIVal.getZExtValue() : (long)CIVal.getSExtValue();
719 if ((IsZExt && isUInt<16>(Imm)) || (!IsZExt && isInt<16>(Imm)))
720 UseImm = true;
721 }
722 }
723
724 unsigned CmpOpc;
725 bool NeedsExt = false;
726 switch (SrcVT.SimpleTy) {
727 default: return false;
728 case MVT::f32:
729 CmpOpc = PPC::FCMPUS;
730 break;
731 case MVT::f64:
732 CmpOpc = PPC::FCMPUD;
733 break;
734 case MVT::i1:
735 case MVT::i8:
736 case MVT::i16:
737 NeedsExt = true;
738 // Intentional fall-through.
739 case MVT::i32:
740 if (!UseImm)
741 CmpOpc = IsZExt ? PPC::CMPLW : PPC::CMPW;
742 else
743 CmpOpc = IsZExt ? PPC::CMPLWI : PPC::CMPWI;
744 break;
745 case MVT::i64:
746 if (!UseImm)
747 CmpOpc = IsZExt ? PPC::CMPLD : PPC::CMPD;
748 else
749 CmpOpc = IsZExt ? PPC::CMPLDI : PPC::CMPDI;
750 break;
751 }
752
753 unsigned SrcReg1 = getRegForValue(SrcValue1);
754 if (SrcReg1 == 0)
755 return false;
756
757 unsigned SrcReg2 = 0;
758 if (!UseImm) {
759 SrcReg2 = getRegForValue(SrcValue2);
760 if (SrcReg2 == 0)
761 return false;
762 }
763
764 if (NeedsExt) {
765 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
766 if (!PPCEmitIntExt(SrcVT, SrcReg1, MVT::i32, ExtReg, IsZExt))
767 return false;
768 SrcReg1 = ExtReg;
769
770 if (!UseImm) {
771 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
772 if (!PPCEmitIntExt(SrcVT, SrcReg2, MVT::i32, ExtReg, IsZExt))
773 return false;
774 SrcReg2 = ExtReg;
775 }
776 }
777
778 if (!UseImm)
779 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc), DestReg)
780 .addReg(SrcReg1).addReg(SrcReg2);
781 else
782 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc), DestReg)
783 .addReg(SrcReg1).addImm(Imm);
784
785 return true;
786}
787
Bill Schmidt72489682013-08-30 02:29:45 +0000788// Attempt to fast-select a binary integer operation that isn't already
789// handled automatically.
790bool PPCFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
791 EVT DestVT = TLI.getValueType(I->getType(), true);
792
793 // We can get here in the case when we have a binary operation on a non-legal
794 // type and the target independent selector doesn't know how to handle it.
795 if (DestVT != MVT::i16 && DestVT != MVT::i8)
796 return false;
797
798 // Look at the currently assigned register for this instruction
799 // to determine the required register class. If there is no register,
800 // make a conservative choice (don't assign R0).
801 unsigned AssignedReg = FuncInfo.ValueMap[I];
802 const TargetRegisterClass *RC =
803 (AssignedReg ? MRI.getRegClass(AssignedReg) :
804 &PPC::GPRC_and_GPRC_NOR0RegClass);
805 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
806
807 unsigned Opc;
808 switch (ISDOpcode) {
809 default: return false;
810 case ISD::ADD:
811 Opc = IsGPRC ? PPC::ADD4 : PPC::ADD8;
812 break;
813 case ISD::OR:
814 Opc = IsGPRC ? PPC::OR : PPC::OR8;
815 break;
816 case ISD::SUB:
817 Opc = IsGPRC ? PPC::SUBF : PPC::SUBF8;
818 break;
819 }
820
821 unsigned ResultReg = createResultReg(RC ? RC : &PPC::G8RCRegClass);
822 unsigned SrcReg1 = getRegForValue(I->getOperand(0));
823 if (SrcReg1 == 0) return false;
824
825 // Handle case of small immediate operand.
826 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(1))) {
827 const APInt &CIVal = ConstInt->getValue();
828 int Imm = (int)CIVal.getSExtValue();
829 bool UseImm = true;
830 if (isInt<16>(Imm)) {
831 switch (Opc) {
832 default:
833 llvm_unreachable("Missing case!");
834 case PPC::ADD4:
835 Opc = PPC::ADDI;
836 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
837 break;
838 case PPC::ADD8:
839 Opc = PPC::ADDI8;
840 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
841 break;
842 case PPC::OR:
843 Opc = PPC::ORI;
844 break;
845 case PPC::OR8:
846 Opc = PPC::ORI8;
847 break;
848 case PPC::SUBF:
849 if (Imm == -32768)
850 UseImm = false;
851 else {
852 Opc = PPC::ADDI;
853 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
854 Imm = -Imm;
855 }
856 break;
857 case PPC::SUBF8:
858 if (Imm == -32768)
859 UseImm = false;
860 else {
861 Opc = PPC::ADDI8;
862 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
863 Imm = -Imm;
864 }
865 break;
866 }
867
868 if (UseImm) {
869 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
870 .addReg(SrcReg1).addImm(Imm);
871 UpdateValueMap(I, ResultReg);
872 return true;
873 }
874 }
875 }
876
877 // Reg-reg case.
878 unsigned SrcReg2 = getRegForValue(I->getOperand(1));
879 if (SrcReg2 == 0) return false;
880
881 // Reverse operands for subtract-from.
882 if (ISDOpcode == ISD::SUB)
883 std::swap(SrcReg1, SrcReg2);
884
885 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
886 .addReg(SrcReg1).addReg(SrcReg2);
887 UpdateValueMap(I, ResultReg);
888 return true;
889}
890
Bill Schmidt055d2072013-08-26 19:42:51 +0000891// Attempt to fast-select a return instruction.
892bool PPCFastISel::SelectRet(const Instruction *I) {
893
894 if (!FuncInfo.CanLowerReturn)
895 return false;
896
897 const ReturnInst *Ret = cast<ReturnInst>(I);
898 const Function &F = *I->getParent()->getParent();
899
900 // Build a list of return value registers.
901 SmallVector<unsigned, 4> RetRegs;
902 CallingConv::ID CC = F.getCallingConv();
903
904 if (Ret->getNumOperands() > 0) {
905 SmallVector<ISD::OutputArg, 4> Outs;
906 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
907
908 // Analyze operands of the call, assigning locations to each operand.
909 SmallVector<CCValAssign, 16> ValLocs;
910 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs, *Context);
911 CCInfo.AnalyzeReturn(Outs, RetCC_PPC64_ELF_FIS);
912 const Value *RV = Ret->getOperand(0);
913
914 // FIXME: Only one output register for now.
915 if (ValLocs.size() > 1)
916 return false;
917
918 // Special case for returning a constant integer of any size.
919 // Materialize the constant as an i64 and copy it to the return
920 // register. This avoids an unnecessary extend or truncate.
921 if (isa<ConstantInt>(*RV)) {
922 const Constant *C = cast<Constant>(RV);
923 unsigned SrcReg = PPCMaterializeInt(C, MVT::i64);
924 unsigned RetReg = ValLocs[0].getLocReg();
925 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
926 RetReg).addReg(SrcReg);
927 RetRegs.push_back(RetReg);
928
929 } else {
930 unsigned Reg = getRegForValue(RV);
931
932 if (Reg == 0)
933 return false;
934
935 // Copy the result values into the output registers.
936 for (unsigned i = 0; i < ValLocs.size(); ++i) {
937
938 CCValAssign &VA = ValLocs[i];
939 assert(VA.isRegLoc() && "Can only return in registers!");
940 RetRegs.push_back(VA.getLocReg());
941 unsigned SrcReg = Reg + VA.getValNo();
942
943 EVT RVEVT = TLI.getValueType(RV->getType());
944 if (!RVEVT.isSimple())
945 return false;
946 MVT RVVT = RVEVT.getSimpleVT();
947 MVT DestVT = VA.getLocVT();
948
949 if (RVVT != DestVT && RVVT != MVT::i8 &&
950 RVVT != MVT::i16 && RVVT != MVT::i32)
951 return false;
952
953 if (RVVT != DestVT) {
954 switch (VA.getLocInfo()) {
955 default:
956 llvm_unreachable("Unknown loc info!");
957 case CCValAssign::Full:
958 llvm_unreachable("Full value assign but types don't match?");
959 case CCValAssign::AExt:
960 case CCValAssign::ZExt: {
961 const TargetRegisterClass *RC =
962 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
963 unsigned TmpReg = createResultReg(RC);
964 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, true))
965 return false;
966 SrcReg = TmpReg;
967 break;
968 }
969 case CCValAssign::SExt: {
970 const TargetRegisterClass *RC =
971 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
972 unsigned TmpReg = createResultReg(RC);
973 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, false))
974 return false;
975 SrcReg = TmpReg;
976 break;
977 }
978 }
979 }
980
981 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
982 TII.get(TargetOpcode::COPY), RetRegs[i])
983 .addReg(SrcReg);
984 }
985 }
986 }
987
988 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
989 TII.get(PPC::BLR));
990
991 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
992 MIB.addReg(RetRegs[i], RegState::Implicit);
993
994 return true;
995}
996
Bill Schmidt3fad2bc2013-08-25 22:33:42 +0000997// Attempt to emit an integer extend of SrcReg into DestReg. Both
998// signed and zero extensions are supported. Return false if we
Bill Schmidt055d2072013-08-26 19:42:51 +0000999// can't handle it.
Bill Schmidt3fad2bc2013-08-25 22:33:42 +00001000bool PPCFastISel::PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1001 unsigned DestReg, bool IsZExt) {
Bill Schmidt055d2072013-08-26 19:42:51 +00001002 if (DestVT != MVT::i32 && DestVT != MVT::i64)
1003 return false;
1004 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 && SrcVT != MVT::i32)
1005 return false;
1006
1007 // Signed extensions use EXTSB, EXTSH, EXTSW.
1008 if (!IsZExt) {
1009 unsigned Opc;
1010 if (SrcVT == MVT::i8)
1011 Opc = (DestVT == MVT::i32) ? PPC::EXTSB : PPC::EXTSB8_32_64;
1012 else if (SrcVT == MVT::i16)
1013 Opc = (DestVT == MVT::i32) ? PPC::EXTSH : PPC::EXTSH8_32_64;
1014 else {
1015 assert(DestVT == MVT::i64 && "Signed extend from i32 to i32??");
1016 Opc = PPC::EXTSW_32_64;
1017 }
1018 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1019 .addReg(SrcReg);
1020
1021 // Unsigned 32-bit extensions use RLWINM.
1022 } else if (DestVT == MVT::i32) {
1023 unsigned MB;
1024 if (SrcVT == MVT::i8)
1025 MB = 24;
1026 else {
1027 assert(SrcVT == MVT::i16 && "Unsigned extend from i32 to i32??");
1028 MB = 16;
1029 }
1030 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::RLWINM),
1031 DestReg)
1032 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB).addImm(/*ME=*/31);
1033
1034 // Unsigned 64-bit extensions use RLDICL (with a 32-bit source).
1035 } else {
1036 unsigned MB;
1037 if (SrcVT == MVT::i8)
1038 MB = 56;
1039 else if (SrcVT == MVT::i16)
1040 MB = 48;
1041 else
1042 MB = 32;
1043 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1044 TII.get(PPC::RLDICL_32_64), DestReg)
1045 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB);
1046 }
1047
1048 return true;
Bill Schmidt3fad2bc2013-08-25 22:33:42 +00001049}
1050
1051// Attempt to fast-select an indirect branch instruction.
1052bool PPCFastISel::SelectIndirectBr(const Instruction *I) {
1053 unsigned AddrReg = getRegForValue(I->getOperand(0));
1054 if (AddrReg == 0)
1055 return false;
1056
1057 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::MTCTR8))
1058 .addReg(AddrReg);
1059 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::BCTR8));
1060
1061 const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1062 for (unsigned i = 0, e = IB->getNumSuccessors(); i != e; ++i)
1063 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[IB->getSuccessor(i)]);
1064
1065 return true;
1066}
1067
Bill Schmidt055d2072013-08-26 19:42:51 +00001068// Attempt to fast-select an integer extend instruction.
1069bool PPCFastISel::SelectIntExt(const Instruction *I) {
1070 Type *DestTy = I->getType();
1071 Value *Src = I->getOperand(0);
1072 Type *SrcTy = Src->getType();
1073
1074 bool IsZExt = isa<ZExtInst>(I);
1075 unsigned SrcReg = getRegForValue(Src);
1076 if (!SrcReg) return false;
1077
1078 EVT SrcEVT, DestEVT;
1079 SrcEVT = TLI.getValueType(SrcTy, true);
1080 DestEVT = TLI.getValueType(DestTy, true);
1081 if (!SrcEVT.isSimple())
1082 return false;
1083 if (!DestEVT.isSimple())
1084 return false;
1085
1086 MVT SrcVT = SrcEVT.getSimpleVT();
1087 MVT DestVT = DestEVT.getSimpleVT();
1088
1089 // If we know the register class needed for the result of this
1090 // instruction, use it. Otherwise pick the register class of the
1091 // correct size that does not contain X0/R0, since we don't know
1092 // whether downstream uses permit that assignment.
1093 unsigned AssignedReg = FuncInfo.ValueMap[I];
1094 const TargetRegisterClass *RC =
1095 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1096 (DestVT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
1097 &PPC::GPRC_and_GPRC_NOR0RegClass));
1098 unsigned ResultReg = createResultReg(RC);
1099
1100 if (!PPCEmitIntExt(SrcVT, SrcReg, DestVT, ResultReg, IsZExt))
1101 return false;
1102
1103 UpdateValueMap(I, ResultReg);
1104 return true;
1105}
1106
Bill Schmidt646cd792013-07-30 00:50:39 +00001107// Attempt to fast-select an instruction that wasn't handled by
Bill Schmidt3fad2bc2013-08-25 22:33:42 +00001108// the table-generated machinery.
Bill Schmidt646cd792013-07-30 00:50:39 +00001109bool PPCFastISel::TargetSelectInstruction(const Instruction *I) {
Bill Schmidt3fad2bc2013-08-25 22:33:42 +00001110
1111 switch (I->getOpcode()) {
Bill Schmidt72489682013-08-30 02:29:45 +00001112 case Instruction::Load:
1113 return SelectLoad(I);
1114 case Instruction::Store:
1115 return SelectStore(I);
Bill Schmidt3fad2bc2013-08-25 22:33:42 +00001116 case Instruction::Br:
1117 return SelectBranch(I);
1118 case Instruction::IndirectBr:
1119 return SelectIndirectBr(I);
Bill Schmidt72489682013-08-30 02:29:45 +00001120 case Instruction::Add:
1121 return SelectBinaryIntOp(I, ISD::ADD);
1122 case Instruction::Or:
1123 return SelectBinaryIntOp(I, ISD::OR);
1124 case Instruction::Sub:
1125 return SelectBinaryIntOp(I, ISD::SUB);
Bill Schmidt055d2072013-08-26 19:42:51 +00001126 case Instruction::Ret:
1127 return SelectRet(I);
1128 case Instruction::ZExt:
1129 case Instruction::SExt:
1130 return SelectIntExt(I);
Bill Schmidt3fad2bc2013-08-25 22:33:42 +00001131 // Here add other flavors of Instruction::XXX that automated
1132 // cases don't catch. For example, switches are terminators
1133 // that aren't yet handled.
1134 default:
1135 break;
1136 }
1137 return false;
Bill Schmidt646cd792013-07-30 00:50:39 +00001138}
1139
1140// Materialize a floating-point constant into a register, and return
1141// the register number (or zero if we failed to handle it).
1142unsigned PPCFastISel::PPCMaterializeFP(const ConstantFP *CFP, MVT VT) {
1143 // No plans to handle long double here.
1144 if (VT != MVT::f32 && VT != MVT::f64)
1145 return 0;
1146
1147 // All FP constants are loaded from the constant pool.
1148 unsigned Align = TD.getPrefTypeAlignment(CFP->getType());
1149 assert(Align > 0 && "Unexpectedly missing alignment information!");
1150 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
1151 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
1152 CodeModel::Model CModel = TM.getCodeModel();
1153
1154 MachineMemOperand *MMO =
1155 FuncInfo.MF->getMachineMemOperand(
1156 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
1157 (VT == MVT::f32) ? 4 : 8, Align);
1158
Bill Schmidt3fad2bc2013-08-25 22:33:42 +00001159 unsigned Opc = (VT == MVT::f32) ? PPC::LFS : PPC::LFD;
1160 unsigned TmpReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1161
1162 // For small code model, generate a LF[SD](0, LDtocCPT(Idx, X2)).
1163 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault) {
Bill Schmidt646cd792013-07-30 00:50:39 +00001164 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocCPT),
Bill Schmidt3fad2bc2013-08-25 22:33:42 +00001165 TmpReg)
1166 .addConstantPoolIndex(Idx).addReg(PPC::X2);
1167 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1168 .addImm(0).addReg(TmpReg).addMemOperand(MMO);
1169 } else {
Bill Schmidt646cd792013-07-30 00:50:39 +00001170 // Otherwise we generate LF[SD](Idx[lo], ADDIStocHA(X2, Idx)).
Bill Schmidt646cd792013-07-30 00:50:39 +00001171 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDIStocHA),
1172 TmpReg).addReg(PPC::X2).addConstantPoolIndex(Idx);
1173 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1174 .addConstantPoolIndex(Idx, 0, PPCII::MO_TOC_LO)
1175 .addReg(TmpReg)
1176 .addMemOperand(MMO);
1177 }
1178
1179 return DestReg;
1180}
1181
Bill Schmidt72489682013-08-30 02:29:45 +00001182// Materialize the address of a global value into a register, and return
1183// the register number (or zero if we failed to handle it).
1184unsigned PPCFastISel::PPCMaterializeGV(const GlobalValue *GV, MVT VT) {
1185 assert(VT == MVT::i64 && "Non-address!");
1186 const TargetRegisterClass *RC = &PPC::G8RC_and_G8RC_NOX0RegClass;
1187 unsigned DestReg = createResultReg(RC);
1188
1189 // Global values may be plain old object addresses, TLS object
1190 // addresses, constant pool entries, or jump tables. How we generate
1191 // code for these may depend on small, medium, or large code model.
1192 CodeModel::Model CModel = TM.getCodeModel();
1193
1194 // FIXME: Jump tables are not yet required because fast-isel doesn't
1195 // handle switches; if that changes, we need them as well. For now,
1196 // what follows assumes everything's a generic (or TLS) global address.
1197 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1198 if (!GVar) {
1199 // If GV is an alias, use the aliasee for determining thread-locality.
1200 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1201 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
1202 assert((GVar || isa<Function>(GV)) && "Unexpected GV subclass!");
1203 }
1204
1205 // FIXME: We don't yet handle the complexity of TLS.
1206 bool IsTLS = GVar && GVar->isThreadLocal();
1207 if (IsTLS)
1208 return 0;
1209
1210 // For small code model, generate a simple TOC load.
1211 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault)
1212 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtoc), DestReg)
1213 .addGlobalAddress(GV).addReg(PPC::X2);
1214 else {
1215 // If the address is an externally defined symbol, a symbol with
1216 // common or externally available linkage, a function address, or a
1217 // jump table address (not yet needed), or if we are generating code
1218 // for large code model, we generate:
1219 // LDtocL(GV, ADDIStocHA(%X2, GV))
1220 // Otherwise we generate:
1221 // ADDItocL(ADDIStocHA(%X2, GV), GV)
1222 // Either way, start with the ADDIStocHA:
1223 unsigned HighPartReg = createResultReg(RC);
1224 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDIStocHA),
1225 HighPartReg).addReg(PPC::X2).addGlobalAddress(GV);
1226
1227 // !GVar implies a function address. An external variable is one
1228 // without an initializer.
1229 // If/when switches are implemented, jump tables should be handled
1230 // on the "if" path here.
1231 if (CModel == CodeModel::Large || !GVar || !GVar->hasInitializer() ||
1232 GVar->hasCommonLinkage() || GVar->hasAvailableExternallyLinkage())
1233 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocL),
1234 DestReg).addGlobalAddress(GV).addReg(HighPartReg);
1235 else
1236 // Otherwise generate the ADDItocL.
1237 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDItocL),
1238 DestReg).addReg(HighPartReg).addGlobalAddress(GV);
1239 }
1240
1241 return DestReg;
1242}
1243
Bill Schmidt646cd792013-07-30 00:50:39 +00001244// Materialize a 32-bit integer constant into a register, and return
1245// the register number (or zero if we failed to handle it).
1246unsigned PPCFastISel::PPCMaterialize32BitInt(int64_t Imm,
1247 const TargetRegisterClass *RC) {
1248 unsigned Lo = Imm & 0xFFFF;
1249 unsigned Hi = (Imm >> 16) & 0xFFFF;
1250
1251 unsigned ResultReg = createResultReg(RC);
1252 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1253
1254 if (isInt<16>(Imm))
1255 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1256 TII.get(IsGPRC ? PPC::LI : PPC::LI8), ResultReg)
1257 .addImm(Imm);
1258 else if (Lo) {
1259 // Both Lo and Hi have nonzero bits.
1260 unsigned TmpReg = createResultReg(RC);
1261 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1262 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), TmpReg)
1263 .addImm(Hi);
1264 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1265 TII.get(IsGPRC ? PPC::ORI : PPC::ORI8), ResultReg)
1266 .addReg(TmpReg).addImm(Lo);
1267 } else
1268 // Just Hi bits.
1269 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1270 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), ResultReg)
1271 .addImm(Hi);
1272
1273 return ResultReg;
1274}
1275
1276// Materialize a 64-bit integer constant into a register, and return
1277// the register number (or zero if we failed to handle it).
1278unsigned PPCFastISel::PPCMaterialize64BitInt(int64_t Imm,
1279 const TargetRegisterClass *RC) {
1280 unsigned Remainder = 0;
1281 unsigned Shift = 0;
1282
1283 // If the value doesn't fit in 32 bits, see if we can shift it
1284 // so that it fits in 32 bits.
1285 if (!isInt<32>(Imm)) {
1286 Shift = countTrailingZeros<uint64_t>(Imm);
1287 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
1288
1289 if (isInt<32>(ImmSh))
1290 Imm = ImmSh;
1291 else {
1292 Remainder = Imm;
1293 Shift = 32;
1294 Imm >>= 32;
1295 }
1296 }
1297
1298 // Handle the high-order 32 bits (if shifted) or the whole 32 bits
1299 // (if not shifted).
1300 unsigned TmpReg1 = PPCMaterialize32BitInt(Imm, RC);
1301 if (!Shift)
1302 return TmpReg1;
1303
1304 // If upper 32 bits were not zero, we've built them and need to shift
1305 // them into place.
1306 unsigned TmpReg2;
1307 if (Imm) {
1308 TmpReg2 = createResultReg(RC);
1309 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::RLDICR),
1310 TmpReg2).addReg(TmpReg1).addImm(Shift).addImm(63 - Shift);
1311 } else
1312 TmpReg2 = TmpReg1;
1313
1314 unsigned TmpReg3, Hi, Lo;
1315 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
1316 TmpReg3 = createResultReg(RC);
1317 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ORIS8),
1318 TmpReg3).addReg(TmpReg2).addImm(Hi);
1319 } else
1320 TmpReg3 = TmpReg2;
1321
1322 if ((Lo = Remainder & 0xFFFF)) {
1323 unsigned ResultReg = createResultReg(RC);
1324 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ORI8),
1325 ResultReg).addReg(TmpReg3).addImm(Lo);
1326 return ResultReg;
1327 }
1328
1329 return TmpReg3;
1330}
1331
1332
1333// Materialize an integer constant into a register, and return
1334// the register number (or zero if we failed to handle it).
1335unsigned PPCFastISel::PPCMaterializeInt(const Constant *C, MVT VT) {
1336
1337 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
1338 VT != MVT::i8 && VT != MVT::i1)
1339 return 0;
1340
1341 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
1342 &PPC::GPRCRegClass);
1343
1344 // If the constant is in range, use a load-immediate.
1345 const ConstantInt *CI = cast<ConstantInt>(C);
1346 if (isInt<16>(CI->getSExtValue())) {
1347 unsigned Opc = (VT == MVT::i64) ? PPC::LI8 : PPC::LI;
1348 unsigned ImmReg = createResultReg(RC);
1349 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ImmReg)
1350 .addImm(CI->getSExtValue());
1351 return ImmReg;
1352 }
1353
1354 // Construct the constant piecewise.
1355 int64_t Imm = CI->getZExtValue();
1356
1357 if (VT == MVT::i64)
1358 return PPCMaterialize64BitInt(Imm, RC);
1359 else if (VT == MVT::i32)
1360 return PPCMaterialize32BitInt(Imm, RC);
1361
1362 return 0;
1363}
1364
1365// Materialize a constant into a register, and return the register
1366// number (or zero if we failed to handle it).
1367unsigned PPCFastISel::TargetMaterializeConstant(const Constant *C) {
1368 EVT CEVT = TLI.getValueType(C->getType(), true);
1369
1370 // Only handle simple types.
1371 if (!CEVT.isSimple()) return 0;
1372 MVT VT = CEVT.getSimpleVT();
1373
1374 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1375 return PPCMaterializeFP(CFP, VT);
Bill Schmidt72489682013-08-30 02:29:45 +00001376 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1377 return PPCMaterializeGV(GV, VT);
Bill Schmidt646cd792013-07-30 00:50:39 +00001378 else if (isa<ConstantInt>(C))
1379 return PPCMaterializeInt(C, VT);
1380 // TBD: Global values.
1381
1382 return 0;
1383}
1384
1385// Materialize the address created by an alloca into a register, and
1386// return the register number (or zero if we failed to handle it). TBD.
1387unsigned PPCFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
1388 return AI && 0;
1389}
1390
Bill Schmidt72489682013-08-30 02:29:45 +00001391// Fold loads into extends when possible.
1392// FIXME: We can have multiple redundant extend/trunc instructions
1393// following a load. The folding only picks up one. Extend this
1394// to check subsequent instructions for the same pattern and remove
1395// them. Thus ResultReg should be the def reg for the last redundant
1396// instruction in a chain, and all intervening instructions can be
1397// removed from parent. Change test/CodeGen/PowerPC/fast-isel-fold.ll
1398// to add ELF64-NOT: rldicl to the appropriate tests when this works.
Bill Schmidt646cd792013-07-30 00:50:39 +00001399bool PPCFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
1400 const LoadInst *LI) {
Bill Schmidt72489682013-08-30 02:29:45 +00001401 // Verify we have a legal type before going any further.
1402 MVT VT;
1403 if (!isLoadTypeLegal(LI->getType(), VT))
1404 return false;
1405
1406 // Combine load followed by zero- or sign-extend.
1407 bool IsZExt = false;
1408 switch(MI->getOpcode()) {
1409 default:
1410 return false;
1411
1412 case PPC::RLDICL:
1413 case PPC::RLDICL_32_64: {
1414 IsZExt = true;
1415 unsigned MB = MI->getOperand(3).getImm();
1416 if ((VT == MVT::i8 && MB <= 56) ||
1417 (VT == MVT::i16 && MB <= 48) ||
1418 (VT == MVT::i32 && MB <= 32))
1419 break;
1420 return false;
1421 }
1422
1423 case PPC::RLWINM:
1424 case PPC::RLWINM8: {
1425 IsZExt = true;
1426 unsigned MB = MI->getOperand(3).getImm();
1427 if ((VT == MVT::i8 && MB <= 24) ||
1428 (VT == MVT::i16 && MB <= 16))
1429 break;
1430 return false;
1431 }
1432
1433 case PPC::EXTSB:
1434 case PPC::EXTSB8:
1435 case PPC::EXTSB8_32_64:
1436 /* There is no sign-extending load-byte instruction. */
1437 return false;
1438
1439 case PPC::EXTSH:
1440 case PPC::EXTSH8:
1441 case PPC::EXTSH8_32_64: {
1442 if (VT != MVT::i16 && VT != MVT::i8)
1443 return false;
1444 break;
1445 }
1446
1447 case PPC::EXTSW:
1448 case PPC::EXTSW_32_64: {
1449 if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8)
1450 return false;
1451 break;
1452 }
1453 }
1454
1455 // See if we can handle this address.
1456 Address Addr;
1457 if (!PPCComputeAddress(LI->getOperand(0), Addr))
1458 return false;
1459
1460 unsigned ResultReg = MI->getOperand(0).getReg();
1461
1462 if (!PPCEmitLoad(VT, ResultReg, Addr, 0, IsZExt))
1463 return false;
1464
1465 MI->eraseFromParent();
1466 return true;
Bill Schmidt646cd792013-07-30 00:50:39 +00001467}
1468
1469// Attempt to lower call arguments in a faster way than done by
1470// the selection DAG code.
1471bool PPCFastISel::FastLowerArguments() {
1472 // Defer to normal argument lowering for now. It's reasonably
1473 // efficient. Consider doing something like ARM to handle the
1474 // case where all args fit in registers, no varargs, no float
1475 // or vector args.
1476 return false;
1477}
1478
Bill Schmidt3fad2bc2013-08-25 22:33:42 +00001479// Handle materializing integer constants into a register. This is not
1480// automatically generated for PowerPC, so must be explicitly created here.
1481unsigned PPCFastISel::FastEmit_i(MVT Ty, MVT VT, unsigned Opc, uint64_t Imm) {
1482
1483 if (Opc != ISD::Constant)
1484 return 0;
1485
1486 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
1487 VT != MVT::i8 && VT != MVT::i1)
1488 return 0;
1489
1490 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
1491 &PPC::GPRCRegClass);
1492 if (VT == MVT::i64)
1493 return PPCMaterialize64BitInt(Imm, RC);
1494 else
1495 return PPCMaterialize32BitInt(Imm, RC);
1496}
1497
Bill Schmidt72489682013-08-30 02:29:45 +00001498// Override for ADDI and ADDI8 to set the correct register class
1499// on RHS operand 0. The automatic infrastructure naively assumes
1500// GPRC for i32 and G8RC for i64; the concept of "no R0" is lost
1501// for these cases. At the moment, none of the other automatically
1502// generated RI instructions require special treatment. However, once
1503// SelectSelect is implemented, "isel" requires similar handling.
1504//
1505// Also be conservative about the output register class. Avoid
1506// assigning R0 or X0 to the output register for GPRC and G8RC
1507// register classes, as any such result could be used in ADDI, etc.,
1508// where those regs have another meaning.
1509unsigned PPCFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
1510 const TargetRegisterClass *RC,
1511 unsigned Op0, bool Op0IsKill,
1512 uint64_t Imm) {
1513 if (MachineInstOpcode == PPC::ADDI)
1514 MRI.setRegClass(Op0, &PPC::GPRC_and_GPRC_NOR0RegClass);
1515 else if (MachineInstOpcode == PPC::ADDI8)
1516 MRI.setRegClass(Op0, &PPC::G8RC_and_G8RC_NOX0RegClass);
1517
1518 const TargetRegisterClass *UseRC =
1519 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
1520 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
1521
1522 return FastISel::FastEmitInst_ri(MachineInstOpcode, UseRC,
1523 Op0, Op0IsKill, Imm);
1524}
1525
1526// Override for instructions with one register operand to avoid use of
1527// R0/X0. The automatic infrastructure isn't aware of the context so
1528// we must be conservative.
1529unsigned PPCFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
1530 const TargetRegisterClass* RC,
1531 unsigned Op0, bool Op0IsKill) {
1532 const TargetRegisterClass *UseRC =
1533 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
1534 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
1535
1536 return FastISel::FastEmitInst_r(MachineInstOpcode, UseRC, Op0, Op0IsKill);
1537}
1538
1539// Override for instructions with two register operands to avoid use
1540// of R0/X0. The automatic infrastructure isn't aware of the context
1541// so we must be conservative.
1542unsigned PPCFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
1543 const TargetRegisterClass* RC,
1544 unsigned Op0, bool Op0IsKill,
1545 unsigned Op1, bool Op1IsKill) {
1546 const TargetRegisterClass *UseRC =
1547 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
1548 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
1549
1550 return FastISel::FastEmitInst_rr(MachineInstOpcode, UseRC, Op0, Op0IsKill,
1551 Op1, Op1IsKill);
1552}
1553
Bill Schmidt646cd792013-07-30 00:50:39 +00001554namespace llvm {
1555 // Create the fast instruction selector for PowerPC64 ELF.
1556 FastISel *PPC::createFastISel(FunctionLoweringInfo &FuncInfo,
1557 const TargetLibraryInfo *LibInfo) {
1558 const TargetMachine &TM = FuncInfo.MF->getTarget();
1559
1560 // Only available on 64-bit ELF for now.
1561 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
1562 if (Subtarget->isPPC64() && Subtarget->isSVR4ABI())
1563 return new PPCFastISel(FuncInfo, LibInfo);
1564
1565 return 0;
1566 }
1567}