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