1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a pattern matching instruction selector for PowerPC,
11 // converting from a legalized dag to a PPC dag.
13 //===----------------------------------------------------------------------===//
16 #include "PPCTargetMachine.h"
17 #include "PPCISelLowering.h"
18 #include "PPCHazardRecognizers.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Constants.h"
27 #include "llvm/GlobalValue.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
36 Statistic<> FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");
38 //===--------------------------------------------------------------------===//
39 /// PPCDAGToDAGISel - PPC specific code to select PPC machine
40 /// instructions for SelectionDAG operations.
42 class PPCDAGToDAGISel : public SelectionDAGISel {
44 PPCTargetLowering PPCLowering;
45 unsigned GlobalBaseReg;
47 PPCDAGToDAGISel(PPCTargetMachine &tm)
48 : SelectionDAGISel(PPCLowering), TM(tm),
49 PPCLowering(*TM.getTargetLowering()) {}
51 virtual bool runOnFunction(Function &Fn) {
52 // Make sure we re-emit a set of the global base reg if necessary
54 SelectionDAGISel::runOnFunction(Fn);
60 /// getI32Imm - Return a target constant with the specified value, of type
62 inline SDOperand getI32Imm(unsigned Imm) {
63 return CurDAG->getTargetConstant(Imm, MVT::i32);
66 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
67 /// base register. Return the virtual register that holds this value.
68 SDOperand getGlobalBaseReg();
70 // Select - Convert the specified operand from a target-independent to a
71 // target-specific node if it hasn't already been changed.
72 void Select(SDOperand &Result, SDOperand Op);
74 SDNode *SelectBitfieldInsert(SDNode *N);
76 /// SelectCC - Select a comparison of the specified values with the
77 /// specified condition code, returning the CR# of the expression.
78 SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
80 /// SelectAddrImm - Returns true if the address N can be represented by
81 /// a base register plus a signed 16-bit displacement [r+imm].
82 bool SelectAddrImm(SDOperand N, SDOperand &Disp, SDOperand &Base);
84 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
85 /// represented as an indexed [r+r] operation. Returns false if it can
86 /// be represented by [r+imm], which are preferred.
87 bool SelectAddrIdx(SDOperand N, SDOperand &Base, SDOperand &Index);
89 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
90 /// represented as an indexed [r+r] operation.
91 bool SelectAddrIdxOnly(SDOperand N, SDOperand &Base, SDOperand &Index);
93 /// SelectAddrImmShift - Returns true if the address N can be represented by
94 /// a base register plus a signed 14-bit displacement [r+imm*4]. Suitable
95 /// for use by STD and friends.
96 bool SelectAddrImmShift(SDOperand N, SDOperand &Disp, SDOperand &Base);
98 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
99 /// inline asm expressions.
100 virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
102 std::vector<SDOperand> &OutOps,
105 switch (ConstraintCode) {
106 default: return true;
108 if (!SelectAddrIdx(Op, Op0, Op1))
109 SelectAddrImm(Op, Op0, Op1);
111 case 'o': // offsetable
112 if (!SelectAddrImm(Op, Op0, Op1)) {
113 Select(Op0, Op); // r+0.
117 case 'v': // not offsetable
118 SelectAddrIdxOnly(Op, Op0, Op1);
122 OutOps.push_back(Op0);
123 OutOps.push_back(Op1);
127 SDOperand BuildSDIVSequence(SDNode *N);
128 SDOperand BuildUDIVSequence(SDNode *N);
130 /// InstructionSelectBasicBlock - This callback is invoked by
131 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
132 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
134 void InsertVRSaveCode(Function &Fn);
136 virtual const char *getPassName() const {
137 return "PowerPC DAG->DAG Pattern Instruction Selection";
140 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
141 /// this target when scheduling the DAG.
142 virtual HazardRecognizer *CreateTargetHazardRecognizer() {
143 // Should use subtarget info to pick the right hazard recognizer. For
144 // now, always return a PPC970 recognizer.
145 const TargetInstrInfo *II = PPCLowering.getTargetMachine().getInstrInfo();
146 assert(II && "No InstrInfo?");
147 return new PPCHazardRecognizer970(*II);
150 // Include the pieces autogenerated from the target description.
151 #include "PPCGenDAGISel.inc"
154 SDOperand SelectSETCC(SDOperand Op);
158 /// InstructionSelectBasicBlock - This callback is invoked by
159 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
160 void PPCDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
163 // The selection process is inherently a bottom-up recursive process (users
164 // select their uses before themselves). Given infinite stack space, we
165 // could just start selecting on the root and traverse the whole graph. In
166 // practice however, this causes us to run out of stack space on large basic
167 // blocks. To avoid this problem, select the entry node, then all its uses,
168 // iteratively instead of recursively.
169 std::vector<SDOperand> Worklist;
170 Worklist.push_back(DAG.getEntryNode());
172 // Note that we can do this in the PPC target (scanning forward across token
173 // chain edges) because no nodes ever get folded across these edges. On a
174 // target like X86 which supports load/modify/store operations, this would
175 // have to be more careful.
176 while (!Worklist.empty()) {
177 SDOperand Node = Worklist.back();
180 // Chose from the least deep of the top two nodes.
181 if (!Worklist.empty() &&
182 Worklist.back().Val->getNodeDepth() < Node.Val->getNodeDepth())
183 std::swap(Worklist.back(), Node);
185 if ((Node.Val->getOpcode() >= ISD::BUILTIN_OP_END &&
186 Node.Val->getOpcode() < PPCISD::FIRST_NUMBER) ||
187 CodeGenMap.count(Node)) continue;
189 for (SDNode::use_iterator UI = Node.Val->use_begin(),
190 E = Node.Val->use_end(); UI != E; ++UI) {
191 // Scan the values. If this use has a value that is a token chain, add it
194 for (unsigned i = 0, e = User->getNumValues(); i != e; ++i)
195 if (User->getValueType(i) == MVT::Other) {
196 Worklist.push_back(SDOperand(User, i));
201 // Finally, legalize this node.
206 // Select target instructions for the DAG.
207 DAG.setRoot(SelectRoot(DAG.getRoot()));
208 assert(InFlightSet.empty() && "ISel InFlightSet has not been emptied!");
212 DAG.RemoveDeadNodes();
214 // Emit machine code to BB.
215 ScheduleAndEmitDAG(DAG);
218 /// InsertVRSaveCode - Once the entire function has been instruction selected,
219 /// all virtual registers are created and all machine instructions are built,
220 /// check to see if we need to save/restore VRSAVE. If so, do it.
221 void PPCDAGToDAGISel::InsertVRSaveCode(Function &F) {
222 // Check to see if this function uses vector registers, which means we have to
223 // save and restore the VRSAVE register and update it with the regs we use.
225 // In this case, there will be virtual registers of vector type type created
226 // by the scheduler. Detect them now.
227 MachineFunction &Fn = MachineFunction::get(&F);
228 SSARegMap *RegMap = Fn.getSSARegMap();
229 bool HasVectorVReg = false;
230 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
231 e = RegMap->getLastVirtReg()+1; i != e; ++i)
232 if (RegMap->getRegClass(i) == &PPC::VRRCRegClass) {
233 HasVectorVReg = true;
236 if (!HasVectorVReg) return; // nothing to do.
238 // If we have a vector register, we want to emit code into the entry and exit
239 // blocks to save and restore the VRSAVE register. We do this here (instead
240 // of marking all vector instructions as clobbering VRSAVE) for two reasons:
242 // 1. This (trivially) reduces the load on the register allocator, by not
243 // having to represent the live range of the VRSAVE register.
244 // 2. This (more significantly) allows us to create a temporary virtual
245 // register to hold the saved VRSAVE value, allowing this temporary to be
246 // register allocated, instead of forcing it to be spilled to the stack.
248 // Create two vregs - one to hold the VRSAVE register that is live-in to the
249 // function and one for the value after having bits or'd into it.
250 unsigned InVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
251 unsigned UpdatedVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
253 MachineBasicBlock &EntryBB = *Fn.begin();
254 // Emit the following code into the entry block:
255 // InVRSAVE = MFVRSAVE
256 // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
257 // MTVRSAVE UpdatedVRSAVE
258 MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point
259 BuildMI(EntryBB, IP, PPC::MFVRSAVE, 0, InVRSAVE);
260 BuildMI(EntryBB, IP, PPC::UPDATE_VRSAVE, 1, UpdatedVRSAVE).addReg(InVRSAVE);
261 BuildMI(EntryBB, IP, PPC::MTVRSAVE, 1).addReg(UpdatedVRSAVE);
263 // Find all return blocks, outputting a restore in each epilog.
264 const TargetInstrInfo &TII = *TM.getInstrInfo();
265 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
266 if (!BB->empty() && TII.isReturn(BB->back().getOpcode())) {
267 IP = BB->end(); --IP;
269 // Skip over all terminator instructions, which are part of the return
271 MachineBasicBlock::iterator I2 = IP;
272 while (I2 != BB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
275 // Emit: MTVRSAVE InVRSave
276 BuildMI(*BB, IP, PPC::MTVRSAVE, 1).addReg(InVRSAVE);
282 /// getGlobalBaseReg - Output the instructions required to put the
283 /// base address to use for accessing globals into a register.
285 SDOperand PPCDAGToDAGISel::getGlobalBaseReg() {
286 if (!GlobalBaseReg) {
287 // Insert the set of GlobalBaseReg into the first MBB of the function
288 MachineBasicBlock &FirstMBB = BB->getParent()->front();
289 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
290 SSARegMap *RegMap = BB->getParent()->getSSARegMap();
291 // FIXME: when we get to LP64, we will need to create the appropriate
292 // type of register here.
293 GlobalBaseReg = RegMap->createVirtualRegister(PPC::GPRCRegisterClass);
294 BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
295 BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
297 return CurDAG->getRegister(GlobalBaseReg, MVT::i32);
301 // isIntImmediate - This method tests to see if a constant operand.
302 // If so Imm will receive the 32 bit value.
303 static bool isIntImmediate(SDNode *N, unsigned& Imm) {
304 if (N->getOpcode() == ISD::Constant) {
305 Imm = cast<ConstantSDNode>(N)->getValue();
311 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
312 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
313 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
314 // not, since all 1s are not contiguous.
315 static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
316 if (isShiftedMask_32(Val)) {
317 // look for the first non-zero bit
318 MB = CountLeadingZeros_32(Val);
319 // look for the first zero bit after the run of ones
320 ME = CountLeadingZeros_32((Val - 1) ^ Val);
323 Val = ~Val; // invert mask
324 if (isShiftedMask_32(Val)) {
325 // effectively look for the first zero bit
326 ME = CountLeadingZeros_32(Val) - 1;
327 // effectively look for the first one bit after the run of zeros
328 MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
336 // isRotateAndMask - Returns true if Mask and Shift can be folded into a rotate
337 // and mask opcode and mask operation.
338 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
339 unsigned &SH, unsigned &MB, unsigned &ME) {
340 // Don't even go down this path for i64, since different logic will be
341 // necessary for rldicl/rldicr/rldimi.
342 if (N->getValueType(0) != MVT::i32)
346 unsigned Indeterminant = ~0; // bit mask marking indeterminant results
347 unsigned Opcode = N->getOpcode();
348 if (N->getNumOperands() != 2 ||
349 !isIntImmediate(N->getOperand(1).Val, Shift) || (Shift > 31))
352 if (Opcode == ISD::SHL) {
353 // apply shift left to mask if it comes first
354 if (IsShiftMask) Mask = Mask << Shift;
355 // determine which bits are made indeterminant by shift
356 Indeterminant = ~(0xFFFFFFFFu << Shift);
357 } else if (Opcode == ISD::SRL) {
358 // apply shift right to mask if it comes first
359 if (IsShiftMask) Mask = Mask >> Shift;
360 // determine which bits are made indeterminant by shift
361 Indeterminant = ~(0xFFFFFFFFu >> Shift);
362 // adjust for the left rotate
368 // if the mask doesn't intersect any Indeterminant bits
369 if (Mask && !(Mask & Indeterminant)) {
371 // make sure the mask is still a mask (wrap arounds may not be)
372 return isRunOfOnes(Mask, MB, ME);
377 // isOpcWithIntImmediate - This method tests to see if the node is a specific
378 // opcode and that it has a immediate integer right operand.
379 // If so Imm will receive the 32 bit value.
380 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
381 return N->getOpcode() == Opc && isIntImmediate(N->getOperand(1).Val, Imm);
384 // isIntImmediate - This method tests to see if a constant operand.
385 // If so Imm will receive the 32 bit value.
386 static bool isIntImmediate(SDOperand N, unsigned& Imm) {
387 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
388 Imm = (unsigned)CN->getSignExtended();
394 /// SelectBitfieldInsert - turn an or of two masked values into
395 /// the rotate left word immediate then mask insert (rlwimi) instruction.
396 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
397 SDOperand Op0 = N->getOperand(0);
398 SDOperand Op1 = N->getOperand(1);
400 uint64_t LKZ, LKO, RKZ, RKO;
401 TLI.ComputeMaskedBits(Op0, 0xFFFFFFFFULL, LKZ, LKO);
402 TLI.ComputeMaskedBits(Op1, 0xFFFFFFFFULL, RKZ, RKO);
404 unsigned TargetMask = LKZ;
405 unsigned InsertMask = RKZ;
407 if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
408 unsigned Op0Opc = Op0.getOpcode();
409 unsigned Op1Opc = Op1.getOpcode();
410 unsigned Value, SH = 0;
411 TargetMask = ~TargetMask;
412 InsertMask = ~InsertMask;
414 // If the LHS has a foldable shift and the RHS does not, then swap it to the
415 // RHS so that we can fold the shift into the insert.
416 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
417 if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
418 Op0.getOperand(0).getOpcode() == ISD::SRL) {
419 if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
420 Op1.getOperand(0).getOpcode() != ISD::SRL) {
422 std::swap(Op0Opc, Op1Opc);
423 std::swap(TargetMask, InsertMask);
426 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
427 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
428 Op1.getOperand(0).getOpcode() != ISD::SRL) {
430 std::swap(Op0Opc, Op1Opc);
431 std::swap(TargetMask, InsertMask);
436 if (InsertMask && isRunOfOnes(InsertMask, MB, ME)) {
437 SDOperand Tmp1, Tmp2, Tmp3;
438 bool DisjointMask = (TargetMask ^ InsertMask) == 0xFFFFFFFF;
440 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
441 isIntImmediate(Op1.getOperand(1), Value)) {
442 Op1 = Op1.getOperand(0);
443 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
445 if (Op1Opc == ISD::AND) {
446 unsigned SHOpc = Op1.getOperand(0).getOpcode();
447 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) &&
448 isIntImmediate(Op1.getOperand(0).getOperand(1), Value)) {
449 Op1 = Op1.getOperand(0).getOperand(0);
450 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value;
452 Op1 = Op1.getOperand(0);
456 Tmp3 = (Op0Opc == ISD::AND && DisjointMask) ? Op0.getOperand(0) : Op0;
460 return CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2,
461 getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
467 /// SelectAddrImm - Returns true if the address N can be represented by
468 /// a base register plus a signed 16-bit displacement [r+imm].
469 bool PPCDAGToDAGISel::SelectAddrImm(SDOperand N, SDOperand &Disp,
471 // If this can be more profitably realized as r+r, fail.
472 if (SelectAddrIdx(N, Disp, Base))
475 if (N.getOpcode() == ISD::ADD) {
477 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm)) {
478 Disp = getI32Imm(imm & 0xFFFF);
479 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
480 Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
482 Base = N.getOperand(0);
484 return true; // [r+i]
485 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
486 // Match LOAD (ADD (X, Lo(G))).
487 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
488 && "Cannot handle constant offsets yet!");
489 Disp = N.getOperand(1).getOperand(0); // The global address.
490 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
491 Disp.getOpcode() == ISD::TargetConstantPool ||
492 Disp.getOpcode() == ISD::TargetJumpTable);
493 Base = N.getOperand(0);
494 return true; // [&g+r]
496 } else if (N.getOpcode() == ISD::OR) {
498 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm)) {
499 // If this is an or of disjoint bitfields, we can codegen this as an add
500 // (for better address arithmetic) if the LHS and RHS of the OR are
501 // provably disjoint.
502 uint64_t LHSKnownZero, LHSKnownOne;
503 PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
504 LHSKnownZero, LHSKnownOne);
505 if ((LHSKnownZero|~imm) == ~0U) {
506 // If all of the bits are known zero on the LHS or RHS, the add won't
508 Base = N.getOperand(0);
509 Disp = getI32Imm(imm & 0xFFFF);
513 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
514 // Loading from a constant address.
515 int Addr = (int)CN->getValue();
517 // If this address fits entirely in a 16-bit sext immediate field, codegen
519 if (Addr == (short)Addr) {
520 Disp = getI32Imm(Addr);
521 Base = CurDAG->getRegister(PPC::R0, MVT::i32);
525 // Otherwise, break this down into an LIS + disp.
526 Disp = getI32Imm((short)Addr);
527 Base = CurDAG->getConstant(Addr - (signed short)Addr, MVT::i32);
532 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
533 Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
536 return true; // [r+0]
539 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
540 /// represented as an indexed [r+r] operation. Returns false if it can
541 /// be represented by [r+imm], which are preferred.
542 bool PPCDAGToDAGISel::SelectAddrIdx(SDOperand N, SDOperand &Base,
545 if (N.getOpcode() == ISD::ADD) {
546 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm))
548 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
551 Base = N.getOperand(0);
552 Index = N.getOperand(1);
554 } else if (N.getOpcode() == ISD::OR) {
555 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm))
556 return false; // r+i can fold it if we can.
558 // If this is an or of disjoint bitfields, we can codegen this as an add
559 // (for better address arithmetic) if the LHS and RHS of the OR are provably
561 uint64_t LHSKnownZero, LHSKnownOne;
562 uint64_t RHSKnownZero, RHSKnownOne;
563 PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
564 LHSKnownZero, LHSKnownOne);
567 PPCLowering.ComputeMaskedBits(N.getOperand(1), ~0U,
568 RHSKnownZero, RHSKnownOne);
569 // If all of the bits are known zero on the LHS or RHS, the add won't
571 if ((LHSKnownZero | RHSKnownZero) == ~0U) {
572 Base = N.getOperand(0);
573 Index = N.getOperand(1);
582 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
583 /// represented as an indexed [r+r] operation.
584 bool PPCDAGToDAGISel::SelectAddrIdxOnly(SDOperand N, SDOperand &Base,
586 // Check to see if we can easily represent this as an [r+r] address. This
587 // will fail if it thinks that the address is more profitably represented as
588 // reg+imm, e.g. where imm = 0.
589 if (SelectAddrIdx(N, Base, Index))
592 // If the operand is an addition, always emit this as [r+r], since this is
593 // better (for code size, and execution, as the memop does the add for free)
594 // than emitting an explicit add.
595 if (N.getOpcode() == ISD::ADD) {
596 Base = N.getOperand(0);
597 Index = N.getOperand(1);
601 // Otherwise, do it the hard way, using R0 as the base register.
602 Base = CurDAG->getRegister(PPC::R0, MVT::i32);
607 /// SelectAddrImmShift - Returns true if the address N can be represented by
608 /// a base register plus a signed 14-bit displacement [r+imm*4]. Suitable
609 /// for use by STD and friends.
610 bool PPCDAGToDAGISel::SelectAddrImmShift(SDOperand N, SDOperand &Disp,
612 // If this can be more profitably realized as r+r, fail.
613 if (SelectAddrIdx(N, Disp, Base))
616 if (N.getOpcode() == ISD::ADD) {
618 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm) &&
620 Disp = getI32Imm((imm & 0xFFFF) >> 2);
621 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
622 Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
624 Base = N.getOperand(0);
626 return true; // [r+i]
627 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
628 // Match LOAD (ADD (X, Lo(G))).
629 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
630 && "Cannot handle constant offsets yet!");
631 Disp = N.getOperand(1).getOperand(0); // The global address.
632 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
633 Disp.getOpcode() == ISD::TargetConstantPool ||
634 Disp.getOpcode() == ISD::TargetJumpTable);
635 Base = N.getOperand(0);
636 return true; // [&g+r]
638 } else if (N.getOpcode() == ISD::OR) {
640 if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm) &&
642 // If this is an or of disjoint bitfields, we can codegen this as an add
643 // (for better address arithmetic) if the LHS and RHS of the OR are
644 // provably disjoint.
645 uint64_t LHSKnownZero, LHSKnownOne;
646 PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
647 LHSKnownZero, LHSKnownOne);
648 if ((LHSKnownZero|~imm) == ~0U) {
649 // If all of the bits are known zero on the LHS or RHS, the add won't
651 Base = N.getOperand(0);
652 Disp = getI32Imm((imm & 0xFFFF) >> 2);
656 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
657 // Loading from a constant address.
658 int Addr = (int)CN->getValue();
659 if ((Addr & 3) == 0) {
660 // If this address fits entirely in a 16-bit sext immediate field, codegen
662 if (Addr == (short)Addr) {
663 Disp = getI32Imm(Addr >> 2);
664 Base = CurDAG->getRegister(PPC::R0, MVT::i32);
668 // Otherwise, break this down into an LIS + disp.
669 Disp = getI32Imm((short)Addr >> 2);
670 Base = CurDAG->getConstant(Addr - (signed short)Addr, MVT::i32);
676 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
677 Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
680 return true; // [r+0]
684 /// SelectCC - Select a comparison of the specified values with the specified
685 /// condition code, returning the CR# of the expression.
686 SDOperand PPCDAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
688 // Always select the LHS.
691 // Use U to determine whether the SETCC immediate range is signed or not.
692 if (MVT::isInteger(LHS.getValueType())) {
693 bool U = ISD::isUnsignedIntSetCC(CC);
695 if (isIntImmediate(RHS, Imm) &&
696 ((U && isUInt16(Imm)) || (!U && isInt16(Imm))))
697 return SDOperand(CurDAG->getTargetNode(U ? PPC::CMPLWI : PPC::CMPWI,
698 MVT::i32, LHS, getI32Imm(Imm & 0xFFFF)), 0);
700 return SDOperand(CurDAG->getTargetNode(U ? PPC::CMPLW : PPC::CMPW, MVT::i32,
702 } else if (LHS.getValueType() == MVT::f32) {
704 return SDOperand(CurDAG->getTargetNode(PPC::FCMPUS, MVT::i32, LHS, RHS), 0);
707 return SDOperand(CurDAG->getTargetNode(PPC::FCMPUD, MVT::i32, LHS, RHS), 0);
711 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
713 static unsigned getBCCForSetCC(ISD::CondCode CC) {
715 default: assert(0 && "Unknown condition!"); abort();
716 case ISD::SETOEQ: // FIXME: This is incorrect see PR642.
718 case ISD::SETEQ: return PPC::BEQ;
719 case ISD::SETONE: // FIXME: This is incorrect see PR642.
721 case ISD::SETNE: return PPC::BNE;
722 case ISD::SETOLT: // FIXME: This is incorrect see PR642.
724 case ISD::SETLT: return PPC::BLT;
725 case ISD::SETOLE: // FIXME: This is incorrect see PR642.
727 case ISD::SETLE: return PPC::BLE;
728 case ISD::SETOGT: // FIXME: This is incorrect see PR642.
730 case ISD::SETGT: return PPC::BGT;
731 case ISD::SETOGE: // FIXME: This is incorrect see PR642.
733 case ISD::SETGE: return PPC::BGE;
735 case ISD::SETO: return PPC::BUN;
736 case ISD::SETUO: return PPC::BNU;
741 /// getCRIdxForSetCC - Return the index of the condition register field
742 /// associated with the SetCC condition, and whether or not the field is
743 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
744 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
746 default: assert(0 && "Unknown condition!"); abort();
747 case ISD::SETOLT: // FIXME: This is incorrect see PR642.
749 case ISD::SETLT: Inv = false; return 0;
750 case ISD::SETOGE: // FIXME: This is incorrect see PR642.
752 case ISD::SETGE: Inv = true; return 0;
753 case ISD::SETOGT: // FIXME: This is incorrect see PR642.
755 case ISD::SETGT: Inv = false; return 1;
756 case ISD::SETOLE: // FIXME: This is incorrect see PR642.
758 case ISD::SETLE: Inv = true; return 1;
759 case ISD::SETOEQ: // FIXME: This is incorrect see PR642.
761 case ISD::SETEQ: Inv = false; return 2;
762 case ISD::SETONE: // FIXME: This is incorrect see PR642.
764 case ISD::SETNE: Inv = true; return 2;
765 case ISD::SETO: Inv = true; return 3;
766 case ISD::SETUO: Inv = false; return 3;
771 SDOperand PPCDAGToDAGISel::SelectSETCC(SDOperand Op) {
774 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
775 if (isIntImmediate(N->getOperand(1), Imm)) {
776 // We can codegen setcc op, imm very efficiently compared to a brcond.
777 // Check for those cases here.
781 Select(Op, N->getOperand(0));
785 Op = SDOperand(CurDAG->getTargetNode(PPC::CNTLZW, MVT::i32, Op), 0);
786 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(27),
787 getI32Imm(5), getI32Imm(31));
790 SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
791 Op, getI32Imm(~0U)), 0);
792 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
796 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(1),
797 getI32Imm(31), getI32Imm(31));
800 SDOperand(CurDAG->getTargetNode(PPC::NEG, MVT::i32, Op), 0);
801 T = SDOperand(CurDAG->getTargetNode(PPC::ANDC, MVT::i32, T, Op), 0);
802 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, T, getI32Imm(1),
803 getI32Imm(31), getI32Imm(31));
806 } else if (Imm == ~0U) { // setcc op, -1
808 Select(Op, N->getOperand(0));
812 Op = SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
813 Op, getI32Imm(1)), 0);
814 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
815 SDOperand(CurDAG->getTargetNode(PPC::LI, MVT::i32,
819 Op = SDOperand(CurDAG->getTargetNode(PPC::NOR, MVT::i32, Op, Op), 0);
820 SDNode *AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
822 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDOperand(AD, 0),
823 Op, SDOperand(AD, 1));
826 SDOperand AD = SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32, Op,
828 SDOperand AN = SDOperand(CurDAG->getTargetNode(PPC::AND, MVT::i32, AD,
830 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, AN, getI32Imm(1),
831 getI32Imm(31), getI32Imm(31));
834 Op = SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Op,
835 getI32Imm(1), getI32Imm(31),
837 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1));
843 unsigned Idx = getCRIdxForSetCC(CC, Inv);
844 SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
847 // Force the ccreg into CR7.
848 SDOperand CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
850 SDOperand InFlag(0, 0); // Null incoming flag value.
851 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), CR7Reg, CCReg,
854 if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
855 IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, CR7Reg,
858 IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, CCReg), 0);
861 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, IntCR,
862 getI32Imm((32-(3-Idx)) & 31),
863 getI32Imm(31), getI32Imm(31));
866 SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, IntCR,
867 getI32Imm((32-(3-Idx)) & 31),
868 getI32Imm(31),getI32Imm(31)), 0);
869 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
874 // Select - Convert the specified operand from a target-independent to a
875 // target-specific node if it hasn't already been changed.
876 void PPCDAGToDAGISel::Select(SDOperand &Result, SDOperand Op) {
878 if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
879 N->getOpcode() < PPCISD::FIRST_NUMBER) {
881 return; // Already selected.
884 // If this has already been converted, use it.
885 std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
886 if (CGMI != CodeGenMap.end()) {
887 Result = CGMI->second;
891 switch (N->getOpcode()) {
894 Result = SelectSETCC(Op);
896 case PPCISD::GlobalBaseReg:
897 Result = getGlobalBaseReg();
900 case ISD::FrameIndex: {
901 int FI = cast<FrameIndexSDNode>(N)->getIndex();
902 if (N->hasOneUse()) {
903 Result = CurDAG->SelectNodeTo(N, PPC::ADDI, MVT::i32,
904 CurDAG->getTargetFrameIndex(FI, MVT::i32),
908 Result = CodeGenMap[Op] =
909 SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32,
910 CurDAG->getTargetFrameIndex(FI, MVT::i32),
917 Select(InFlag, N->getOperand(1));
918 // Use MFOCRF if supported.
919 if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
920 Result = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32,
921 N->getOperand(0), InFlag), 0);
923 Result = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, InFlag), 0);
924 CodeGenMap[Op] = Result;
929 // FIXME: since this depends on the setting of the carry flag from the srawi
930 // we should really be making notes about that for the scheduler.
931 // FIXME: It sure would be nice if we could cheaply recognize the
932 // srl/add/sra pattern the dag combiner will generate for this as
933 // sra/addze rather than having to handle sdiv ourselves. oh well.
935 if (isIntImmediate(N->getOperand(1), Imm)) {
937 Select(N0, N->getOperand(0));
938 if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
940 CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
941 N0, getI32Imm(Log2_32(Imm)));
942 Result = CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
943 SDOperand(Op, 0), SDOperand(Op, 1));
944 } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
946 CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
947 N0, getI32Imm(Log2_32(-Imm)));
949 SDOperand(CurDAG->getTargetNode(PPC::ADDZE, MVT::i32,
950 SDOperand(Op, 0), SDOperand(Op, 1)),
952 Result = CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
957 // Other cases are autogenerated.
962 // If this is an and of a value rotated between 0 and 31 bits and then and'd
963 // with a mask, emit rlwinm
964 if (isIntImmediate(N->getOperand(1), Imm) && (isShiftedMask_32(Imm) ||
965 isShiftedMask_32(~Imm))) {
968 if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
969 Select(Val, N->getOperand(0).getOperand(0));
970 } else if (Imm == 0) {
971 // AND X, 0 -> 0, not "rlwinm 32".
972 Select(Result, N->getOperand(1));
975 Select(Val, N->getOperand(0));
976 isRunOfOnes(Imm, MB, ME);
979 Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Val,
980 getI32Imm(SH), getI32Imm(MB),
984 // ISD::OR doesn't get all the bitfield insertion fun.
985 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
986 if (isIntImmediate(N->getOperand(1), Imm) &&
987 N->getOperand(0).getOpcode() == ISD::OR &&
988 isIntImmediate(N->getOperand(0).getOperand(1), Imm2)) {
991 if (isRunOfOnes(Imm, MB, ME)) {
992 SDOperand Tmp1, Tmp2;
993 Select(Tmp1, N->getOperand(0).getOperand(0));
994 Select(Tmp2, N->getOperand(0).getOperand(1));
995 Result = SDOperand(CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32,
997 getI32Imm(0), getI32Imm(MB),
1003 // Other cases are autogenerated.
1007 if (SDNode *I = SelectBitfieldInsert(N)) {
1008 Result = CodeGenMap[Op] = SDOperand(I, 0);
1012 // Other cases are autogenerated.
1015 unsigned Imm, SH, MB, ME;
1016 if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1017 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1019 Select(Val, N->getOperand(0).getOperand(0));
1020 Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32,
1021 Val, getI32Imm(SH), getI32Imm(MB),
1026 // Other cases are autogenerated.
1030 unsigned Imm, SH, MB, ME;
1031 if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1032 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1034 Select(Val, N->getOperand(0).getOperand(0));
1035 Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32,
1036 Val, getI32Imm(SH), getI32Imm(MB),
1041 // Other cases are autogenerated.
1044 case ISD::SELECT_CC: {
1045 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1047 // handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
1048 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1049 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1050 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1051 if (N1C->isNullValue() && N3C->isNullValue() &&
1052 N2C->getValue() == 1ULL && CC == ISD::SETNE) {
1054 Select(LHS, N->getOperand(0));
1056 CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1057 LHS, getI32Imm(~0U));
1058 Result = CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1059 SDOperand(Tmp, 0), LHS,
1064 SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
1065 unsigned BROpc = getBCCForSetCC(CC);
1067 bool isFP = MVT::isFloatingPoint(N->getValueType(0));
1068 unsigned SelectCCOp;
1069 if (MVT::isInteger(N->getValueType(0)))
1070 SelectCCOp = PPC::SELECT_CC_Int;
1071 else if (N->getValueType(0) == MVT::f32)
1072 SelectCCOp = PPC::SELECT_CC_F4;
1073 else if (N->getValueType(0) == MVT::f64)
1074 SelectCCOp = PPC::SELECT_CC_F8;
1076 SelectCCOp = PPC::SELECT_CC_VRRC;
1079 Select(N2, N->getOperand(2));
1080 Select(N3, N->getOperand(3));
1081 Result = CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), CCReg,
1082 N2, N3, getI32Imm(BROpc));
1087 Select(Chain, N->getOperand(0));
1088 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1089 SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
1090 Result = CurDAG->SelectNodeTo(N, PPC::COND_BRANCH, MVT::Other,
1091 CondCode, getI32Imm(getBCCForSetCC(CC)),
1092 N->getOperand(4), Chain);
1096 SDOperand Chain, Target;
1097 Select(Chain, N->getOperand(0));
1098 Select(Target,N->getOperand(1));
1099 Chain = SDOperand(CurDAG->getTargetNode(PPC::MTCTR, MVT::Other, Target,
1101 Result = CurDAG->SelectNodeTo(N, PPC::BCTR, MVT::Other, Chain);
1106 SelectCode(Result, Op);
1110 /// createPPCISelDag - This pass converts a legalized DAG into a
1111 /// PowerPC-specific DAG, ready for instruction scheduling.
1113 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
1114 return new PPCDAGToDAGISel(TM);