Match tablegen changes.
[oota-llvm.git] / lib / Target / PowerPC / PPCISelDAGToDAG.cpp
1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for PowerPC,
11 // converting from a legalized dag to a PPC dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PPC.h"
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"
31 #include "llvm/Support/Visibility.h"
32 #include <iostream>
33 #include <queue>
34 #include <set>
35 using namespace llvm;
36
37 namespace {
38   Statistic<> FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");
39     
40   //===--------------------------------------------------------------------===//
41   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
42   /// instructions for SelectionDAG operations.
43   ///
44   class VISIBILITY_HIDDEN PPCDAGToDAGISel : public SelectionDAGISel {
45     PPCTargetMachine &TM;
46     PPCTargetLowering PPCLowering;
47     unsigned GlobalBaseReg;
48   public:
49     PPCDAGToDAGISel(PPCTargetMachine &tm)
50       : SelectionDAGISel(PPCLowering), TM(tm),
51         PPCLowering(*TM.getTargetLowering()) {}
52     
53     virtual bool runOnFunction(Function &Fn) {
54       // Make sure we re-emit a set of the global base reg if necessary
55       GlobalBaseReg = 0;
56       SelectionDAGISel::runOnFunction(Fn);
57       
58       InsertVRSaveCode(Fn);
59       return true;
60     }
61    
62     /// getI32Imm - Return a target constant with the specified value, of type
63     /// i32.
64     inline SDOperand getI32Imm(unsigned Imm) {
65       return CurDAG->getTargetConstant(Imm, MVT::i32);
66     }
67
68     /// getI64Imm - Return a target constant with the specified value, of type
69     /// i64.
70     inline SDOperand getI64Imm(uint64_t Imm) {
71       return CurDAG->getTargetConstant(Imm, MVT::i64);
72     }
73     
74     /// getSmallIPtrImm - Return a target constant of pointer type.
75     inline SDOperand getSmallIPtrImm(unsigned Imm) {
76       return CurDAG->getTargetConstant(Imm, PPCLowering.getPointerTy());
77     }
78     
79     
80     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
81     /// base register.  Return the virtual register that holds this value.
82     SDOperand getGlobalBaseReg();
83     
84     // Select - Convert the specified operand from a target-independent to a
85     // target-specific node if it hasn't already been changed.
86     SDNode *Select(SDOperand &Result, SDOperand Op);
87     
88     SDNode *SelectBitfieldInsert(SDNode *N);
89
90     /// SelectCC - Select a comparison of the specified values with the
91     /// specified condition code, returning the CR# of the expression.
92     SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
93
94     /// SelectAddrImm - Returns true if the address N can be represented by
95     /// a base register plus a signed 16-bit displacement [r+imm].
96     bool SelectAddrImm(SDOperand N, SDOperand &Disp, SDOperand &Base);
97       
98     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
99     /// represented as an indexed [r+r] operation.  Returns false if it can
100     /// be represented by [r+imm], which are preferred.
101     bool SelectAddrIdx(SDOperand N, SDOperand &Base, SDOperand &Index);
102     
103     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
104     /// represented as an indexed [r+r] operation.
105     bool SelectAddrIdxOnly(SDOperand N, SDOperand &Base, SDOperand &Index);
106
107     /// SelectAddrImmShift - Returns true if the address N can be represented by
108     /// a base register plus a signed 14-bit displacement [r+imm*4].  Suitable
109     /// for use by STD and friends.
110     bool SelectAddrImmShift(SDOperand N, SDOperand &Disp, SDOperand &Base);
111     
112     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
113     /// inline asm expressions.
114     virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
115                                               char ConstraintCode,
116                                               std::vector<SDOperand> &OutOps,
117                                               SelectionDAG &DAG) {
118       SDOperand Op0, Op1;
119       switch (ConstraintCode) {
120       default: return true;
121       case 'm':   // memory
122         if (!SelectAddrIdx(Op, Op0, Op1))
123           SelectAddrImm(Op, Op0, Op1);
124         break;
125       case 'o':   // offsetable
126         if (!SelectAddrImm(Op, Op0, Op1)) {
127           AddToQueue(Op0, Op);     // r+0.
128           Op1 = getSmallIPtrImm(0);
129         }
130         break;
131       case 'v':   // not offsetable
132         SelectAddrIdxOnly(Op, Op0, Op1);
133         break;
134       }
135       
136       OutOps.push_back(Op0);
137       OutOps.push_back(Op1);
138       return false;
139     }
140     
141     SDOperand BuildSDIVSequence(SDNode *N);
142     SDOperand BuildUDIVSequence(SDNode *N);
143     
144     /// InstructionSelectBasicBlock - This callback is invoked by
145     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
146     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
147     
148     void InsertVRSaveCode(Function &Fn);
149
150     virtual const char *getPassName() const {
151       return "PowerPC DAG->DAG Pattern Instruction Selection";
152     } 
153     
154     /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
155     /// this target when scheduling the DAG.
156     virtual HazardRecognizer *CreateTargetHazardRecognizer() {
157       // Should use subtarget info to pick the right hazard recognizer.  For
158       // now, always return a PPC970 recognizer.
159       const TargetInstrInfo *II = PPCLowering.getTargetMachine().getInstrInfo();
160       assert(II && "No InstrInfo?");
161       return new PPCHazardRecognizer970(*II); 
162     }
163
164 // Include the pieces autogenerated from the target description.
165 #include "PPCGenDAGISel.inc"
166     
167 private:
168     SDOperand SelectSETCC(SDOperand Op);
169     SDNode *MySelect_PPCbctrl(SDOperand &Result, SDOperand N);
170     SDNode *MySelect_PPCcall(SDOperand &Result, SDOperand N);
171   };
172 }
173
174 /// InstructionSelectBasicBlock - This callback is invoked by
175 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
176 void PPCDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
177   DEBUG(BB->dump());
178
179   // Select target instructions for the DAG.
180   DAG.setRoot(SelectRoot(DAG.getRoot()));
181   DAG.RemoveDeadNodes();
182   
183   // Emit machine code to BB.
184   ScheduleAndEmitDAG(DAG);
185 }
186
187 /// InsertVRSaveCode - Once the entire function has been instruction selected,
188 /// all virtual registers are created and all machine instructions are built,
189 /// check to see if we need to save/restore VRSAVE.  If so, do it.
190 void PPCDAGToDAGISel::InsertVRSaveCode(Function &F) {
191   // Check to see if this function uses vector registers, which means we have to
192   // save and restore the VRSAVE register and update it with the regs we use.  
193   //
194   // In this case, there will be virtual registers of vector type type created
195   // by the scheduler.  Detect them now.
196   MachineFunction &Fn = MachineFunction::get(&F);
197   SSARegMap *RegMap = Fn.getSSARegMap();
198   bool HasVectorVReg = false;
199   for (unsigned i = MRegisterInfo::FirstVirtualRegister, 
200        e = RegMap->getLastVirtReg()+1; i != e; ++i)
201     if (RegMap->getRegClass(i) == &PPC::VRRCRegClass) {
202       HasVectorVReg = true;
203       break;
204     }
205   if (!HasVectorVReg) return;  // nothing to do.
206       
207   // If we have a vector register, we want to emit code into the entry and exit
208   // blocks to save and restore the VRSAVE register.  We do this here (instead
209   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
210   //
211   // 1. This (trivially) reduces the load on the register allocator, by not
212   //    having to represent the live range of the VRSAVE register.
213   // 2. This (more significantly) allows us to create a temporary virtual
214   //    register to hold the saved VRSAVE value, allowing this temporary to be
215   //    register allocated, instead of forcing it to be spilled to the stack.
216
217   // Create two vregs - one to hold the VRSAVE register that is live-in to the
218   // function and one for the value after having bits or'd into it.
219   unsigned InVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
220   unsigned UpdatedVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
221   
222   MachineBasicBlock &EntryBB = *Fn.begin();
223   // Emit the following code into the entry block:
224   // InVRSAVE = MFVRSAVE
225   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
226   // MTVRSAVE UpdatedVRSAVE
227   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
228   BuildMI(EntryBB, IP, PPC::MFVRSAVE, 0, InVRSAVE);
229   BuildMI(EntryBB, IP, PPC::UPDATE_VRSAVE, 1, UpdatedVRSAVE).addReg(InVRSAVE);
230   BuildMI(EntryBB, IP, PPC::MTVRSAVE, 1).addReg(UpdatedVRSAVE);
231   
232   // Find all return blocks, outputting a restore in each epilog.
233   const TargetInstrInfo &TII = *TM.getInstrInfo();
234   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
235     if (!BB->empty() && TII.isReturn(BB->back().getOpcode())) {
236       IP = BB->end(); --IP;
237       
238       // Skip over all terminator instructions, which are part of the return
239       // sequence.
240       MachineBasicBlock::iterator I2 = IP;
241       while (I2 != BB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
242         IP = I2;
243       
244       // Emit: MTVRSAVE InVRSave
245       BuildMI(*BB, IP, PPC::MTVRSAVE, 1).addReg(InVRSAVE);
246     }        
247   }
248 }
249
250
251 /// getGlobalBaseReg - Output the instructions required to put the
252 /// base address to use for accessing globals into a register.
253 ///
254 SDOperand PPCDAGToDAGISel::getGlobalBaseReg() {
255   if (!GlobalBaseReg) {
256     // Insert the set of GlobalBaseReg into the first MBB of the function
257     MachineBasicBlock &FirstMBB = BB->getParent()->front();
258     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
259     SSARegMap *RegMap = BB->getParent()->getSSARegMap();
260
261     if (PPCLowering.getPointerTy() == MVT::i32)
262       GlobalBaseReg = RegMap->createVirtualRegister(PPC::GPRCRegisterClass);
263     else
264       GlobalBaseReg = RegMap->createVirtualRegister(PPC::G8RCRegisterClass);
265     
266     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
267     BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
268   }
269   return CurDAG->getRegister(GlobalBaseReg, PPCLowering.getPointerTy());
270 }
271
272 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
273 /// or 64-bit immediate, and if the value can be accurately represented as a
274 /// sign extension from a 16-bit value.  If so, this returns true and the
275 /// immediate.
276 static bool isIntS16Immediate(SDNode *N, short &Imm) {
277   if (N->getOpcode() != ISD::Constant)
278     return false;
279
280   Imm = (short)cast<ConstantSDNode>(N)->getValue();
281   if (N->getValueType(0) == MVT::i32)
282     return Imm == (int32_t)cast<ConstantSDNode>(N)->getValue();
283   else
284     return Imm == (int64_t)cast<ConstantSDNode>(N)->getValue();
285 }
286
287 static bool isIntS16Immediate(SDOperand Op, short &Imm) {
288   return isIntS16Immediate(Op.Val, Imm);
289 }
290
291
292 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
293 /// operand. If so Imm will receive the 32-bit value.
294 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
295   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
296     Imm = cast<ConstantSDNode>(N)->getValue();
297     return true;
298   }
299   return false;
300 }
301
302 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
303 /// operand.  If so Imm will receive the 64-bit value.
304 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
305   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
306     Imm = cast<ConstantSDNode>(N)->getValue();
307     return true;
308   }
309   return false;
310 }
311
312 // isInt32Immediate - This method tests to see if a constant operand.
313 // If so Imm will receive the 32 bit value.
314 static bool isInt32Immediate(SDOperand N, unsigned &Imm) {
315   return isInt32Immediate(N.Val, Imm);
316 }
317
318
319 // isOpcWithIntImmediate - This method tests to see if the node is a specific
320 // opcode and that it has a immediate integer right operand.
321 // If so Imm will receive the 32 bit value.
322 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
323   return N->getOpcode() == Opc && isInt32Immediate(N->getOperand(1).Val, Imm);
324 }
325
326
327 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
328 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
329 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
330 // not, since all 1s are not contiguous.
331 static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
332   if (isShiftedMask_32(Val)) {
333     // look for the first non-zero bit
334     MB = CountLeadingZeros_32(Val);
335     // look for the first zero bit after the run of ones
336     ME = CountLeadingZeros_32((Val - 1) ^ Val);
337     return true;
338   } else {
339     Val = ~Val; // invert mask
340     if (isShiftedMask_32(Val)) {
341       // effectively look for the first zero bit
342       ME = CountLeadingZeros_32(Val) - 1;
343       // effectively look for the first one bit after the run of zeros
344       MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
345       return true;
346     }
347   }
348   // no run present
349   return false;
350 }
351
352 // isRotateAndMask - Returns true if Mask and Shift can be folded into a rotate
353 // and mask opcode and mask operation.
354 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
355                             unsigned &SH, unsigned &MB, unsigned &ME) {
356   // Don't even go down this path for i64, since different logic will be
357   // necessary for rldicl/rldicr/rldimi.
358   if (N->getValueType(0) != MVT::i32)
359     return false;
360
361   unsigned Shift  = 32;
362   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
363   unsigned Opcode = N->getOpcode();
364   if (N->getNumOperands() != 2 ||
365       !isInt32Immediate(N->getOperand(1).Val, Shift) || (Shift > 31))
366     return false;
367   
368   if (Opcode == ISD::SHL) {
369     // apply shift left to mask if it comes first
370     if (IsShiftMask) Mask = Mask << Shift;
371     // determine which bits are made indeterminant by shift
372     Indeterminant = ~(0xFFFFFFFFu << Shift);
373   } else if (Opcode == ISD::SRL) { 
374     // apply shift right to mask if it comes first
375     if (IsShiftMask) Mask = Mask >> Shift;
376     // determine which bits are made indeterminant by shift
377     Indeterminant = ~(0xFFFFFFFFu >> Shift);
378     // adjust for the left rotate
379     Shift = 32 - Shift;
380   } else {
381     return false;
382   }
383   
384   // if the mask doesn't intersect any Indeterminant bits
385   if (Mask && !(Mask & Indeterminant)) {
386     SH = Shift & 31;
387     // make sure the mask is still a mask (wrap arounds may not be)
388     return isRunOfOnes(Mask, MB, ME);
389   }
390   return false;
391 }
392
393 /// SelectBitfieldInsert - turn an or of two masked values into
394 /// the rotate left word immediate then mask insert (rlwimi) instruction.
395 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
396   SDOperand Op0 = N->getOperand(0);
397   SDOperand Op1 = N->getOperand(1);
398   
399   uint64_t LKZ, LKO, RKZ, RKO;
400   TLI.ComputeMaskedBits(Op0, 0xFFFFFFFFULL, LKZ, LKO);
401   TLI.ComputeMaskedBits(Op1, 0xFFFFFFFFULL, RKZ, RKO);
402   
403   unsigned TargetMask = LKZ;
404   unsigned InsertMask = RKZ;
405   
406   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
407     unsigned Op0Opc = Op0.getOpcode();
408     unsigned Op1Opc = Op1.getOpcode();
409     unsigned Value, SH = 0;
410     TargetMask = ~TargetMask;
411     InsertMask = ~InsertMask;
412
413     // If the LHS has a foldable shift and the RHS does not, then swap it to the
414     // RHS so that we can fold the shift into the insert.
415     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
416       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
417           Op0.getOperand(0).getOpcode() == ISD::SRL) {
418         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
419             Op1.getOperand(0).getOpcode() != ISD::SRL) {
420           std::swap(Op0, Op1);
421           std::swap(Op0Opc, Op1Opc);
422           std::swap(TargetMask, InsertMask);
423         }
424       }
425     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
426       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
427           Op1.getOperand(0).getOpcode() != ISD::SRL) {
428         std::swap(Op0, Op1);
429         std::swap(Op0Opc, Op1Opc);
430         std::swap(TargetMask, InsertMask);
431       }
432     }
433     
434     unsigned MB, ME;
435     if (InsertMask && isRunOfOnes(InsertMask, MB, ME)) {
436       SDOperand Tmp1, Tmp2, Tmp3;
437       bool DisjointMask = (TargetMask ^ InsertMask) == 0xFFFFFFFF;
438
439       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
440           isInt32Immediate(Op1.getOperand(1), Value)) {
441         Op1 = Op1.getOperand(0);
442         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
443       }
444       if (Op1Opc == ISD::AND) {
445         unsigned SHOpc = Op1.getOperand(0).getOpcode();
446         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) &&
447             isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
448           Op1 = Op1.getOperand(0).getOperand(0);
449           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
450         } else {
451           Op1 = Op1.getOperand(0);
452         }
453       }
454       
455       Tmp3 = (Op0Opc == ISD::AND && DisjointMask) ? Op0.getOperand(0) : Op0;
456       AddToQueue(Tmp1, Tmp3);
457       AddToQueue(Tmp2, Op1);
458       SH &= 31;
459       return CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2,
460                                    getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
461     }
462   }
463   return 0;
464 }
465
466 /// SelectAddrImm - Returns true if the address N can be represented by
467 /// a base register plus a signed 16-bit displacement [r+imm].
468 bool PPCDAGToDAGISel::SelectAddrImm(SDOperand N, SDOperand &Disp, 
469                                     SDOperand &Base) {
470   // If this can be more profitably realized as r+r, fail.
471   if (SelectAddrIdx(N, Disp, Base))
472     return false;
473
474   if (N.getOpcode() == ISD::ADD) {
475     short imm = 0;
476     if (isIntS16Immediate(N.getOperand(1), imm)) {
477       Disp = getI32Imm((int)imm & 0xFFFF);
478       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
479         Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
480       } else {
481         Base = N.getOperand(0);
482       }
483       return true; // [r+i]
484     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
485       // Match LOAD (ADD (X, Lo(G))).
486       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
487              && "Cannot handle constant offsets yet!");
488       Disp = N.getOperand(1).getOperand(0);  // The global address.
489       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
490              Disp.getOpcode() == ISD::TargetConstantPool ||
491              Disp.getOpcode() == ISD::TargetJumpTable);
492       Base = N.getOperand(0);
493       return true;  // [&g+r]
494     }
495   } else if (N.getOpcode() == ISD::OR) {
496     short imm = 0;
497     if (isIntS16Immediate(N.getOperand(1), imm)) {
498       // If this is an or of disjoint bitfields, we can codegen this as an add
499       // (for better address arithmetic) if the LHS and RHS of the OR are
500       // provably disjoint.
501       uint64_t LHSKnownZero, LHSKnownOne;
502       PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
503                                     LHSKnownZero, LHSKnownOne);
504       if ((LHSKnownZero|~(unsigned)imm) == ~0U) {
505         // If all of the bits are known zero on the LHS or RHS, the add won't
506         // carry.
507         Base = N.getOperand(0);
508         Disp = getI32Imm((int)imm & 0xFFFF);
509         return true;
510       }
511     }
512   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
513     // Loading from a constant address.
514
515     // If this address fits entirely in a 16-bit sext immediate field, codegen
516     // this as "d, 0"
517     short Imm;
518     if (isIntS16Immediate(CN, Imm)) {
519       Disp = CurDAG->getTargetConstant(Imm, CN->getValueType(0));
520       Base = CurDAG->getRegister(PPC::R0, CN->getValueType(0));
521       return true;
522     }
523
524     // FIXME: Handle small sext constant offsets in PPC64 mode also!
525     if (CN->getValueType(0) == MVT::i32) {
526       int Addr = (int)CN->getValue();
527     
528       // Otherwise, break this down into an LIS + disp.
529       Disp = getI32Imm((short)Addr);
530       Base = CurDAG->getConstant(Addr - (signed short)Addr, MVT::i32);
531       return true;
532     }
533   }
534   
535   Disp = getSmallIPtrImm(0);
536   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
537     Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
538   else
539     Base = N;
540   return true;      // [r+0]
541 }
542
543 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
544 /// represented as an indexed [r+r] operation.  Returns false if it can
545 /// be represented by [r+imm], which are preferred.
546 bool PPCDAGToDAGISel::SelectAddrIdx(SDOperand N, SDOperand &Base, 
547                                     SDOperand &Index) {
548   short imm = 0;
549   if (N.getOpcode() == ISD::ADD) {
550     if (isIntS16Immediate(N.getOperand(1), imm))
551       return false;    // r+i
552     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
553       return false;    // r+i
554     
555     Base = N.getOperand(0);
556     Index = N.getOperand(1);
557     return true;
558   } else if (N.getOpcode() == ISD::OR) {
559     if (isIntS16Immediate(N.getOperand(1), imm))
560       return false;    // r+i can fold it if we can.
561     
562     // If this is an or of disjoint bitfields, we can codegen this as an add
563     // (for better address arithmetic) if the LHS and RHS of the OR are provably
564     // disjoint.
565     uint64_t LHSKnownZero, LHSKnownOne;
566     uint64_t RHSKnownZero, RHSKnownOne;
567     PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
568                                   LHSKnownZero, LHSKnownOne);
569     
570     if (LHSKnownZero) {
571       PPCLowering.ComputeMaskedBits(N.getOperand(1), ~0U,
572                                     RHSKnownZero, RHSKnownOne);
573       // If all of the bits are known zero on the LHS or RHS, the add won't
574       // carry.
575       if ((LHSKnownZero | RHSKnownZero) == ~0U) {
576         Base = N.getOperand(0);
577         Index = N.getOperand(1);
578         return true;
579       }
580     }
581   }
582   
583   return false;
584 }
585
586 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
587 /// represented as an indexed [r+r] operation.
588 bool PPCDAGToDAGISel::SelectAddrIdxOnly(SDOperand N, SDOperand &Base, 
589                                         SDOperand &Index) {
590   // Check to see if we can easily represent this as an [r+r] address.  This
591   // will fail if it thinks that the address is more profitably represented as
592   // reg+imm, e.g. where imm = 0.
593   if (SelectAddrIdx(N, Base, Index))
594     return true;
595   
596   // If the operand is an addition, always emit this as [r+r], since this is
597   // better (for code size, and execution, as the memop does the add for free)
598   // than emitting an explicit add.
599   if (N.getOpcode() == ISD::ADD) {
600     Base = N.getOperand(0);
601     Index = N.getOperand(1);
602     return true;
603   }
604   
605   // Otherwise, do it the hard way, using R0 as the base register.
606   Base = CurDAG->getRegister(PPC::R0, N.getValueType());
607   Index = N;
608   return true;
609 }
610
611 /// SelectAddrImmShift - Returns true if the address N can be represented by
612 /// a base register plus a signed 14-bit displacement [r+imm*4].  Suitable
613 /// for use by STD and friends.
614 bool PPCDAGToDAGISel::SelectAddrImmShift(SDOperand N, SDOperand &Disp, 
615                                          SDOperand &Base) {
616   // If this can be more profitably realized as r+r, fail.
617   if (SelectAddrIdx(N, Disp, Base))
618     return false;
619   
620   if (N.getOpcode() == ISD::ADD) {
621     short imm = 0;
622     if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
623       Disp = getI32Imm(((int)imm & 0xFFFF) >> 2);
624       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
625         Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
626       } else {
627         Base = N.getOperand(0);
628       }
629       return true; // [r+i]
630     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
631       // Match LOAD (ADD (X, Lo(G))).
632       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
633              && "Cannot handle constant offsets yet!");
634       Disp = N.getOperand(1).getOperand(0);  // The global address.
635       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
636              Disp.getOpcode() == ISD::TargetConstantPool ||
637              Disp.getOpcode() == ISD::TargetJumpTable);
638       Base = N.getOperand(0);
639       return true;  // [&g+r]
640     }
641   } else if (N.getOpcode() == ISD::OR) {
642     short imm = 0;
643     if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
644       // If this is an or of disjoint bitfields, we can codegen this as an add
645       // (for better address arithmetic) if the LHS and RHS of the OR are
646       // provably disjoint.
647       uint64_t LHSKnownZero, LHSKnownOne;
648       PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
649                                     LHSKnownZero, LHSKnownOne);
650       if ((LHSKnownZero|~(unsigned)imm) == ~0U) {
651         // If all of the bits are known zero on the LHS or RHS, the add won't
652         // carry.
653         Base = N.getOperand(0);
654         Disp = getI32Imm(((int)imm & 0xFFFF) >> 2);
655         return true;
656       }
657     }
658   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
659     // Loading from a constant address.
660     
661     // If this address fits entirely in a 14-bit sext immediate field, codegen
662     // this as "d, 0"
663     short Imm;
664     if (isIntS16Immediate(CN, Imm)) {
665       Disp = getSmallIPtrImm((unsigned short)Imm >> 2);
666       Base = CurDAG->getRegister(PPC::R0, CN->getValueType(0));
667       return true;
668     }
669     
670     // FIXME: Handle small sext constant offsets in PPC64 mode also!
671     if (CN->getValueType(0) == MVT::i32) {
672       int Addr = (int)CN->getValue();
673       
674       // Otherwise, break this down into an LIS + disp.
675       Disp = getI32Imm((short)Addr >> 2);
676       Base = CurDAG->getConstant(Addr - (signed short)Addr, MVT::i32);
677       return true;
678     }
679   }
680   
681   Disp = getSmallIPtrImm(0);
682   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
683     Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
684   else
685     Base = N;
686   return true;      // [r+0]
687 }
688
689
690 /// SelectCC - Select a comparison of the specified values with the specified
691 /// condition code, returning the CR# of the expression.
692 SDOperand PPCDAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
693                                     ISD::CondCode CC) {
694   // Always select the LHS.
695   AddToQueue(LHS, LHS);
696   unsigned Opc;
697   
698   if (LHS.getValueType() == MVT::i32) {
699     unsigned Imm;
700     if (ISD::isUnsignedIntSetCC(CC)) {
701       if (isInt32Immediate(RHS, Imm) && isUInt16(Imm))
702         return SDOperand(CurDAG->getTargetNode(PPC::CMPLWI, MVT::i32, LHS,
703                                                getI32Imm(Imm & 0xFFFF)), 0);
704       Opc = PPC::CMPLW;
705     } else {
706       short SImm;
707       if (isIntS16Immediate(RHS, SImm))
708         return SDOperand(CurDAG->getTargetNode(PPC::CMPWI, MVT::i32, LHS,
709                                                getI32Imm((int)SImm & 0xFFFF)),
710                          0);
711       Opc = PPC::CMPW;
712     }
713   } else if (LHS.getValueType() == MVT::i64) {
714     uint64_t Imm;
715     if (ISD::isUnsignedIntSetCC(CC)) {
716       if (isInt64Immediate(RHS.Val, Imm) && isUInt16(Imm))
717         return SDOperand(CurDAG->getTargetNode(PPC::CMPLDI, MVT::i64, LHS,
718                                                getI64Imm(Imm & 0xFFFF)), 0);
719       Opc = PPC::CMPLD;
720     } else {
721       short SImm;
722       if (isIntS16Immediate(RHS, SImm))
723         return SDOperand(CurDAG->getTargetNode(PPC::CMPDI, MVT::i64, LHS,
724                                                getI64Imm((int)SImm & 0xFFFF)),
725                          0);
726       Opc = PPC::CMPD;
727     }
728   } else if (LHS.getValueType() == MVT::f32) {
729     Opc = PPC::FCMPUS;
730   } else {
731     assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
732     Opc = PPC::FCMPUD;
733   }
734   AddToQueue(RHS, RHS);
735   return SDOperand(CurDAG->getTargetNode(Opc, MVT::i32, LHS, RHS), 0);
736 }
737
738 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
739 /// to Condition.
740 static unsigned getBCCForSetCC(ISD::CondCode CC) {
741   switch (CC) {
742   default: assert(0 && "Unknown condition!"); abort();
743   case ISD::SETOEQ:    // FIXME: This is incorrect see PR642.
744   case ISD::SETUEQ:
745   case ISD::SETEQ:  return PPC::BEQ;
746   case ISD::SETONE:    // FIXME: This is incorrect see PR642.
747   case ISD::SETUNE:
748   case ISD::SETNE:  return PPC::BNE;
749   case ISD::SETOLT:    // FIXME: This is incorrect see PR642.
750   case ISD::SETULT:
751   case ISD::SETLT:  return PPC::BLT;
752   case ISD::SETOLE:    // FIXME: This is incorrect see PR642.
753   case ISD::SETULE:
754   case ISD::SETLE:  return PPC::BLE;
755   case ISD::SETOGT:    // FIXME: This is incorrect see PR642.
756   case ISD::SETUGT:
757   case ISD::SETGT:  return PPC::BGT;
758   case ISD::SETOGE:    // FIXME: This is incorrect see PR642.
759   case ISD::SETUGE:
760   case ISD::SETGE:  return PPC::BGE;
761     
762   case ISD::SETO:   return PPC::BUN;
763   case ISD::SETUO:  return PPC::BNU;
764   }
765   return 0;
766 }
767
768 /// getCRIdxForSetCC - Return the index of the condition register field
769 /// associated with the SetCC condition, and whether or not the field is
770 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
771 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
772   switch (CC) {
773   default: assert(0 && "Unknown condition!"); abort();
774   case ISD::SETOLT:  // FIXME: This is incorrect see PR642.
775   case ISD::SETULT:
776   case ISD::SETLT:  Inv = false;  return 0;
777   case ISD::SETOGE:  // FIXME: This is incorrect see PR642.
778   case ISD::SETUGE:
779   case ISD::SETGE:  Inv = true;   return 0;
780   case ISD::SETOGT:  // FIXME: This is incorrect see PR642.
781   case ISD::SETUGT:
782   case ISD::SETGT:  Inv = false;  return 1;
783   case ISD::SETOLE:  // FIXME: This is incorrect see PR642.
784   case ISD::SETULE:
785   case ISD::SETLE:  Inv = true;   return 1;
786   case ISD::SETOEQ:  // FIXME: This is incorrect see PR642.
787   case ISD::SETUEQ:
788   case ISD::SETEQ:  Inv = false;  return 2;
789   case ISD::SETONE:  // FIXME: This is incorrect see PR642.
790   case ISD::SETUNE:
791   case ISD::SETNE:  Inv = true;   return 2;
792   case ISD::SETO:   Inv = true;   return 3;
793   case ISD::SETUO:  Inv = false;  return 3;
794   }
795   return 0;
796 }
797
798 SDOperand PPCDAGToDAGISel::SelectSETCC(SDOperand Op) {
799   SDNode *N = Op.Val;
800   unsigned Imm;
801   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
802   if (isInt32Immediate(N->getOperand(1), Imm)) {
803     // We can codegen setcc op, imm very efficiently compared to a brcond.
804     // Check for those cases here.
805     // setcc op, 0
806     if (Imm == 0) {
807       SDOperand Op;
808       AddToQueue(Op, N->getOperand(0));
809       switch (CC) {
810       default: break;
811       case ISD::SETEQ:
812         Op = SDOperand(CurDAG->getTargetNode(PPC::CNTLZW, MVT::i32, Op), 0);
813         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(27),
814                                     getI32Imm(5), getI32Imm(31));
815       case ISD::SETNE: {
816         SDOperand AD =
817           SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
818                                           Op, getI32Imm(~0U)), 0);
819         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, 
820                                     AD.getValue(1));
821       }
822       case ISD::SETLT:
823         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(1),
824                                     getI32Imm(31), getI32Imm(31));
825       case ISD::SETGT: {
826         SDOperand T =
827           SDOperand(CurDAG->getTargetNode(PPC::NEG, MVT::i32, Op), 0);
828         T = SDOperand(CurDAG->getTargetNode(PPC::ANDC, MVT::i32, T, Op), 0);
829         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, T, getI32Imm(1),
830                                     getI32Imm(31), getI32Imm(31));
831       }
832       }
833     } else if (Imm == ~0U) {        // setcc op, -1
834       SDOperand Op;
835       AddToQueue(Op, N->getOperand(0));
836       switch (CC) {
837       default: break;
838       case ISD::SETEQ:
839         Op = SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
840                                              Op, getI32Imm(1)), 0);
841         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
842                               SDOperand(CurDAG->getTargetNode(PPC::LI, MVT::i32,
843                                                               getI32Imm(0)), 0),
844                                     Op.getValue(1));
845       case ISD::SETNE: {
846         Op = SDOperand(CurDAG->getTargetNode(PPC::NOR, MVT::i32, Op, Op), 0);
847         SDNode *AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
848                                            Op, getI32Imm(~0U));
849         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDOperand(AD, 0),
850                                     Op, SDOperand(AD, 1));
851       }
852       case ISD::SETLT: {
853         SDOperand AD = SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32, Op,
854                                                        getI32Imm(1)), 0);
855         SDOperand AN = SDOperand(CurDAG->getTargetNode(PPC::AND, MVT::i32, AD,
856                                                        Op), 0);
857         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, AN, getI32Imm(1),
858                                     getI32Imm(31), getI32Imm(31));
859       }
860       case ISD::SETGT:
861         Op = SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Op,
862                                              getI32Imm(1), getI32Imm(31),
863                                              getI32Imm(31)), 0);
864         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1));
865       }
866     }
867   }
868   
869   bool Inv;
870   unsigned Idx = getCRIdxForSetCC(CC, Inv);
871   SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
872   SDOperand IntCR;
873   
874   // Force the ccreg into CR7.
875   SDOperand CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
876   
877   SDOperand InFlag(0, 0);  // Null incoming flag value.
878   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), CR7Reg, CCReg, 
879                                InFlag).getValue(1);
880   
881   if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
882     IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, CR7Reg,
883                                             CCReg), 0);
884   else
885     IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, CCReg), 0);
886   
887   if (!Inv) {
888     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, IntCR,
889                                 getI32Imm((32-(3-Idx)) & 31),
890                                 getI32Imm(31), getI32Imm(31));
891   } else {
892     SDOperand Tmp =
893       SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, IntCR,
894                                       getI32Imm((32-(3-Idx)) & 31),
895                                       getI32Imm(31),getI32Imm(31)), 0);
896     return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
897   }
898 }
899
900
901 // Select - Convert the specified operand from a target-independent to a
902 // target-specific node if it hasn't already been changed.
903 SDNode *PPCDAGToDAGISel::Select(SDOperand &Result, SDOperand Op) {
904   SDNode *N = Op.Val;
905   if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
906       N->getOpcode() < PPCISD::FIRST_NUMBER) {
907     Result = Op;
908     return NULL;   // Already selected.
909   }
910
911   switch (N->getOpcode()) {
912   default: break;
913   case ISD::SETCC:
914     Result = SelectSETCC(Op);
915     return NULL;
916   case PPCISD::GlobalBaseReg:
917     Result = getGlobalBaseReg();
918     return Result.Val;
919     
920   case ISD::FrameIndex: {
921     int FI = cast<FrameIndexSDNode>(N)->getIndex();
922     SDOperand TFI = CurDAG->getTargetFrameIndex(FI, Op.getValueType());
923     unsigned Opc = Op.getValueType() == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
924     if (N->hasOneUse()) {
925       Result = CurDAG->SelectNodeTo(N, Opc, Op.getValueType(), TFI,
926                                     getSmallIPtrImm(0));
927       return NULL;
928     }
929     Result =
930       SDOperand(CurDAG->getTargetNode(Opc, Op.getValueType(), TFI,
931                                       getSmallIPtrImm(0)), 0);
932     return Result.Val;
933   }
934
935   case PPCISD::MFCR: {
936     SDOperand InFlag;
937     AddToQueue(InFlag, N->getOperand(1));
938     // Use MFOCRF if supported.
939     if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
940       Result = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32,
941                                                N->getOperand(0), InFlag), 0);
942     else
943       Result = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, InFlag), 0);
944     return Result.Val;
945   }
946     
947   case ISD::SDIV: {
948     // FIXME: since this depends on the setting of the carry flag from the srawi
949     //        we should really be making notes about that for the scheduler.
950     // FIXME: It sure would be nice if we could cheaply recognize the 
951     //        srl/add/sra pattern the dag combiner will generate for this as
952     //        sra/addze rather than having to handle sdiv ourselves.  oh well.
953     unsigned Imm;
954     if (isInt32Immediate(N->getOperand(1), Imm)) {
955       SDOperand N0;
956       AddToQueue(N0, N->getOperand(0));
957       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
958         SDNode *Op =
959           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
960                                 N0, getI32Imm(Log2_32(Imm)));
961         Result = CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
962                                       SDOperand(Op, 0), SDOperand(Op, 1));
963       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
964         SDNode *Op =
965           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
966                                 N0, getI32Imm(Log2_32(-Imm)));
967         SDOperand PT =
968           SDOperand(CurDAG->getTargetNode(PPC::ADDZE, MVT::i32,
969                                           SDOperand(Op, 0), SDOperand(Op, 1)),
970                     0);
971         Result = CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
972       }
973       return NULL;
974     }
975     
976     // Other cases are autogenerated.
977     break;
978   }
979   case ISD::AND: {
980     unsigned Imm, Imm2;
981     // If this is an and of a value rotated between 0 and 31 bits and then and'd
982     // with a mask, emit rlwinm
983     if (isInt32Immediate(N->getOperand(1), Imm) &&
984         (isShiftedMask_32(Imm) || isShiftedMask_32(~Imm))) {
985       SDOperand Val;
986       unsigned SH, MB, ME;
987       if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
988         AddToQueue(Val, N->getOperand(0).getOperand(0));
989       } else if (Imm == 0) {
990         // AND X, 0 -> 0, not "rlwinm 32".
991         AddToQueue(Result, N->getOperand(1));
992         return NULL;
993       } else {        
994         AddToQueue(Val, N->getOperand(0));
995         isRunOfOnes(Imm, MB, ME);
996         SH = 0;
997       }
998       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Val,
999                                     getI32Imm(SH), getI32Imm(MB),
1000                                     getI32Imm(ME));
1001       return NULL;
1002     }
1003     // ISD::OR doesn't get all the bitfield insertion fun.
1004     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
1005     if (isInt32Immediate(N->getOperand(1), Imm) && 
1006         N->getOperand(0).getOpcode() == ISD::OR &&
1007         isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
1008       unsigned MB, ME;
1009       Imm = ~(Imm^Imm2);
1010       if (isRunOfOnes(Imm, MB, ME)) {
1011         SDOperand Tmp1, Tmp2;
1012         AddToQueue(Tmp1, N->getOperand(0).getOperand(0));
1013         AddToQueue(Tmp2, N->getOperand(0).getOperand(1));
1014         Result = SDOperand(CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32,
1015                                                  Tmp1, Tmp2,
1016                                                  getI32Imm(0), getI32Imm(MB),
1017                                                  getI32Imm(ME)), 0);
1018         return Result.Val;
1019       }
1020     }
1021     
1022     // Other cases are autogenerated.
1023     break;
1024   }
1025   case ISD::OR:
1026     if (N->getValueType(0) == MVT::i32)
1027       if (SDNode *I = SelectBitfieldInsert(N)) {
1028         Result = SDOperand(I, 0);
1029         return Result.Val;
1030       }
1031       
1032     // Other cases are autogenerated.
1033     break;
1034   case ISD::SHL: {
1035     unsigned Imm, SH, MB, ME;
1036     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1037         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1038       SDOperand Val;
1039       AddToQueue(Val, N->getOperand(0).getOperand(0));
1040       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, 
1041                                     Val, getI32Imm(SH), getI32Imm(MB),
1042                                     getI32Imm(ME));
1043       return NULL;
1044     }
1045     
1046     // Other cases are autogenerated.
1047     break;
1048   }
1049   case ISD::SRL: {
1050     unsigned Imm, SH, MB, ME;
1051     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1052         isRotateAndMask(N, Imm, true, SH, MB, ME)) { 
1053       SDOperand Val;
1054       AddToQueue(Val, N->getOperand(0).getOperand(0));
1055       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, 
1056                                     Val, getI32Imm(SH), getI32Imm(MB),
1057                                     getI32Imm(ME));
1058       return NULL;
1059     }
1060     
1061     // Other cases are autogenerated.
1062     break;
1063   }
1064   case ISD::SELECT_CC: {
1065     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1066     
1067     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
1068     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1069       if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1070         if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1071           if (N1C->isNullValue() && N3C->isNullValue() &&
1072               N2C->getValue() == 1ULL && CC == ISD::SETNE &&
1073               // FIXME: Implement this optzn for PPC64.
1074               N->getValueType(0) == MVT::i32) {
1075             SDOperand LHS;
1076             AddToQueue(LHS, N->getOperand(0));
1077             SDNode *Tmp =
1078               CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1079                                     LHS, getI32Imm(~0U));
1080             Result = CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1081                                           SDOperand(Tmp, 0), LHS,
1082                                           SDOperand(Tmp, 1));
1083             return NULL;
1084           }
1085
1086     SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
1087     unsigned BROpc = getBCCForSetCC(CC);
1088
1089     bool isFP = MVT::isFloatingPoint(N->getValueType(0));
1090     unsigned SelectCCOp;
1091     if (N->getValueType(0) == MVT::i32)
1092       SelectCCOp = PPC::SELECT_CC_I4;
1093     else if (N->getValueType(0) == MVT::i64)
1094       SelectCCOp = PPC::SELECT_CC_I8;
1095     else if (N->getValueType(0) == MVT::f32)
1096       SelectCCOp = PPC::SELECT_CC_F4;
1097     else if (N->getValueType(0) == MVT::f64)
1098       SelectCCOp = PPC::SELECT_CC_F8;
1099     else
1100       SelectCCOp = PPC::SELECT_CC_VRRC;
1101
1102     SDOperand N2, N3;
1103     AddToQueue(N2, N->getOperand(2));
1104     AddToQueue(N3, N->getOperand(3));
1105     Result = CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), CCReg,
1106                                   N2, N3, getI32Imm(BROpc));
1107     return NULL;
1108   }
1109   case ISD::BR_CC: {
1110     SDOperand Chain;
1111     AddToQueue(Chain, N->getOperand(0));
1112     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1113     SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
1114     Result = CurDAG->SelectNodeTo(N, PPC::COND_BRANCH, MVT::Other, 
1115                                   CondCode, getI32Imm(getBCCForSetCC(CC)), 
1116                                   N->getOperand(4), Chain);
1117     return NULL;
1118   }
1119   case ISD::BRIND: {
1120     // FIXME: Should custom lower this.
1121     SDOperand Chain, Target;
1122     AddToQueue(Chain, N->getOperand(0));
1123     AddToQueue(Target,N->getOperand(1));
1124     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
1125     Chain = SDOperand(CurDAG->getTargetNode(Opc, MVT::Other, Target,
1126                                             Chain), 0);
1127     Result = CurDAG->SelectNodeTo(N, PPC::BCTR, MVT::Other, Chain);
1128     return NULL;
1129   }
1130   // FIXME: These are manually selected because tblgen isn't handling varargs
1131   // nodes correctly.
1132   case PPCISD::BCTRL:            return MySelect_PPCbctrl(Result, Op);
1133   case PPCISD::CALL:             return MySelect_PPCcall(Result, Op);
1134   }
1135   
1136   return SelectCode(Result, Op);
1137 }
1138
1139
1140 // FIXME: This is manually selected because tblgen isn't handling varargs nodes
1141 // correctly.
1142 SDNode *PPCDAGToDAGISel::MySelect_PPCbctrl(SDOperand &Result, SDOperand N) {
1143   SDOperand Chain(0, 0);
1144   SDNode *ResNode;
1145   
1146   bool hasFlag =
1147     N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;
1148
1149   SmallVector<SDOperand, 8> Ops;
1150   // Push varargs arguments, including optional flag.
1151   for (unsigned i = 1, e = N.getNumOperands()-hasFlag; i != e; ++i) {
1152     AddToQueue(Chain, N.getOperand(i));
1153     Ops.push_back(Chain);
1154   }
1155
1156   AddToQueue(Chain, N.getOperand(0));
1157   Ops.push_back(Chain);
1158
1159   if (hasFlag) {
1160     AddToQueue(Chain, N.getOperand(N.getNumOperands()-1));
1161     Ops.push_back(Chain);
1162   }
1163   
1164   ResNode = CurDAG->getTargetNode(PPC::BCTRL, MVT::Other, MVT::Flag,
1165                                   &Ops[0], Ops.size());
1166   Result = SDOperand(ResNode, N.ResNo);
1167   return ResNode;
1168 }
1169
1170 // FIXME: This is manually selected because tblgen isn't handling varargs nodes
1171 // correctly.
1172 SDNode *PPCDAGToDAGISel::MySelect_PPCcall(SDOperand &Result, SDOperand N) {
1173   SDOperand Chain(0, 0);
1174   SDOperand N1(0, 0);
1175   SDOperand Tmp0(0, 0);
1176   SDNode *ResNode;
1177   Chain = N.getOperand(0);
1178   N1 = N.getOperand(1);
1179   
1180   // Pattern: (PPCcall:void (imm:i32):$func)
1181   // Emits: (BLA:void (imm:i32):$func)
1182   // Pattern complexity = 4  cost = 1
1183   if (N1.getOpcode() == ISD::Constant) {
1184     unsigned Tmp0C = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1185     
1186     SmallVector<SDOperand, 8> Ops;
1187     Ops.push_back(CurDAG->getTargetConstant(Tmp0C, MVT::i32));
1188
1189     bool hasFlag =
1190       N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;
1191     
1192     // Push varargs arguments, not including optional flag.
1193     for (unsigned i = 2, e = N.getNumOperands()-hasFlag; i != e; ++i) {
1194       AddToQueue(Chain, N.getOperand(i));
1195       Ops.push_back(Chain);
1196     }
1197     AddToQueue(Chain, N.getOperand(0));
1198     Ops.push_back(Chain);
1199     if (hasFlag) {
1200       AddToQueue(Chain, N.getOperand(N.getNumOperands()-1));
1201       Ops.push_back(Chain);
1202     }
1203     ResNode = CurDAG->getTargetNode(PPC::BLA, MVT::Other, MVT::Flag,
1204                                     &Ops[0], Ops.size());
1205     
1206     Result = SDOperand(ResNode, N.ResNo);
1207     return ResNode;
1208   }
1209   
1210   // Pattern: (PPCcall:void (tglobaladdr:i32):$dst)
1211   // Emits: (BL:void (tglobaladdr:i32):$dst)
1212   // Pattern complexity = 4  cost = 1
1213   if (N1.getOpcode() == ISD::TargetGlobalAddress) {
1214     SmallVector<SDOperand, 8> Ops;
1215     Ops.push_back(N1);
1216     
1217     bool hasFlag =
1218       N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;
1219
1220     // Push varargs arguments, not including optional flag.
1221     for (unsigned i = 2, e = N.getNumOperands()-hasFlag; i != e; ++i) {
1222       AddToQueue(Chain, N.getOperand(i));
1223       Ops.push_back(Chain);
1224     }
1225     AddToQueue(Chain, N.getOperand(0));
1226     Ops.push_back(Chain);
1227     if (hasFlag) {
1228       AddToQueue(Chain, N.getOperand(N.getNumOperands()-1));
1229       Ops.push_back(Chain);
1230     }
1231     
1232     ResNode = CurDAG->getTargetNode(PPC::BL, MVT::Other, MVT::Flag,
1233                                     &Ops[0], Ops.size());
1234     
1235     Result = SDOperand(ResNode, N.ResNo);
1236     return ResNode;
1237   }
1238   
1239   // Pattern: (PPCcall:void (texternalsym:i32):$dst)
1240   // Emits: (BL:void (texternalsym:i32):$dst)
1241   // Pattern complexity = 4  cost = 1
1242   if (N1.getOpcode() == ISD::TargetExternalSymbol) {
1243     std::vector<SDOperand> Ops;
1244     Ops.push_back(N1);
1245     
1246     bool hasFlag =
1247       N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;
1248
1249     // Push varargs arguments, not including optional flag.
1250     for (unsigned i = 2, e = N.getNumOperands()-hasFlag; i != e; ++i) {
1251       AddToQueue(Chain, N.getOperand(i));
1252       Ops.push_back(Chain);
1253     }
1254     AddToQueue(Chain, N.getOperand(0));
1255     Ops.push_back(Chain);
1256     if (hasFlag) {
1257       AddToQueue(Chain, N.getOperand(N.getNumOperands()-1));
1258       Ops.push_back(Chain);
1259     }
1260     
1261     ResNode = CurDAG->getTargetNode(PPC::BL, MVT::Other, MVT::Flag,
1262                                     &Ops[0], Ops.size());
1263
1264     Result = SDOperand(ResNode, N.ResNo);
1265     return ResNode;
1266   }
1267   std::cerr << "Cannot yet select: ";
1268   N.Val->dump(CurDAG);
1269   std::cerr << '\n';
1270   abort();
1271
1272   return NULL;
1273 }
1274
1275
1276 /// createPPCISelDag - This pass converts a legalized DAG into a 
1277 /// PowerPC-specific DAG, ready for instruction scheduling.
1278 ///
1279 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
1280   return new PPCDAGToDAGISel(TM);
1281 }
1282