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