Add support for sdiv by 2^k and -2^k. Producing code like:
[oota-llvm.git] / lib / Target / PowerPC / PPCISelDAGToDAG.cpp
1 //===-- PPC32ISelDAGToDAG.cpp - PPC32 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 32 bit PowerPC,
11 // converting from a legalized dag to a PPC dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PowerPC.h"
16 #include "PPC32TargetMachine.h"
17 #include "PPC32ISelLowering.h"
18 #include "llvm/CodeGen/MachineConstantPool.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 using namespace llvm;
31
32 namespace {
33   Statistic<> FusedFP ("ppc-codegen", "Number of fused fp operations");
34   Statistic<> FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");
35     
36   //===--------------------------------------------------------------------===//
37   /// PPC32DAGToDAGISel - PPC32 specific code to select PPC32 machine
38   /// instructions for SelectionDAG operations.
39   ///
40   class PPC32DAGToDAGISel : public SelectionDAGISel {
41     PPC32TargetLowering PPC32Lowering;
42     unsigned GlobalBaseReg;
43   public:
44     PPC32DAGToDAGISel(TargetMachine &TM)
45       : SelectionDAGISel(PPC32Lowering), PPC32Lowering(TM) {}
46     
47     virtual bool runOnFunction(Function &Fn) {
48       // Make sure we re-emit a set of the global base reg if necessary
49       GlobalBaseReg = 0;
50       return SelectionDAGISel::runOnFunction(Fn);
51     }
52    
53     /// getI32Imm - Return a target constant with the specified value, of type
54     /// i32.
55     inline SDOperand getI32Imm(unsigned Imm) {
56       return CurDAG->getTargetConstant(Imm, MVT::i32);
57     }
58
59     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
60     /// base register.  Return the virtual register that holds this value.
61     SDOperand getGlobalBaseReg();
62     
63     // Select - Convert the specified operand from a target-independent to a
64     // target-specific node if it hasn't already been changed.
65     SDOperand Select(SDOperand Op);
66     
67     SDNode *SelectIntImmediateExpr(SDOperand LHS, SDOperand RHS,
68                                    unsigned OCHi, unsigned OCLo,
69                                    bool IsArithmetic = false,
70                                    bool Negate = false);
71     SDNode *SelectBitfieldInsert(SDNode *N);
72
73     /// SelectCC - Select a comparison of the specified values with the
74     /// specified condition code, returning the CR# of the expression.
75     SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
76
77     /// SelectAddr - Given the specified address, return the two operands for a
78     /// load/store instruction, and return true if it should be an indexed [r+r]
79     /// operation.
80     bool SelectAddr(SDOperand Addr, SDOperand &Op1, SDOperand &Op2);
81
82     /// InstructionSelectBasicBlock - This callback is invoked by
83     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
84     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG) {
85       DEBUG(BB->dump());
86       // Select target instructions for the DAG.
87       Select(DAG.getRoot());
88       DAG.RemoveDeadNodes();
89       
90       // Emit machine code to BB. 
91       ScheduleAndEmitDAG(DAG);
92     }
93  
94     virtual const char *getPassName() const {
95       return "PowerPC DAG->DAG Pattern Instruction Selection";
96     } 
97   };
98 }
99
100 /// getGlobalBaseReg - Output the instructions required to put the
101 /// base address to use for accessing globals into a register.
102 ///
103 SDOperand PPC32DAGToDAGISel::getGlobalBaseReg() {
104   if (!GlobalBaseReg) {
105     // Insert the set of GlobalBaseReg into the first MBB of the function
106     MachineBasicBlock &FirstMBB = BB->getParent()->front();
107     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
108     SSARegMap *RegMap = BB->getParent()->getSSARegMap();
109     GlobalBaseReg = RegMap->createVirtualRegister(PPC32::GPRCRegisterClass);
110     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
111     BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
112   }
113   return CurDAG->getRegister(GlobalBaseReg, MVT::i32);
114 }
115
116
117 // isIntImmediate - This method tests to see if a constant operand.
118 // If so Imm will receive the 32 bit value.
119 static bool isIntImmediate(SDNode *N, unsigned& Imm) {
120   if (N->getOpcode() == ISD::Constant) {
121     Imm = cast<ConstantSDNode>(N)->getValue();
122     return true;
123   }
124   return false;
125 }
126
127 // isOprShiftImm - Returns true if the specified operand is a shift opcode with
128 // a immediate shift count less than 32.
129 static bool isOprShiftImm(SDNode *N, unsigned& Opc, unsigned& SH) {
130   Opc = N->getOpcode();
131   return (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) &&
132     isIntImmediate(N->getOperand(1).Val, SH) && SH < 32;
133 }
134
135 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
136 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
137 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
138 // not, since all 1s are not contiguous.
139 static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
140   if (isShiftedMask_32(Val)) {
141     // look for the first non-zero bit
142     MB = CountLeadingZeros_32(Val);
143     // look for the first zero bit after the run of ones
144     ME = CountLeadingZeros_32((Val - 1) ^ Val);
145     return true;
146   } else {
147     Val = ~Val; // invert mask
148     if (isShiftedMask_32(Val)) {
149       // effectively look for the first zero bit
150       ME = CountLeadingZeros_32(Val) - 1;
151       // effectively look for the first one bit after the run of zeros
152       MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
153       return true;
154     }
155   }
156   // no run present
157   return false;
158 }
159
160 // isRotateAndMask - Returns true if Mask and Shift can be folded in to a rotate
161 // and mask opcode and mask operation.
162 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
163                             unsigned &SH, unsigned &MB, unsigned &ME) {
164   unsigned Shift  = 32;
165   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
166   unsigned Opcode = N->getOpcode();
167   if (!isIntImmediate(N->getOperand(1).Val, Shift) || (Shift > 31))
168     return false;
169   
170   if (Opcode == ISD::SHL) {
171     // apply shift left to mask if it comes first
172     if (IsShiftMask) Mask = Mask << Shift;
173     // determine which bits are made indeterminant by shift
174     Indeterminant = ~(0xFFFFFFFFu << Shift);
175   } else if (Opcode == ISD::SRA || Opcode == ISD::SRL) { 
176     // apply shift right to mask if it comes first
177     if (IsShiftMask) Mask = Mask >> Shift;
178     // determine which bits are made indeterminant by shift
179     Indeterminant = ~(0xFFFFFFFFu >> Shift);
180     // adjust for the left rotate
181     Shift = 32 - Shift;
182   } else {
183     return false;
184   }
185   
186   // if the mask doesn't intersect any Indeterminant bits
187   if (Mask && !(Mask & Indeterminant)) {
188     SH = Shift;
189     // make sure the mask is still a mask (wrap arounds may not be)
190     return isRunOfOnes(Mask, MB, ME);
191   }
192   return false;
193 }
194
195 // isOpcWithIntImmediate - This method tests to see if the node is a specific
196 // opcode and that it has a immediate integer right operand.
197 // If so Imm will receive the 32 bit value.
198 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
199   return N->getOpcode() == Opc && isIntImmediate(N->getOperand(1).Val, Imm);
200 }
201
202 // isOprNot - Returns true if the specified operand is an xor with immediate -1.
203 static bool isOprNot(SDNode *N) {
204   unsigned Imm;
205   return isOpcWithIntImmediate(N, ISD::XOR, Imm) && (signed)Imm == -1;
206 }
207
208 // Immediate constant composers.
209 // Lo16 - grabs the lo 16 bits from a 32 bit constant.
210 // Hi16 - grabs the hi 16 bits from a 32 bit constant.
211 // HA16 - computes the hi bits required if the lo bits are add/subtracted in
212 // arithmethically.
213 static unsigned Lo16(unsigned x)  { return x & 0x0000FFFF; }
214 static unsigned Hi16(unsigned x)  { return Lo16(x >> 16); }
215 static unsigned HA16(unsigned x)  { return Hi16((signed)x - (signed short)x); }
216
217 // isIntImmediate - This method tests to see if a constant operand.
218 // If so Imm will receive the 32 bit value.
219 static bool isIntImmediate(SDOperand N, unsigned& Imm) {
220   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
221     Imm = (unsigned)CN->getSignExtended();
222     return true;
223   }
224   return false;
225 }
226
227 /// SelectBitfieldInsert - turn an or of two masked values into
228 /// the rotate left word immediate then mask insert (rlwimi) instruction.
229 /// Returns true on success, false if the caller still needs to select OR.
230 ///
231 /// Patterns matched:
232 /// 1. or shl, and   5. or and, and
233 /// 2. or and, shl   6. or shl, shr
234 /// 3. or shr, and   7. or shr, shl
235 /// 4. or and, shr
236 SDNode *PPC32DAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
237   bool IsRotate = false;
238   unsigned TgtMask = 0xFFFFFFFF, InsMask = 0xFFFFFFFF, SH = 0;
239   unsigned Value;
240   
241   SDOperand Op0 = N->getOperand(0);
242   SDOperand Op1 = N->getOperand(1);
243   
244   unsigned Op0Opc = Op0.getOpcode();
245   unsigned Op1Opc = Op1.getOpcode();
246   
247   // Verify that we have the correct opcodes
248   if (ISD::SHL != Op0Opc && ISD::SRL != Op0Opc && ISD::AND != Op0Opc)
249     return false;
250   if (ISD::SHL != Op1Opc && ISD::SRL != Op1Opc && ISD::AND != Op1Opc)
251     return false;
252   
253   // Generate Mask value for Target
254   if (isIntImmediate(Op0.getOperand(1), Value)) {
255     switch(Op0Opc) {
256       case ISD::SHL: TgtMask <<= Value; break;
257       case ISD::SRL: TgtMask >>= Value; break;
258       case ISD::AND: TgtMask &= Value; break;
259     }
260   } else {
261     return 0;
262   }
263   
264   // Generate Mask value for Insert
265   if (isIntImmediate(Op1.getOperand(1), Value)) {
266     switch(Op1Opc) {
267       case ISD::SHL:
268         SH = Value;
269         InsMask <<= SH;
270         if (Op0Opc == ISD::SRL) IsRotate = true;
271           break;
272       case ISD::SRL:
273         SH = Value;
274         InsMask >>= SH;
275         SH = 32-SH;
276         if (Op0Opc == ISD::SHL) IsRotate = true;
277           break;
278       case ISD::AND:
279         InsMask &= Value;
280         break;
281     }
282   } else {
283     return 0;
284   }
285   
286   // If both of the inputs are ANDs and one of them has a logical shift by
287   // constant as its input, make that AND the inserted value so that we can
288   // combine the shift into the rotate part of the rlwimi instruction
289   bool IsAndWithShiftOp = false;
290   if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
291     if (Op1.getOperand(0).getOpcode() == ISD::SHL ||
292         Op1.getOperand(0).getOpcode() == ISD::SRL) {
293       if (isIntImmediate(Op1.getOperand(0).getOperand(1), Value)) {
294         SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
295         IsAndWithShiftOp = true;
296       }
297     } else if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
298                Op0.getOperand(0).getOpcode() == ISD::SRL) {
299       if (isIntImmediate(Op0.getOperand(0).getOperand(1), Value)) {
300         std::swap(Op0, Op1);
301         std::swap(TgtMask, InsMask);
302         SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
303         IsAndWithShiftOp = true;
304       }
305     }
306   }
307   
308   // Verify that the Target mask and Insert mask together form a full word mask
309   // and that the Insert mask is a run of set bits (which implies both are runs
310   // of set bits).  Given that, Select the arguments and generate the rlwimi
311   // instruction.
312   unsigned MB, ME;
313   if (((TgtMask & InsMask) == 0) && isRunOfOnes(InsMask, MB, ME)) {
314     bool fullMask = (TgtMask ^ InsMask) == 0xFFFFFFFF;
315     bool Op0IsAND = Op0Opc == ISD::AND;
316     // Check for rotlwi / rotrwi here, a special case of bitfield insert
317     // where both bitfield halves are sourced from the same value.
318     if (IsRotate && fullMask &&
319         N->getOperand(0).getOperand(0) == N->getOperand(1).getOperand(0)) {
320       Op0 = CurDAG->getTargetNode(PPC::RLWINM, MVT::i32,
321                                   Select(N->getOperand(0).getOperand(0)),
322                                   getI32Imm(SH), getI32Imm(0), getI32Imm(31));
323       return Op0.Val;
324     }
325     SDOperand Tmp1 = (Op0IsAND && fullMask) ? Select(Op0.getOperand(0))
326                                             : Select(Op0);
327     SDOperand Tmp2 = IsAndWithShiftOp ? Select(Op1.getOperand(0).getOperand(0)) 
328                                       : Select(Op1.getOperand(0));
329     Op0 = CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2,
330                                 getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
331     return Op0.Val;
332   }
333   return 0;
334 }
335
336 // SelectIntImmediateExpr - Choose code for integer operations with an immediate
337 // operand.
338 SDNode *PPC32DAGToDAGISel::SelectIntImmediateExpr(SDOperand LHS, SDOperand RHS,
339                                                   unsigned OCHi, unsigned OCLo,
340                                                   bool IsArithmetic,
341                                                   bool Negate) {
342   // Check to make sure this is a constant.
343   ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS);
344   // Exit if not a constant.
345   if (!CN) return 0;
346   // Extract immediate.
347   unsigned C = (unsigned)CN->getValue();
348   // Negate if required (ISD::SUB).
349   if (Negate) C = -C;
350   // Get the hi and lo portions of constant.
351   unsigned Hi = IsArithmetic ? HA16(C) : Hi16(C);
352   unsigned Lo = Lo16(C);
353
354   // If two instructions are needed and usage indicates it would be better to
355   // load immediate into a register, bail out.
356   if (Hi && Lo && CN->use_size() > 2) return false;
357
358   // Select the first operand.
359   SDOperand Opr0 = Select(LHS);
360
361   if (Lo)  // Add in the lo-part.
362     Opr0 = CurDAG->getTargetNode(OCLo, MVT::i32, Opr0, getI32Imm(Lo));
363   if (Hi)  // Add in the hi-part.
364     Opr0 = CurDAG->getTargetNode(OCHi, MVT::i32, Opr0, getI32Imm(Hi));
365   return Opr0.Val;
366 }
367
368 /// SelectAddr - Given the specified address, return the two operands for a
369 /// load/store instruction, and return true if it should be an indexed [r+r]
370 /// operation.
371 bool PPC32DAGToDAGISel::SelectAddr(SDOperand Addr, SDOperand &Op1,
372                                    SDOperand &Op2) {
373   unsigned imm = 0;
374   if (Addr.getOpcode() == ISD::ADD) {
375     if (isIntImmediate(Addr.getOperand(1), imm) && isInt16(imm)) {
376       Op1 = getI32Imm(Lo16(imm));
377       if (FrameIndexSDNode *FI =
378             dyn_cast<FrameIndexSDNode>(Addr.getOperand(0))) {
379         ++FrameOff;
380         Op2 = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
381       } else {
382         Op2 = Select(Addr.getOperand(0));
383       }
384       return false;
385     } else {
386       Op1 = Select(Addr.getOperand(0));
387       Op2 = Select(Addr.getOperand(1));
388       return true;   // [r+r]
389     }
390   }
391
392   // Now check if we're dealing with a global, and whether or not we should emit
393   // an optimized load or store for statics.
394   if (GlobalAddressSDNode *GN = dyn_cast<GlobalAddressSDNode>(Addr)) {
395     GlobalValue *GV = GN->getGlobal();
396     if (!GV->hasWeakLinkage() && !GV->isExternal()) {
397       Op1 = CurDAG->getTargetGlobalAddress(GV, MVT::i32);
398       if (PICEnabled)
399         Op2 = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),
400                                     Op1);
401       else
402         Op2 = CurDAG->getTargetNode(PPC::LIS, MVT::i32, Op1);
403       return false;
404     }
405   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Addr)) {
406     Op1 = getI32Imm(0);
407     Op2 = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
408     return false;
409   } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Addr)) {
410     Op1 = Addr;
411     if (PICEnabled)
412       Op2 = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),Op1);
413     else
414       Op2 = CurDAG->getTargetNode(PPC::LIS, MVT::i32, Op1);
415     return false;
416   }
417   Op1 = getI32Imm(0);
418   Op2 = Select(Addr);
419   return false;
420 }
421
422 /// SelectCC - Select a comparison of the specified values with the specified
423 /// condition code, returning the CR# of the expression.
424 SDOperand PPC32DAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
425                                       ISD::CondCode CC) {
426   // Always select the LHS.
427   LHS = Select(LHS);
428
429   // Use U to determine whether the SETCC immediate range is signed or not.
430   if (MVT::isInteger(LHS.getValueType())) {
431     bool U = ISD::isUnsignedIntSetCC(CC);
432     unsigned Imm;
433     if (isIntImmediate(RHS, Imm) && 
434         ((U && isUInt16(Imm)) || (!U && isInt16(Imm))))
435       return CurDAG->getTargetNode(U ? PPC::CMPLWI : PPC::CMPWI, MVT::i32,
436                                    LHS, getI32Imm(Lo16(Imm)));
437     return CurDAG->getTargetNode(U ? PPC::CMPLW : PPC::CMPW, MVT::i32,
438                                  LHS, Select(RHS));
439   } else {
440     return CurDAG->getTargetNode(PPC::FCMPU, MVT::i32, LHS, Select(RHS));
441   }
442 }
443
444 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
445 /// to Condition.
446 static unsigned getBCCForSetCC(ISD::CondCode CC) {
447   switch (CC) {
448   default: assert(0 && "Unknown condition!"); abort();
449   case ISD::SETEQ:  return PPC::BEQ;
450   case ISD::SETNE:  return PPC::BNE;
451   case ISD::SETULT:
452   case ISD::SETLT:  return PPC::BLT;
453   case ISD::SETULE:
454   case ISD::SETLE:  return PPC::BLE;
455   case ISD::SETUGT:
456   case ISD::SETGT:  return PPC::BGT;
457   case ISD::SETUGE:
458   case ISD::SETGE:  return PPC::BGE;
459   }
460   return 0;
461 }
462
463
464 // Select - Convert the specified operand from a target-independent to a
465 // target-specific node if it hasn't already been changed.
466 SDOperand PPC32DAGToDAGISel::Select(SDOperand Op) {
467   SDNode *N = Op.Val;
468   if (N->getOpcode() >= ISD::BUILTIN_OP_END)
469     return Op;   // Already selected.
470   
471   switch (N->getOpcode()) {
472   default:
473     std::cerr << "Cannot yet select: ";
474     N->dump();
475     std::cerr << "\n";
476     abort();
477   case ISD::EntryToken:       // These leaves remain the same.
478     return Op;
479   case ISD::TokenFactor: {
480     SDOperand New;
481     if (N->getNumOperands() == 2) {
482       SDOperand Op0 = Select(N->getOperand(0));
483       SDOperand Op1 = Select(N->getOperand(1));
484       New = CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);
485     } else {
486       std::vector<SDOperand> Ops;
487       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
488         Ops.push_back(Select(N->getOperand(i)));
489       New = CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);
490     }
491     
492     if (New.Val != N) {
493       CurDAG->ReplaceAllUsesWith(N, New.Val);
494       N = New.Val;
495     }
496     break;
497   }
498   case ISD::CopyFromReg: {
499     SDOperand Chain = Select(N->getOperand(0));
500     if (Chain == N->getOperand(0)) return Op; // No change
501     SDOperand New = CurDAG->getCopyFromReg(Chain,
502          cast<RegisterSDNode>(N->getOperand(1))->getReg(), N->getValueType(0));
503     return New.getValue(Op.ResNo);
504   }
505   case ISD::CopyToReg: {
506     SDOperand Chain = Select(N->getOperand(0));
507     SDOperand Reg = N->getOperand(1);
508     SDOperand Val = Select(N->getOperand(2));
509     if (Chain != N->getOperand(0) || Val != N->getOperand(2)) {
510       SDOperand New = CurDAG->getNode(ISD::CopyToReg, MVT::Other,
511                                       Chain, Reg, Val);
512       CurDAG->ReplaceAllUsesWith(N, New.Val);
513       N = New.Val;
514     }
515     break;    
516   }
517   case ISD::Constant: {
518     assert(N->getValueType(0) == MVT::i32);
519     unsigned v = (unsigned)cast<ConstantSDNode>(N)->getValue();
520     unsigned Hi = HA16(v);
521     unsigned Lo = Lo16(v);
522     if (Hi && Lo) {
523       SDOperand Top = CurDAG->getTargetNode(PPC::LIS, MVT::i32, 
524                                             getI32Imm(v >> 16));
525       CurDAG->SelectNodeTo(N, MVT::i32, PPC::ORI, Top, getI32Imm(v & 0xFFFF));
526     } else if (Lo) {
527       CurDAG->SelectNodeTo(N, MVT::i32, PPC::LI, getI32Imm(v));
528     } else {
529       CurDAG->SelectNodeTo(N, MVT::i32, PPC::LIS, getI32Imm(v >> 16));
530     }
531     break;
532   }
533   case ISD::ConstantFP: {  // FIXME: this should get sucked into the legalizer
534     MachineConstantPool *CP = CurDAG->getMachineFunction().getConstantPool();
535     Constant *CFP = ConstantFP::get(Type::FloatTy,
536                                     cast<ConstantFPSDNode>(N)->getValue());
537     SDOperand CPN = CurDAG->getConstantPool(CP->getConstantPoolIndex(CFP),
538                                             MVT::i32);
539     SDOperand Tmp;
540     if (PICEnabled)
541       Tmp = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),CPN);
542     else
543       Tmp = CurDAG->getTargetNode(PPC::LIS, MVT::i32, CPN);
544     CurDAG->SelectNodeTo(N, N->getValueType(0), PPC::LFS, CPN, Tmp);
545     break;
546   }
547   case ISD::UNDEF:
548     if (N->getValueType(0) == MVT::i32)
549       CurDAG->SelectNodeTo(N, MVT::i32, PPC::IMPLICIT_DEF_GPR);
550     else
551       CurDAG->SelectNodeTo(N, N->getValueType(0), PPC::IMPLICIT_DEF_FP);
552     break;
553   case ISD::FrameIndex: {
554     int FI = cast<FrameIndexSDNode>(N)->getIndex();
555     CurDAG->SelectNodeTo(N, MVT::i32, PPC::ADDI,
556                          CurDAG->getTargetFrameIndex(FI, MVT::i32),
557                          getI32Imm(0));
558     break;
559   }
560   case ISD::ConstantPool: {
561     unsigned CPIIdx = cast<ConstantPoolSDNode>(N)->getIndex();
562     SDOperand Tmp, CPI = CurDAG->getTargetConstantPool(CPIIdx, MVT::i32);
563     if (PICEnabled)
564       Tmp = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),CPI);
565     else
566       Tmp = CurDAG->getTargetNode(PPC::LIS, MVT::i32, CPI);
567     CurDAG->SelectNodeTo(N, MVT::i32, PPC::LA, Tmp, CPI);
568     break;
569   }
570   case ISD::GlobalAddress: {
571     GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
572     SDOperand Tmp;
573     SDOperand GA = CurDAG->getTargetGlobalAddress(GV, MVT::i32);
574     if (PICEnabled)
575       Tmp = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(), GA);
576     else
577       Tmp = CurDAG->getTargetNode(PPC::LIS, MVT::i32, GA);
578
579     if (GV->hasWeakLinkage() || GV->isExternal())
580       CurDAG->SelectNodeTo(N, MVT::i32, PPC::LWZ, GA, Tmp);
581     else
582       CurDAG->SelectNodeTo(N, MVT::i32, PPC::LA, Tmp, GA);
583     break;
584   }
585   case ISD::SIGN_EXTEND_INREG:
586     switch(cast<VTSDNode>(N->getOperand(1))->getVT()) {
587     default: assert(0 && "Illegal type in SIGN_EXTEND_INREG"); break;
588     case MVT::i16:
589       CurDAG->SelectNodeTo(N, MVT::i32, PPC::EXTSH, Select(N->getOperand(0)));
590       break;
591     case MVT::i8:
592       CurDAG->SelectNodeTo(N, MVT::i32, PPC::EXTSB, Select(N->getOperand(0)));
593       break;
594     }
595     break;
596   case ISD::CTLZ:
597     assert(N->getValueType(0) == MVT::i32);
598     CurDAG->SelectNodeTo(N, MVT::i32, PPC::CNTLZW, Select(N->getOperand(0)));
599     break;
600   case ISD::ADD: {
601     MVT::ValueType Ty = N->getValueType(0);
602     if (Ty == MVT::i32) {
603       if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), N->getOperand(1),
604                                              PPC::ADDIS, PPC::ADDI, true)) {
605         CurDAG->ReplaceAllUsesWith(N, I);
606         N = I;
607       } else {
608         CurDAG->SelectNodeTo(N, Ty, PPC::ADD, Select(N->getOperand(0)),
609                              Select(N->getOperand(1)));
610       }
611       break;
612     }
613     
614     if (!NoExcessFPPrecision) {  // Match FMA ops
615       if (N->getOperand(0).getOpcode() == ISD::MUL &&
616           N->getOperand(0).Val->hasOneUse()) {
617         ++FusedFP; // Statistic
618         CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FMADD : PPC::FMADDS,
619                              Select(N->getOperand(0).getOperand(0)),
620                              Select(N->getOperand(0).getOperand(1)),
621                              Select(N->getOperand(1)));
622         break;
623       } else if (N->getOperand(1).getOpcode() == ISD::MUL &&
624                  N->getOperand(1).hasOneUse()) {
625         ++FusedFP; // Statistic
626         CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FMADD : PPC::FMADDS,
627                              Select(N->getOperand(1).getOperand(0)),
628                              Select(N->getOperand(1).getOperand(1)),
629                              Select(N->getOperand(0)));
630         break;
631       }
632     }
633     
634     CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FADD : PPC::FADDS,
635                          Select(N->getOperand(0)), Select(N->getOperand(1)));
636     break;
637   }
638   case ISD::SUB: {
639     MVT::ValueType Ty = N->getValueType(0);
640     if (Ty == MVT::i32) {
641       unsigned Imm;
642       if (isIntImmediate(N->getOperand(0), Imm) && isInt16(Imm)) {
643         if (0 == Imm)
644           CurDAG->SelectNodeTo(N, Ty, PPC::NEG, Select(N->getOperand(1)));
645         else
646           CurDAG->SelectNodeTo(N, Ty, PPC::SUBFIC, Select(N->getOperand(1)),
647                                getI32Imm(Lo16(Imm)));
648         break;
649       }
650       if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), N->getOperand(1),
651                                           PPC::ADDIS, PPC::ADDI, true, true)) {
652         CurDAG->ReplaceAllUsesWith(N, I);
653         N = I;
654       } else {
655         CurDAG->SelectNodeTo(N, Ty, PPC::SUBF, Select(N->getOperand(1)),
656                              Select(N->getOperand(0)));
657       }
658       break;
659     }
660     
661     if (!NoExcessFPPrecision) {  // Match FMA ops
662       if (N->getOperand(0).getOpcode() == ISD::MUL &&
663           N->getOperand(0).Val->hasOneUse()) {
664         ++FusedFP; // Statistic
665         CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FMSUB : PPC::FMSUBS,
666                              Select(N->getOperand(0).getOperand(0)),
667                              Select(N->getOperand(0).getOperand(1)),
668                              Select(N->getOperand(1)));
669         break;
670       } else if (N->getOperand(1).getOpcode() == ISD::MUL &&
671                  N->getOperand(1).Val->hasOneUse()) {
672         ++FusedFP; // Statistic
673         CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FNMSUB : PPC::FNMSUBS,
674                              Select(N->getOperand(1).getOperand(0)),
675                              Select(N->getOperand(1).getOperand(1)),
676                              Select(N->getOperand(0)));
677         break;
678       }
679     }
680     CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FSUB : PPC::FSUBS,
681                          Select(N->getOperand(0)),
682                          Select(N->getOperand(1)));
683     break;
684   }
685   case ISD::MUL: {
686     unsigned Imm, Opc;
687     if (isIntImmediate(N->getOperand(1), Imm) && isInt16(Imm)) {
688       CurDAG->SelectNodeTo(N, N->getValueType(0), PPC::MULLI, 
689                            Select(N->getOperand(0)), getI32Imm(Lo16(Imm)));
690       break;
691     } 
692     switch (N->getValueType(0)) {
693       default: assert(0 && "Unhandled multiply type!");
694       case MVT::i32: Opc = PPC::MULLW; break;
695       case MVT::f32: Opc = PPC::FMULS; break;
696       case MVT::f64: Opc = PPC::FMUL;  break;
697     }
698     CurDAG->SelectNodeTo(N, MVT::i32, Opc, Select(N->getOperand(0)), 
699                          Select(N->getOperand(1)));
700     break;
701   }
702   case ISD::SDIV: {
703     unsigned Imm;
704     if (isIntImmediate(N->getOperand(1), Imm)) {
705       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
706         SDOperand Op =
707           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
708                                 Select(N->getOperand(0)),
709                                 getI32Imm(Log2_32(Imm)));
710         CurDAG->SelectNodeTo(N, MVT::i32, PPC::ADDZE,
711                              Op.getValue(0), Op.getValue(1));
712         break;
713       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
714         SDOperand Op =
715           CurDAG->getTargetNode(PPC::SRAWI, MVT::Flag, MVT::i32,
716                                 Select(N->getOperand(0)),
717                                 getI32Imm(Log2_32(-Imm)));
718         SDOperand PT =
719           CurDAG->getTargetNode(PPC::ADDZE, MVT::i32, Op.getValue(1),
720                                 Op.getValue(0));
721         CurDAG->SelectNodeTo(N, MVT::i32, PPC::NEG, PT);
722         break;
723       }
724     }
725     assert(0 && "SDIV not implemented yet!");
726     abort();
727   }    
728   case ISD::MULHS:
729     assert(N->getValueType(0) == MVT::i32);
730     CurDAG->SelectNodeTo(N, MVT::i32, PPC::MULHW, Select(N->getOperand(0)), 
731                          Select(N->getOperand(1)));
732     break;
733   case ISD::MULHU:
734     assert(N->getValueType(0) == MVT::i32);
735     CurDAG->SelectNodeTo(N, MVT::i32, PPC::MULHWU, Select(N->getOperand(0)),
736                          Select(N->getOperand(1)));
737     break;
738   case ISD::AND: {
739     unsigned Imm;
740     // If this is an and of a value rotated between 0 and 31 bits and then and'd
741     // with a mask, emit rlwinm
742     if (isIntImmediate(N->getOperand(1), Imm) && (isShiftedMask_32(Imm) ||
743                                                   isShiftedMask_32(~Imm))) {
744       SDOperand Val;
745       unsigned SH, MB, ME;
746       if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
747         Val = Select(N->getOperand(0).getOperand(0));
748       } else {
749         Val = Select(N->getOperand(0));
750         isRunOfOnes(Imm, MB, ME);
751         SH = 0;
752       }
753       CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, Val, getI32Imm(SH),
754                            getI32Imm(MB), getI32Imm(ME));
755       break;
756     }
757     // If this is an and with an immediate that isn't a mask, then codegen it as
758     // high and low 16 bit immediate ands.
759     if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), 
760                                            N->getOperand(1),
761                                            PPC::ANDISo, PPC::ANDIo)) {
762       CurDAG->ReplaceAllUsesWith(N, I); 
763       N = I;
764       break;
765     }
766     // Finally, check for the case where we are being asked to select
767     // and (not(a), b) or and (a, not(b)) which can be selected as andc.
768     if (isOprNot(N->getOperand(0).Val))
769       CurDAG->SelectNodeTo(N, MVT::i32, PPC::ANDC, Select(N->getOperand(1)),
770                            Select(N->getOperand(0).getOperand(0)));
771     else if (isOprNot(N->getOperand(1).Val))
772       CurDAG->SelectNodeTo(N, MVT::i32, PPC::ANDC, Select(N->getOperand(0)),
773                            Select(N->getOperand(1).getOperand(0)));
774     else
775       CurDAG->SelectNodeTo(N, MVT::i32, PPC::AND, Select(N->getOperand(0)),
776                            Select(N->getOperand(1)));
777     break;
778   }
779   case ISD::OR:
780     if (SDNode *I = SelectBitfieldInsert(N)) {
781       CurDAG->ReplaceAllUsesWith(N, I);
782       N = I;
783       break;
784     }
785     if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), 
786                                            N->getOperand(1),
787                                            PPC::ORIS, PPC::ORI)) {
788       CurDAG->ReplaceAllUsesWith(N, I); 
789       N = I;
790       break;
791     }
792     // Finally, check for the case where we are being asked to select
793     // 'or (not(a), b)' or 'or (a, not(b))' which can be selected as orc.
794     if (isOprNot(N->getOperand(0).Val))
795       CurDAG->SelectNodeTo(N, MVT::i32, PPC::ORC, Select(N->getOperand(1)),
796                            Select(N->getOperand(0).getOperand(0)));
797     else if (isOprNot(N->getOperand(1).Val))
798       CurDAG->SelectNodeTo(N, MVT::i32, PPC::ORC, Select(N->getOperand(0)),
799                            Select(N->getOperand(1).getOperand(0)));
800     else
801       CurDAG->SelectNodeTo(N, MVT::i32, PPC::OR, Select(N->getOperand(0)),
802                            Select(N->getOperand(1)));
803     break;
804   case ISD::XOR:
805     // Check whether or not this node is a logical 'not'.  This is represented
806     // by llvm as a xor with the constant value -1 (all bits set).  If this is a
807     // 'not', then fold 'or' into 'nor', and so forth for the supported ops.
808     if (isOprNot(N)) {
809       unsigned Opc;
810       SDOperand Val = Select(N->getOperand(0));
811       switch (Val.getTargetOpcode()) {
812       default:        Opc = 0;          break;
813       case PPC::OR:   Opc = PPC::NOR;   break;
814       case PPC::AND:  Opc = PPC::NAND;  break;
815       case PPC::XOR:  Opc = PPC::EQV;   break;
816       }
817       if (Opc)
818         CurDAG->SelectNodeTo(N, MVT::i32, Opc, Val.getOperand(0),
819                              Val.getOperand(1));
820       else
821         CurDAG->SelectNodeTo(N, MVT::i32, PPC::NOR, Val, Val);
822       break;
823     }
824     // If this is a xor with an immediate other than -1, then codegen it as high
825     // and low 16 bit immediate xors.
826     if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), 
827                                            N->getOperand(1),
828                                            PPC::XORIS, PPC::XORI)) {
829       CurDAG->ReplaceAllUsesWith(N, I); 
830       N = I;
831       break;
832     }
833     // Finally, check for the case where we are being asked to select
834     // xor (not(a), b) which is equivalent to not(xor a, b), which is eqv
835     if (isOprNot(N->getOperand(0).Val))
836       CurDAG->SelectNodeTo(N, MVT::i32, PPC::EQV, 
837                            Select(N->getOperand(0).getOperand(0)),
838                            Select(N->getOperand(1)));
839     else
840       CurDAG->SelectNodeTo(N, MVT::i32, PPC::XOR, Select(N->getOperand(0)),
841                            Select(N->getOperand(1)));
842     break;
843   case ISD::SHL: {
844     unsigned Imm, SH, MB, ME;
845     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
846         isRotateAndMask(N, Imm, true, SH, MB, ME))
847       CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, 
848                            Select(N->getOperand(0).getOperand(0)),
849                            getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
850     else if (isIntImmediate(N->getOperand(1), Imm))
851       CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, Select(N->getOperand(0)),
852                            getI32Imm(Imm), getI32Imm(0), getI32Imm(31-Imm));
853     else
854       CurDAG->SelectNodeTo(N, MVT::i32, PPC::SLW, Select(N->getOperand(0)),
855                            Select(N->getOperand(1)));
856     break;
857   }
858   case ISD::SRL: {
859     unsigned Imm, SH, MB, ME;
860     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
861         isRotateAndMask(N, Imm, true, SH, MB, ME))
862       CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, 
863                            Select(N->getOperand(0).getOperand(0)),
864                            getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
865     else if (isIntImmediate(N->getOperand(1), Imm))
866       CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, Select(N->getOperand(0)),
867                            getI32Imm(32-Imm), getI32Imm(Imm), getI32Imm(31));
868     else
869       CurDAG->SelectNodeTo(N, MVT::i32, PPC::SRW, Select(N->getOperand(0)),
870                            Select(N->getOperand(1)));
871     break;
872   }
873   case ISD::SRA: {
874     unsigned Imm, SH, MB, ME;
875     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
876         isRotateAndMask(N, Imm, true, SH, MB, ME))
877       CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, 
878                            Select(N->getOperand(0).getOperand(0)),
879                            getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
880     else if (isIntImmediate(N->getOperand(1), Imm))
881       CurDAG->SelectNodeTo(N, MVT::i32, PPC::SRAWI, Select(N->getOperand(0)), 
882                            getI32Imm(Imm));
883     else
884       CurDAG->SelectNodeTo(N, MVT::i32, PPC::SRAW, Select(N->getOperand(0)),
885                            Select(N->getOperand(1)));
886     break;
887   }
888   case ISD::FABS:
889     CurDAG->SelectNodeTo(N, N->getValueType(0), PPC::FABS, 
890                          Select(N->getOperand(0)));
891     break;
892   case ISD::FP_EXTEND:
893     assert(MVT::f64 == N->getValueType(0) && 
894            MVT::f32 == N->getOperand(0).getValueType() && "Illegal FP_EXTEND");
895     CurDAG->SelectNodeTo(N, MVT::f64, PPC::FMR, Select(N->getOperand(0)));
896     break;
897   case ISD::FP_ROUND:
898     assert(MVT::f32 == N->getValueType(0) && 
899            MVT::f64 == N->getOperand(0).getValueType() && "Illegal FP_ROUND");
900     CurDAG->SelectNodeTo(N, MVT::f32, PPC::FRSP, Select(N->getOperand(0)));
901     break;
902   case ISD::FNEG: {
903     SDOperand Val = Select(N->getOperand(0));
904     MVT::ValueType Ty = N->getValueType(0);
905     if (Val.Val->hasOneUse()) {
906       unsigned Opc;
907       switch (Val.getTargetOpcode()) {
908       default:          Opc = 0;            break;
909       case PPC::FABS:   Opc = PPC::FNABS;   break;
910       case PPC::FMADD:  Opc = PPC::FNMADD;  break;
911       case PPC::FMADDS: Opc = PPC::FNMADDS; break;
912       case PPC::FMSUB:  Opc = PPC::FNMSUB;  break;
913       case PPC::FMSUBS: Opc = PPC::FNMSUBS; break;
914       }
915       // If we inverted the opcode, then emit the new instruction with the
916       // inverted opcode and the original instruction's operands.  Otherwise, 
917       // fall through and generate a fneg instruction.
918       if (Opc) {
919         if (PPC::FNABS == Opc)
920           CurDAG->SelectNodeTo(N, Ty, Opc, Val.getOperand(0));
921         else
922           CurDAG->SelectNodeTo(N, Ty, Opc, Val.getOperand(0),
923                                Val.getOperand(1), Val.getOperand(2));
924         break;
925       }
926     }
927     CurDAG->SelectNodeTo(N, Ty, PPC::FNEG, Val);
928     break;
929   }
930   case ISD::FSQRT: {
931     MVT::ValueType Ty = N->getValueType(0);
932     CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FSQRT : PPC::FSQRTS,
933                          Select(N->getOperand(0)));
934     break;
935   }
936   case ISD::LOAD:
937   case ISD::EXTLOAD:
938   case ISD::ZEXTLOAD:
939   case ISD::SEXTLOAD: {
940     SDOperand Op1, Op2;
941     bool isIdx = SelectAddr(N->getOperand(1), Op1, Op2);
942
943     MVT::ValueType TypeBeingLoaded = (N->getOpcode() == ISD::LOAD) ?
944       N->getValueType(0) : cast<VTSDNode>(N->getOperand(3))->getVT();
945     unsigned Opc;
946     switch (TypeBeingLoaded) {
947     default: N->dump(); assert(0 && "Cannot load this type!");
948     case MVT::i1:
949     case MVT::i8:  Opc = isIdx ? PPC::LBZX : PPC::LBZ; break;
950     case MVT::i16:
951       if (N->getOpcode() == ISD::SEXTLOAD) { // SEXT load?
952         Opc = isIdx ? PPC::LHAX : PPC::LHA;
953       } else {
954         Opc = isIdx ? PPC::LHZX : PPC::LHZ;
955       }
956       break;
957     case MVT::i32: Opc = isIdx ? PPC::LWZX : PPC::LWZ; break;
958     case MVT::f32: Opc = isIdx ? PPC::LFSX : PPC::LFS; break;
959     case MVT::f64: Opc = isIdx ? PPC::LFDX : PPC::LFD; break;
960     }
961
962     CurDAG->SelectNodeTo(N, N->getValueType(0), MVT::Other, Opc,
963                          Op1, Op2, Select(N->getOperand(0)));
964     break;
965   }
966
967   case ISD::TRUNCSTORE:
968   case ISD::STORE: {
969     SDOperand AddrOp1, AddrOp2;
970     bool isIdx = SelectAddr(N->getOperand(2), AddrOp1, AddrOp2);
971
972     unsigned Opc;
973     if (N->getOpcode() == ISD::STORE) {
974       switch (N->getOperand(1).getValueType()) {
975       default: assert(0 && "unknown Type in store");
976       case MVT::i32: Opc = isIdx ? PPC::STWX  : PPC::STW; break;
977       case MVT::f64: Opc = isIdx ? PPC::STFDX : PPC::STFD; break;
978       case MVT::f32: Opc = isIdx ? PPC::STFSX : PPC::STFS; break;
979       }
980     } else { //ISD::TRUNCSTORE
981       switch(cast<VTSDNode>(N->getOperand(4))->getVT()) {
982       default: assert(0 && "unknown Type in store");
983       case MVT::i1:
984       case MVT::i8:  Opc = isIdx ? PPC::STBX : PPC::STB; break;
985       case MVT::i16: Opc = isIdx ? PPC::STHX : PPC::STH; break;
986       }
987     }
988     
989     CurDAG->SelectNodeTo(N, MVT::Other, Opc, Select(N->getOperand(1)),
990                          AddrOp1, AddrOp2, Select(N->getOperand(0)));
991     break;
992   }
993
994   case ISD::CALLSEQ_START:
995   case ISD::CALLSEQ_END: {
996     unsigned Amt = cast<ConstantSDNode>(N->getOperand(1))->getValue();
997     unsigned Opc = N->getOpcode() == ISD::CALLSEQ_START ?
998                        PPC::ADJCALLSTACKDOWN : PPC::ADJCALLSTACKUP;
999     CurDAG->SelectNodeTo(N, MVT::Other, Opc, 
1000                          getI32Imm(Amt), Select(N->getOperand(0)));
1001     break;
1002   }
1003   case ISD::CALL:
1004   case ISD::TAILCALL: {
1005     SDOperand Chain = Select(N->getOperand(0));
1006
1007     unsigned CallOpcode;
1008     std::vector<SDOperand> CallOperands;
1009     
1010     if (GlobalAddressSDNode *GASD =
1011         dyn_cast<GlobalAddressSDNode>(N->getOperand(1))) {
1012       CallOpcode = PPC::CALLpcrel;
1013       CallOperands.push_back(CurDAG->getTargetGlobalAddress(GASD->getGlobal(),
1014                                                             MVT::i32));
1015     } else if (ExternalSymbolSDNode *ESSDN =
1016                dyn_cast<ExternalSymbolSDNode>(N->getOperand(1))) {
1017       CallOpcode = PPC::CALLpcrel;
1018       CallOperands.push_back(N->getOperand(1));
1019     } else {
1020       // Copy the callee address into the CTR register.
1021       SDOperand Callee = Select(N->getOperand(1));
1022       Chain = CurDAG->getTargetNode(PPC::MTCTR, MVT::Other, Callee, Chain);
1023
1024       // Copy the callee address into R12 on darwin.
1025       SDOperand R12 = CurDAG->getRegister(PPC::R12, MVT::i32);
1026       Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, R12, Callee, Chain);
1027       
1028       CallOperands.push_back(getI32Imm(20));  // Information to encode indcall
1029       CallOperands.push_back(getI32Imm(0));   // Information to encode indcall
1030       CallOperands.push_back(R12);
1031       CallOpcode = PPC::CALLindirect;
1032     }
1033     
1034     unsigned GPR_idx = 0, FPR_idx = 0;
1035     static const unsigned GPR[] = {
1036       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1037       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1038     };
1039     static const unsigned FPR[] = {
1040       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1041       PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1042     };
1043     
1044     for (unsigned i = 2, e = N->getNumOperands(); i != e; ++i)
1045       if (N->getOperand(i).getOpcode() != ISD::UNDEF) {
1046         unsigned DestReg = 0;
1047         MVT::ValueType RegTy;
1048         if (N->getOperand(i).getValueType() == MVT::i32) {
1049           assert(GPR_idx < 8 && "Too many int args");
1050           DestReg = GPR[GPR_idx++];
1051           RegTy = MVT::i32;
1052         } else {
1053           assert(MVT::isFloatingPoint(N->getOperand(i).getValueType()) &&
1054                  "Unpromoted integer arg?");
1055           assert(FPR_idx < 13 && "Too many fp args");
1056           DestReg = FPR[FPR_idx++];
1057           RegTy = MVT::f64;   // Even if this is really f32!
1058         }
1059         
1060         SDOperand Reg = CurDAG->getRegister(DestReg, RegTy);
1061         Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, Chain, Reg,
1062                                 Select(N->getOperand(i)));
1063         CallOperands.push_back(Reg);
1064       }
1065
1066     // Finally, once everything is in registers to pass to the call, emit the
1067     // call itself.
1068     CallOperands.push_back(Chain);
1069     Chain = CurDAG->getTargetNode(CallOpcode, MVT::Other, CallOperands);
1070     
1071     std::vector<SDOperand> CallResults;
1072     
1073     // If the call has results, copy the values out of the ret val registers.
1074     switch (N->getValueType(0)) {
1075     default: assert(0 && "Unexpected ret value!");
1076     case MVT::Other: break;
1077     case MVT::i32:
1078       if (N->getValueType(1) == MVT::i32) {
1079         Chain = CurDAG->getCopyFromReg(Chain, PPC::R4, MVT::i32).getValue(1);
1080         CallResults.push_back(Chain.getValue(0));
1081         Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32).getValue(1);
1082         CallResults.push_back(Chain.getValue(0));
1083       } else {
1084         Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32).getValue(1);
1085         CallResults.push_back(Chain.getValue(0));
1086       }
1087       break;
1088     case MVT::f32:
1089     case MVT::f64:
1090       Chain = CurDAG->getCopyFromReg(Chain, PPC::F1, MVT::f64).getValue(1);
1091       CallResults.push_back(Chain.getValue(0));
1092       break;
1093     }
1094     
1095     CallResults.push_back(Chain);
1096     CurDAG->ReplaceAllUsesWith(N, CallResults);
1097     return CallResults[Op.ResNo];
1098   }
1099   case ISD::RET: {
1100     SDOperand Chain = Select(N->getOperand(0));     // Token chain.
1101
1102     if (N->getNumOperands() > 1) {
1103       SDOperand Val = Select(N->getOperand(1));
1104       switch (N->getOperand(1).getValueType()) {
1105       default: assert(0 && "Unknown return type!");
1106       case MVT::f64:
1107       case MVT::f32:
1108         Chain = CurDAG->getCopyToReg(Chain, PPC::F1, Val);
1109         break;
1110       case MVT::i32:
1111         Chain = CurDAG->getCopyToReg(Chain, PPC::R3, Val);
1112         break;
1113       }
1114
1115       if (N->getNumOperands() > 2) {
1116         assert(N->getOperand(1).getValueType() == MVT::i32 &&
1117                N->getOperand(2).getValueType() == MVT::i32 &&
1118                N->getNumOperands() == 2 && "Unknown two-register ret value!");
1119         Val = Select(N->getOperand(2));
1120         Chain = CurDAG->getCopyToReg(Chain, PPC::R4, Val);
1121       }
1122     }
1123
1124     // Finally, select this to a blr (return) instruction.
1125     CurDAG->SelectNodeTo(N, MVT::Other, PPC::BLR, Chain);
1126     break;
1127   }
1128   case ISD::BR:
1129     CurDAG->SelectNodeTo(N, MVT::Other, PPC::B, N->getOperand(1),
1130                          Select(N->getOperand(0)));
1131     break;
1132   case ISD::BR_CC:
1133   case ISD::BRTWOWAY_CC: {
1134     SDOperand Chain = Select(N->getOperand(0));
1135     MachineBasicBlock *Dest =
1136       cast<BasicBlockSDNode>(N->getOperand(4))->getBasicBlock();
1137     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1138     SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
1139     unsigned Opc = getBCCForSetCC(CC);
1140
1141     // If this is a two way branch, then grab the fallthrough basic block
1142     // argument and build a PowerPC branch pseudo-op, suitable for long branch
1143     // conversion if necessary by the branch selection pass.  Otherwise, emit a
1144     // standard conditional branch.
1145     if (N->getOpcode() == ISD::BRTWOWAY_CC) {
1146       MachineBasicBlock *Fallthrough =
1147         cast<BasicBlockSDNode>(N->getOperand(5))->getBasicBlock();
1148       SDOperand CB = CurDAG->getTargetNode(PPC::COND_BRANCH, MVT::Other,
1149                                            CondCode, getI32Imm(Opc),
1150                                            N->getOperand(4), N->getOperand(5),
1151                                            Chain);
1152       CurDAG->SelectNodeTo(N, MVT::Other, PPC::B, N->getOperand(5), CB);
1153     } else {
1154       // Iterate to the next basic block
1155       ilist<MachineBasicBlock>::iterator It = BB;
1156       ++It;
1157
1158       // If the fallthrough path is off the end of the function, which would be
1159       // undefined behavior, set it to be the same as the current block because
1160       // we have nothing better to set it to, and leaving it alone will cause
1161       // the PowerPC Branch Selection pass to crash.
1162       if (It == BB->getParent()->end()) It = Dest;
1163       CurDAG->SelectNodeTo(N, MVT::Other, PPC::COND_BRANCH, CondCode,
1164                            getI32Imm(Opc), N->getOperand(4),
1165                            CurDAG->getBasicBlock(It), Chain);
1166     }
1167     break;
1168   }
1169   }
1170   return SDOperand(N, Op.ResNo);
1171 }
1172
1173
1174 /// createPPC32ISelDag - This pass converts a legalized DAG into a 
1175 /// PowerPC-specific DAG, ready for instruction scheduling.
1176 ///
1177 FunctionPass *llvm::createPPC32ISelDag(TargetMachine &TM) {
1178   return new PPC32DAGToDAGISel(TM);
1179 }
1180