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