Implement selection of inline asm memory operands
[oota-llvm.git] / lib / Target / PowerPC / PPCISelDAGToDAG.cpp
1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for PowerPC,
11 // converting from a legalized dag to a PPC dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PPC.h"
16 #include "PPCTargetMachine.h"
17 #include "PPCISelLowering.h"
18 #include "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/Constants.h"
26 #include "llvm/GlobalValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/MathExtras.h"
29 #include <iostream>
30 #include <set>
31 using namespace llvm;
32
33 namespace {
34   Statistic<> FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");
35     
36   //===--------------------------------------------------------------------===//
37   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
38   /// instructions for SelectionDAG operations.
39   ///
40   class PPCDAGToDAGISel : public SelectionDAGISel {
41     PPCTargetLowering PPCLowering;
42     unsigned GlobalBaseReg;
43   public:
44     PPCDAGToDAGISel(TargetMachine &TM)
45       : SelectionDAGISel(PPCLowering), PPCLowering(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     void Select(SDOperand &Result, SDOperand Op);
66     
67     SDNode *SelectBitfieldInsert(SDNode *N);
68
69     /// SelectCC - Select a comparison of the specified values with the
70     /// specified condition code, returning the CR# of the expression.
71     SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
72
73     /// SelectAddrImm - Returns true if the address N can be represented by
74     /// a base register plus a signed 16-bit displacement [r+imm].
75     bool SelectAddrImm(SDOperand N, SDOperand &Disp, SDOperand &Base);
76       
77     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
78     /// represented as an indexed [r+r] operation.  Returns false if it can
79     /// be represented by [r+imm], which are preferred.
80     bool SelectAddrIdx(SDOperand N, SDOperand &Base, SDOperand &Index);
81     
82     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
83     /// represented as an indexed [r+r] operation.
84     bool SelectAddrIdxOnly(SDOperand N, SDOperand &Base, SDOperand &Index);
85
86     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
87     /// inline asm expressions.
88     virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
89                                               char ConstraintCode,
90                                               std::vector<SDOperand> &OutOps,
91                                               SelectionDAG &DAG) {
92       SDOperand Op0, Op1;
93       switch (ConstraintCode) {
94       default: return true;
95       case 'm':   // memory
96         if (!SelectAddrIdx(Op, Op0, Op1))
97           SelectAddrImm(Op, Op0, Op1);
98         break;
99       case 'o':   // offsetable
100         if (!SelectAddrImm(Op, Op0, Op1)) {
101           Select(Op0, Op);     // r+0.
102           Op1 = getI32Imm(0);
103         }
104         break;
105       case 'v':   // not offsetable
106         SelectAddrIdxOnly(Op, Op0, Op1);
107         break;
108       }
109       
110       OutOps.push_back(Op0);
111       OutOps.push_back(Op1);
112       return false;
113     }
114     
115     SDOperand BuildSDIVSequence(SDNode *N);
116     SDOperand BuildUDIVSequence(SDNode *N);
117     
118     /// InstructionSelectBasicBlock - This callback is invoked by
119     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
120     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
121     
122     virtual const char *getPassName() const {
123       return "PowerPC DAG->DAG Pattern Instruction Selection";
124     } 
125
126 // Include the pieces autogenerated from the target description.
127 #include "PPCGenDAGISel.inc"
128     
129 private:
130     SDOperand SelectADD_PARTS(SDOperand Op);
131     SDOperand SelectSUB_PARTS(SDOperand Op);
132     SDOperand SelectSETCC(SDOperand Op);
133     SDOperand SelectCALL(SDOperand Op);
134   };
135 }
136
137 /// InstructionSelectBasicBlock - This callback is invoked by
138 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
139 void PPCDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
140   DEBUG(BB->dump());
141   
142   // The selection process is inherently a bottom-up recursive process (users
143   // select their uses before themselves).  Given infinite stack space, we
144   // could just start selecting on the root and traverse the whole graph.  In
145   // practice however, this causes us to run out of stack space on large basic
146   // blocks.  To avoid this problem, select the entry node, then all its uses,
147   // iteratively instead of recursively.
148   std::vector<SDOperand> Worklist;
149   Worklist.push_back(DAG.getEntryNode());
150   
151   // Note that we can do this in the PPC target (scanning forward across token
152   // chain edges) because no nodes ever get folded across these edges.  On a
153   // target like X86 which supports load/modify/store operations, this would
154   // have to be more careful.
155   while (!Worklist.empty()) {
156     SDOperand Node = Worklist.back();
157     Worklist.pop_back();
158     
159     // Chose from the least deep of the top two nodes.
160     if (!Worklist.empty() &&
161         Worklist.back().Val->getNodeDepth() < Node.Val->getNodeDepth())
162       std::swap(Worklist.back(), Node);
163     
164     if ((Node.Val->getOpcode() >= ISD::BUILTIN_OP_END &&
165          Node.Val->getOpcode() < PPCISD::FIRST_NUMBER) ||
166         CodeGenMap.count(Node)) continue;
167     
168     for (SDNode::use_iterator UI = Node.Val->use_begin(),
169          E = Node.Val->use_end(); UI != E; ++UI) {
170       // Scan the values.  If this use has a value that is a token chain, add it
171       // to the worklist.
172       SDNode *User = *UI;
173       for (unsigned i = 0, e = User->getNumValues(); i != e; ++i)
174         if (User->getValueType(i) == MVT::Other) {
175           Worklist.push_back(SDOperand(User, i));
176           break; 
177         }
178     }
179
180     // Finally, legalize this node.
181     SDOperand Dummy;
182     Select(Dummy, Node);
183   }
184     
185   // Select target instructions for the DAG.
186   DAG.setRoot(SelectRoot(DAG.getRoot()));
187   CodeGenMap.clear();
188   DAG.RemoveDeadNodes();
189   
190   // Emit machine code to BB. 
191   ScheduleAndEmitDAG(DAG);
192 }
193
194 /// getGlobalBaseReg - Output the instructions required to put the
195 /// base address to use for accessing globals into a register.
196 ///
197 SDOperand PPCDAGToDAGISel::getGlobalBaseReg() {
198   if (!GlobalBaseReg) {
199     // Insert the set of GlobalBaseReg into the first MBB of the function
200     MachineBasicBlock &FirstMBB = BB->getParent()->front();
201     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
202     SSARegMap *RegMap = BB->getParent()->getSSARegMap();
203     // FIXME: when we get to LP64, we will need to create the appropriate
204     // type of register here.
205     GlobalBaseReg = RegMap->createVirtualRegister(PPC::GPRCRegisterClass);
206     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
207     BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
208   }
209   return CurDAG->getRegister(GlobalBaseReg, MVT::i32);
210 }
211
212
213 // isIntImmediate - This method tests to see if a constant operand.
214 // If so Imm will receive the 32 bit value.
215 static bool isIntImmediate(SDNode *N, unsigned& Imm) {
216   if (N->getOpcode() == ISD::Constant) {
217     Imm = cast<ConstantSDNode>(N)->getValue();
218     return true;
219   }
220   return false;
221 }
222
223 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
224 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
225 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
226 // not, since all 1s are not contiguous.
227 static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
228   if (isShiftedMask_32(Val)) {
229     // look for the first non-zero bit
230     MB = CountLeadingZeros_32(Val);
231     // look for the first zero bit after the run of ones
232     ME = CountLeadingZeros_32((Val - 1) ^ Val);
233     return true;
234   } else {
235     Val = ~Val; // invert mask
236     if (isShiftedMask_32(Val)) {
237       // effectively look for the first zero bit
238       ME = CountLeadingZeros_32(Val) - 1;
239       // effectively look for the first one bit after the run of zeros
240       MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
241       return true;
242     }
243   }
244   // no run present
245   return false;
246 }
247
248 // isRotateAndMask - Returns true if Mask and Shift can be folded into a rotate
249 // and mask opcode and mask operation.
250 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
251                             unsigned &SH, unsigned &MB, unsigned &ME) {
252   // Don't even go down this path for i64, since different logic will be
253   // necessary for rldicl/rldicr/rldimi.
254   if (N->getValueType(0) != MVT::i32)
255     return false;
256
257   unsigned Shift  = 32;
258   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
259   unsigned Opcode = N->getOpcode();
260   if (N->getNumOperands() != 2 ||
261       !isIntImmediate(N->getOperand(1).Val, Shift) || (Shift > 31))
262     return false;
263   
264   if (Opcode == ISD::SHL) {
265     // apply shift left to mask if it comes first
266     if (IsShiftMask) Mask = Mask << Shift;
267     // determine which bits are made indeterminant by shift
268     Indeterminant = ~(0xFFFFFFFFu << Shift);
269   } else if (Opcode == ISD::SRL) { 
270     // apply shift right to mask if it comes first
271     if (IsShiftMask) Mask = Mask >> Shift;
272     // determine which bits are made indeterminant by shift
273     Indeterminant = ~(0xFFFFFFFFu >> Shift);
274     // adjust for the left rotate
275     Shift = 32 - Shift;
276   } else {
277     return false;
278   }
279   
280   // if the mask doesn't intersect any Indeterminant bits
281   if (Mask && !(Mask & Indeterminant)) {
282     SH = Shift;
283     // make sure the mask is still a mask (wrap arounds may not be)
284     return isRunOfOnes(Mask, MB, ME);
285   }
286   return false;
287 }
288
289 // isOpcWithIntImmediate - This method tests to see if the node is a specific
290 // opcode and that it has a immediate integer right operand.
291 // If so Imm will receive the 32 bit value.
292 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
293   return N->getOpcode() == Opc && isIntImmediate(N->getOperand(1).Val, Imm);
294 }
295
296 // isIntImmediate - This method tests to see if a constant operand.
297 // If so Imm will receive the 32 bit value.
298 static bool isIntImmediate(SDOperand N, unsigned& Imm) {
299   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
300     Imm = (unsigned)CN->getSignExtended();
301     return true;
302   }
303   return false;
304 }
305
306 /// SelectBitfieldInsert - turn an or of two masked values into
307 /// the rotate left word immediate then mask insert (rlwimi) instruction.
308 /// Returns true on success, false if the caller still needs to select OR.
309 ///
310 /// Patterns matched:
311 /// 1. or shl, and   5. or and, and
312 /// 2. or and, shl   6. or shl, shr
313 /// 3. or shr, and   7. or shr, shl
314 /// 4. or and, shr
315 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
316   bool IsRotate = false;
317   unsigned TgtMask = 0xFFFFFFFF, InsMask = 0xFFFFFFFF, SH = 0;
318   unsigned Value;
319   
320   SDOperand Op0 = N->getOperand(0);
321   SDOperand Op1 = N->getOperand(1);
322   
323   unsigned Op0Opc = Op0.getOpcode();
324   unsigned Op1Opc = Op1.getOpcode();
325   
326   // Verify that we have the correct opcodes
327   if (ISD::SHL != Op0Opc && ISD::SRL != Op0Opc && ISD::AND != Op0Opc)
328     return false;
329   if (ISD::SHL != Op1Opc && ISD::SRL != Op1Opc && ISD::AND != Op1Opc)
330     return false;
331   
332   // Generate Mask value for Target
333   if (isIntImmediate(Op0.getOperand(1), Value)) {
334     switch(Op0Opc) {
335     case ISD::SHL: TgtMask <<= Value; break;
336     case ISD::SRL: TgtMask >>= Value; break;
337     case ISD::AND: TgtMask &= Value; break;
338     }
339   } else {
340     return 0;
341   }
342   
343   // Generate Mask value for Insert
344   if (!isIntImmediate(Op1.getOperand(1), Value))
345     return 0;
346   
347   switch(Op1Opc) {
348   case ISD::SHL:
349     SH = Value;
350     InsMask <<= SH;
351     if (Op0Opc == ISD::SRL) IsRotate = true;
352     break;
353   case ISD::SRL:
354     SH = Value;
355     InsMask >>= SH;
356     SH = 32-SH;
357     if (Op0Opc == ISD::SHL) IsRotate = true;
358     break;
359   case ISD::AND:
360     InsMask &= Value;
361     break;
362   }
363   
364   // If both of the inputs are ANDs and one of them has a logical shift by
365   // constant as its input, make that AND the inserted value so that we can
366   // combine the shift into the rotate part of the rlwimi instruction
367   bool IsAndWithShiftOp = false;
368   if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
369     if (Op1.getOperand(0).getOpcode() == ISD::SHL ||
370         Op1.getOperand(0).getOpcode() == ISD::SRL) {
371       if (isIntImmediate(Op1.getOperand(0).getOperand(1), Value)) {
372         SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
373         IsAndWithShiftOp = true;
374       }
375     } else if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
376                Op0.getOperand(0).getOpcode() == ISD::SRL) {
377       if (isIntImmediate(Op0.getOperand(0).getOperand(1), Value)) {
378         std::swap(Op0, Op1);
379         std::swap(TgtMask, InsMask);
380         SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
381         IsAndWithShiftOp = true;
382       }
383     }
384   }
385   
386   // Verify that the Target mask and Insert mask together form a full word mask
387   // and that the Insert mask is a run of set bits (which implies both are runs
388   // of set bits).  Given that, Select the arguments and generate the rlwimi
389   // instruction.
390   unsigned MB, ME;
391   if (((TgtMask & InsMask) == 0) && isRunOfOnes(InsMask, MB, ME)) {
392     bool fullMask = (TgtMask ^ InsMask) == 0xFFFFFFFF;
393     bool Op0IsAND = Op0Opc == ISD::AND;
394     // Check for rotlwi / rotrwi here, a special case of bitfield insert
395     // where both bitfield halves are sourced from the same value.
396     if (IsRotate && fullMask &&
397         N->getOperand(0).getOperand(0) == N->getOperand(1).getOperand(0)) {
398       SDOperand Tmp;
399       Select(Tmp, N->getOperand(0).getOperand(0));
400       return CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Tmp,
401                                    getI32Imm(SH), getI32Imm(0), getI32Imm(31));
402     }
403     SDOperand Tmp1, Tmp2;
404     Select(Tmp1, ((Op0IsAND && fullMask) ? Op0.getOperand(0) : Op0));
405     Select(Tmp2, (IsAndWithShiftOp ? Op1.getOperand(0).getOperand(0)
406                                    : Op1.getOperand(0)));
407     return CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2,
408                                  getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
409   }
410   return 0;
411 }
412
413 /// SelectAddrImm - Returns true if the address N can be represented by
414 /// a base register plus a signed 16-bit displacement [r+imm].
415 bool PPCDAGToDAGISel::SelectAddrImm(SDOperand N, SDOperand &Disp, 
416                                     SDOperand &Base) {
417   if (N.getOpcode() == ISD::ADD) {
418     unsigned imm = 0;
419     if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm)) {
420       Disp = getI32Imm(imm & 0xFFFF);
421       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
422         Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
423       } else {
424         Base = N.getOperand(0);
425       }
426       return true; // [r+i]
427     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
428       // Match LOAD (ADD (X, Lo(G))).
429       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
430              && "Cannot handle constant offsets yet!");
431       Disp = N.getOperand(1).getOperand(0);  // The global address.
432       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
433              Disp.getOpcode() == ISD::TargetConstantPool);
434       Base = N.getOperand(0);
435       return true;  // [&g+r]
436     }
437     return false;   // [r+r]
438   }
439   Disp = getI32Imm(0);
440   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
441     Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
442   else
443     Base = N;
444   return true;      // [r+0]
445 }
446
447 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
448 /// represented as an indexed [r+r] operation.  Returns false if it can
449 /// be represented by [r+imm], which are preferred.
450 bool PPCDAGToDAGISel::SelectAddrIdx(SDOperand N, SDOperand &Base, 
451                                     SDOperand &Index) {
452   // Check to see if we can represent this as an [r+imm] address instead, 
453   // which will fail if the address is more profitably represented as an
454   // [r+r] address.
455   if (SelectAddrImm(N, Base, Index))
456     return false;
457   
458   if (N.getOpcode() == ISD::ADD) {
459     Base = N.getOperand(0);
460     Index = N.getOperand(1);
461     return true;
462   }
463  
464   Base = CurDAG->getRegister(PPC::R0, MVT::i32);
465   Index = N;
466   return true;
467 }
468
469 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
470 /// represented as an indexed [r+r] operation.
471 bool PPCDAGToDAGISel::SelectAddrIdxOnly(SDOperand N, SDOperand &Base, 
472                                         SDOperand &Index) {
473   if (N.getOpcode() == ISD::ADD) {
474     Base = N.getOperand(0);
475     Index = N.getOperand(1);
476     return true;
477   }
478   
479   Base = CurDAG->getRegister(PPC::R0, MVT::i32);
480   Index = N;
481   return true;
482 }
483
484 /// SelectCC - Select a comparison of the specified values with the specified
485 /// condition code, returning the CR# of the expression.
486 SDOperand PPCDAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
487                                     ISD::CondCode CC) {
488   // Always select the LHS.
489   Select(LHS, LHS);
490
491   // Use U to determine whether the SETCC immediate range is signed or not.
492   if (MVT::isInteger(LHS.getValueType())) {
493     bool U = ISD::isUnsignedIntSetCC(CC);
494     unsigned Imm;
495     if (isIntImmediate(RHS, Imm) && 
496         ((U && isUInt16(Imm)) || (!U && isInt16(Imm))))
497       return SDOperand(CurDAG->getTargetNode(U ? PPC::CMPLWI : PPC::CMPWI,
498                                     MVT::i32, LHS, getI32Imm(Imm & 0xFFFF)), 0);
499     Select(RHS, RHS);
500     return SDOperand(CurDAG->getTargetNode(U ? PPC::CMPLW : PPC::CMPW, MVT::i32,
501                                            LHS, RHS), 0);
502   } else if (LHS.getValueType() == MVT::f32) {
503     Select(RHS, RHS);
504     return SDOperand(CurDAG->getTargetNode(PPC::FCMPUS, MVT::i32, LHS, RHS), 0);
505   } else {
506     Select(RHS, RHS);
507     return SDOperand(CurDAG->getTargetNode(PPC::FCMPUD, MVT::i32, LHS, RHS), 0);
508   }
509 }
510
511 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
512 /// to Condition.
513 static unsigned getBCCForSetCC(ISD::CondCode CC) {
514   switch (CC) {
515   default: assert(0 && "Unknown condition!"); abort();
516   case ISD::SETOEQ:    // FIXME: This is incorrect see PR642.
517   case ISD::SETEQ:  return PPC::BEQ;
518   case ISD::SETONE:    // FIXME: This is incorrect see PR642.
519   case ISD::SETNE:  return PPC::BNE;
520   case ISD::SETOLT:    // FIXME: This is incorrect see PR642.
521   case ISD::SETULT:
522   case ISD::SETLT:  return PPC::BLT;
523   case ISD::SETOLE:    // FIXME: This is incorrect see PR642.
524   case ISD::SETULE:
525   case ISD::SETLE:  return PPC::BLE;
526   case ISD::SETOGT:    // FIXME: This is incorrect see PR642.
527   case ISD::SETUGT:
528   case ISD::SETGT:  return PPC::BGT;
529   case ISD::SETOGE:    // FIXME: This is incorrect see PR642.
530   case ISD::SETUGE:
531   case ISD::SETGE:  return PPC::BGE;
532     
533   case ISD::SETO:   return PPC::BUN;
534   case ISD::SETUO:  return PPC::BNU;
535   }
536   return 0;
537 }
538
539 /// getCRIdxForSetCC - Return the index of the condition register field
540 /// associated with the SetCC condition, and whether or not the field is
541 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
542 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
543   switch (CC) {
544   default: assert(0 && "Unknown condition!"); abort();
545   case ISD::SETOLT:  // FIXME: This is incorrect see PR642.
546   case ISD::SETULT:
547   case ISD::SETLT:  Inv = false;  return 0;
548   case ISD::SETOGE:  // FIXME: This is incorrect see PR642.
549   case ISD::SETUGE:
550   case ISD::SETGE:  Inv = true;   return 0;
551   case ISD::SETOGT:  // FIXME: This is incorrect see PR642.
552   case ISD::SETUGT:
553   case ISD::SETGT:  Inv = false;  return 1;
554   case ISD::SETOLE:  // FIXME: This is incorrect see PR642.
555   case ISD::SETULE:
556   case ISD::SETLE:  Inv = true;   return 1;
557   case ISD::SETOEQ:  // FIXME: This is incorrect see PR642.
558   case ISD::SETEQ:  Inv = false;  return 2;
559   case ISD::SETONE:  // FIXME: This is incorrect see PR642.
560   case ISD::SETNE:  Inv = true;   return 2;
561   case ISD::SETO:   Inv = true;   return 3;
562   case ISD::SETUO:  Inv = false;  return 3;
563   }
564   return 0;
565 }
566
567 SDOperand PPCDAGToDAGISel::SelectSETCC(SDOperand Op) {
568   SDNode *N = Op.Val;
569   unsigned Imm;
570   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
571   if (isIntImmediate(N->getOperand(1), Imm)) {
572     // We can codegen setcc op, imm very efficiently compared to a brcond.
573     // Check for those cases here.
574     // setcc op, 0
575     if (Imm == 0) {
576       SDOperand Op;
577       Select(Op, N->getOperand(0));
578       switch (CC) {
579       default: break;
580       case ISD::SETEQ:
581         Op = SDOperand(CurDAG->getTargetNode(PPC::CNTLZW, MVT::i32, Op), 0);
582         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(27),
583                                     getI32Imm(5), getI32Imm(31));
584       case ISD::SETNE: {
585         SDOperand AD =
586           SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
587                                           Op, getI32Imm(~0U)), 0);
588         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, 
589                                     AD.getValue(1));
590       }
591       case ISD::SETLT:
592         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(1),
593                                     getI32Imm(31), getI32Imm(31));
594       case ISD::SETGT: {
595         SDOperand T =
596           SDOperand(CurDAG->getTargetNode(PPC::NEG, MVT::i32, Op), 0);
597         T = SDOperand(CurDAG->getTargetNode(PPC::ANDC, MVT::i32, T, Op), 0);
598         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, T, getI32Imm(1),
599                                     getI32Imm(31), getI32Imm(31));
600       }
601       }
602     } else if (Imm == ~0U) {        // setcc op, -1
603       SDOperand Op;
604       Select(Op, N->getOperand(0));
605       switch (CC) {
606       default: break;
607       case ISD::SETEQ:
608         Op = SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
609                                              Op, getI32Imm(1)), 0);
610         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
611                               SDOperand(CurDAG->getTargetNode(PPC::LI, MVT::i32,
612                                                               getI32Imm(0)), 0),
613                                     Op.getValue(1));
614       case ISD::SETNE: {
615         Op = SDOperand(CurDAG->getTargetNode(PPC::NOR, MVT::i32, Op, Op), 0);
616         SDNode *AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
617                                            Op, getI32Imm(~0U));
618         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDOperand(AD, 0), Op, 
619                                     SDOperand(AD, 1));
620       }
621       case ISD::SETLT: {
622         SDOperand AD = SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32, Op,
623                                                        getI32Imm(1)), 0);
624         SDOperand AN = SDOperand(CurDAG->getTargetNode(PPC::AND, MVT::i32, AD,
625                                                        Op), 0);
626         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, AN, getI32Imm(1),
627                                     getI32Imm(31), getI32Imm(31));
628       }
629       case ISD::SETGT:
630         Op = SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Op,
631                                              getI32Imm(1), getI32Imm(31),
632                                              getI32Imm(31)), 0);
633         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1));
634       }
635     }
636   }
637   
638   bool Inv;
639   unsigned Idx = getCRIdxForSetCC(CC, Inv);
640   SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
641   SDOperand IntCR;
642   
643   // Force the ccreg into CR7.
644   SDOperand CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
645   
646   SDOperand InFlag(0, 0);  // Null incoming flag value.
647   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), CR7Reg, CCReg, 
648                                InFlag).getValue(1);
649   
650   if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
651     IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, CR7Reg,
652                                             CCReg), 0);
653   else
654     IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, CCReg), 0);
655   
656   if (!Inv) {
657     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, IntCR,
658                                 getI32Imm((32-(3-Idx)) & 31),
659                                 getI32Imm(31), getI32Imm(31));
660   } else {
661     SDOperand Tmp =
662       SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, IntCR,
663                                       getI32Imm((32-(3-Idx)) & 31),
664                                       getI32Imm(31),getI32Imm(31)), 0);
665     return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
666   }
667 }
668
669 /// isCallCompatibleAddress - Return true if the specified 32-bit value is
670 /// representable in the immediate field of a Bx instruction.
671 static bool isCallCompatibleAddress(ConstantSDNode *C) {
672   int Addr = C->getValue();
673   if (Addr & 3) return false;  // Low 2 bits are implicitly zero.
674   return (Addr << 6 >> 6) == Addr;  // Top 6 bits have to be sext of immediate.
675 }
676
677 SDOperand PPCDAGToDAGISel::SelectCALL(SDOperand Op) {
678   SDNode *N = Op.Val;
679   SDOperand Chain;
680   Select(Chain, N->getOperand(0));
681   
682   unsigned CallOpcode;
683   std::vector<SDOperand> CallOperands;
684   
685   if (GlobalAddressSDNode *GASD =
686       dyn_cast<GlobalAddressSDNode>(N->getOperand(1))) {
687     CallOpcode = PPC::BL;
688     CallOperands.push_back(N->getOperand(1));
689   } else if (ExternalSymbolSDNode *ESSDN =
690              dyn_cast<ExternalSymbolSDNode>(N->getOperand(1))) {
691     CallOpcode = PPC::BL;
692     CallOperands.push_back(N->getOperand(1));
693   } else if (isa<ConstantSDNode>(N->getOperand(1)) &&
694              isCallCompatibleAddress(cast<ConstantSDNode>(N->getOperand(1)))) {
695     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
696     CallOpcode = PPC::BLA;
697     CallOperands.push_back(getI32Imm((int)C->getValue() >> 2));
698   } else {
699     // Copy the callee address into the CTR register.
700     SDOperand Callee;
701     Select(Callee, N->getOperand(1));
702     Chain = SDOperand(CurDAG->getTargetNode(PPC::MTCTR, MVT::Other, Callee,
703                                             Chain), 0);
704     
705     // Copy the callee address into R12 on darwin.
706     SDOperand R12 = CurDAG->getRegister(PPC::R12, MVT::i32);
707     Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, Chain, R12, Callee);
708
709     CallOperands.push_back(R12);
710     CallOpcode = PPC::BCTRL;
711   }
712   
713   unsigned GPR_idx = 0, FPR_idx = 0;
714   static const unsigned GPR[] = {
715     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
716     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
717   };
718   static const unsigned FPR[] = {
719     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
720     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
721   };
722   
723   SDOperand InFlag;  // Null incoming flag value.
724   
725   for (unsigned i = 2, e = N->getNumOperands(); i != e; ++i) {
726     unsigned DestReg = 0;
727     MVT::ValueType RegTy = N->getOperand(i).getValueType();
728     if (RegTy == MVT::i32) {
729       assert(GPR_idx < 8 && "Too many int args");
730       DestReg = GPR[GPR_idx++];
731     } else {
732       assert(MVT::isFloatingPoint(N->getOperand(i).getValueType()) &&
733              "Unpromoted integer arg?");
734       assert(FPR_idx < 13 && "Too many fp args");
735       DestReg = FPR[FPR_idx++];
736     }
737     
738     if (N->getOperand(i).getOpcode() != ISD::UNDEF) {
739       SDOperand Val;
740       Select(Val, N->getOperand(i));
741       Chain = CurDAG->getCopyToReg(Chain, DestReg, Val, InFlag);
742       InFlag = Chain.getValue(1);
743       CallOperands.push_back(CurDAG->getRegister(DestReg, RegTy));
744     }
745   }
746   
747   // Finally, once everything is in registers to pass to the call, emit the
748   // call itself.
749   if (InFlag.Val)
750     CallOperands.push_back(InFlag);   // Strong dep on register copies.
751   else
752     CallOperands.push_back(Chain);    // Weak dep on whatever occurs before
753   Chain = SDOperand(CurDAG->getTargetNode(CallOpcode, MVT::Other, MVT::Flag,
754                                           CallOperands), 0);
755   
756   std::vector<SDOperand> CallResults;
757   
758   // If the call has results, copy the values out of the ret val registers.
759   switch (N->getValueType(0)) {
760     default: assert(0 && "Unexpected ret value!");
761     case MVT::Other: break;
762     case MVT::i32:
763       if (N->getValueType(1) == MVT::i32) {
764         Chain = CurDAG->getCopyFromReg(Chain, PPC::R4, MVT::i32, 
765                                        Chain.getValue(1)).getValue(1);
766         CallResults.push_back(Chain.getValue(0));
767         Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32,
768                                        Chain.getValue(2)).getValue(1);
769         CallResults.push_back(Chain.getValue(0));
770       } else {
771         Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32,
772                                        Chain.getValue(1)).getValue(1);
773         CallResults.push_back(Chain.getValue(0));
774       }
775       break;
776     case MVT::f32:
777     case MVT::f64:
778       Chain = CurDAG->getCopyFromReg(Chain, PPC::F1, N->getValueType(0),
779                                      Chain.getValue(1)).getValue(1);
780       CallResults.push_back(Chain.getValue(0));
781       break;
782   }
783   
784   CallResults.push_back(Chain);
785   for (unsigned i = 0, e = CallResults.size(); i != e; ++i)
786     CodeGenMap[Op.getValue(i)] = CallResults[i];
787   return CallResults[Op.ResNo];
788 }
789
790 // Select - Convert the specified operand from a target-independent to a
791 // target-specific node if it hasn't already been changed.
792 void PPCDAGToDAGISel::Select(SDOperand &Result, SDOperand Op) {
793   SDNode *N = Op.Val;
794   if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
795       N->getOpcode() < PPCISD::FIRST_NUMBER) {
796     Result = Op;
797     return;   // Already selected.
798   }
799
800   // If this has already been converted, use it.
801   std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
802   if (CGMI != CodeGenMap.end()) {
803     Result = CGMI->second;
804     return;
805   }
806   
807   switch (N->getOpcode()) {
808   default: break;
809   case ISD::SETCC:
810     Result = SelectSETCC(Op);
811     return;
812   case PPCISD::CALL:
813     Result = SelectCALL(Op);
814     return;
815   case PPCISD::GlobalBaseReg:
816     Result = getGlobalBaseReg();
817     return;
818     
819   case ISD::FrameIndex: {
820     int FI = cast<FrameIndexSDNode>(N)->getIndex();
821     if (N->hasOneUse()) {
822       Result = CurDAG->SelectNodeTo(N, PPC::ADDI, MVT::i32,
823                                     CurDAG->getTargetFrameIndex(FI, MVT::i32),
824                                     getI32Imm(0));
825       return;
826     }
827     Result = CodeGenMap[Op] = 
828       SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32,
829                                       CurDAG->getTargetFrameIndex(FI, MVT::i32),
830                                       getI32Imm(0)), 0);
831     return;
832   }
833   case ISD::SDIV: {
834     // FIXME: since this depends on the setting of the carry flag from the srawi
835     //        we should really be making notes about that for the scheduler.
836     // FIXME: It sure would be nice if we could cheaply recognize the 
837     //        srl/add/sra pattern the dag combiner will generate for this as
838     //        sra/addze rather than having to handle sdiv ourselves.  oh well.
839     unsigned Imm;
840     if (isIntImmediate(N->getOperand(1), Imm)) {
841       SDOperand N0;
842       Select(N0, N->getOperand(0));
843       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
844         SDNode *Op =
845           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
846                                 N0, getI32Imm(Log2_32(Imm)));
847         Result = CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
848                                       SDOperand(Op, 0), SDOperand(Op, 1));
849       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
850         SDNode *Op =
851           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
852                                 N0, getI32Imm(Log2_32(-Imm)));
853         SDOperand PT =
854           SDOperand(CurDAG->getTargetNode(PPC::ADDZE, MVT::i32,
855                                           SDOperand(Op, 0), SDOperand(Op, 1)),
856                     0);
857         Result = CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
858       }
859       return;
860     }
861     
862     // Other cases are autogenerated.
863     break;
864   }
865   case ISD::AND: {
866     unsigned Imm, Imm2;
867     // If this is an and of a value rotated between 0 and 31 bits and then and'd
868     // with a mask, emit rlwinm
869     if (isIntImmediate(N->getOperand(1), Imm) && (isShiftedMask_32(Imm) ||
870                                                   isShiftedMask_32(~Imm))) {
871       SDOperand Val;
872       unsigned SH, MB, ME;
873       if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
874         Select(Val, N->getOperand(0).getOperand(0));
875       } else if (Imm == 0) {
876         // AND X, 0 -> 0, not "rlwinm 32".
877         Select(Result, N->getOperand(1));
878         return ;
879       } else {        
880         Select(Val, N->getOperand(0));
881         isRunOfOnes(Imm, MB, ME);
882         SH = 0;
883       }
884       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Val,
885                                     getI32Imm(SH), getI32Imm(MB),
886                                     getI32Imm(ME));
887       return;
888     }
889     // ISD::OR doesn't get all the bitfield insertion fun.
890     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
891     if (isIntImmediate(N->getOperand(1), Imm) && 
892         N->getOperand(0).getOpcode() == ISD::OR &&
893         isIntImmediate(N->getOperand(0).getOperand(1), Imm2)) {
894       unsigned MB, ME;
895       Imm = ~(Imm^Imm2);
896       if (isRunOfOnes(Imm, MB, ME)) {
897         SDOperand Tmp1, Tmp2;
898         Select(Tmp1, N->getOperand(0).getOperand(0));
899         Select(Tmp2, N->getOperand(0).getOperand(1));
900         Result = SDOperand(CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32,
901                                                  Tmp1, Tmp2,
902                                                  getI32Imm(0), getI32Imm(MB),
903                                                  getI32Imm(ME)), 0);
904         return;
905       }
906     }
907     
908     // Other cases are autogenerated.
909     break;
910   }
911   case ISD::OR:
912     if (SDNode *I = SelectBitfieldInsert(N)) {
913       Result = CodeGenMap[Op] = SDOperand(I, 0);
914       return;
915     }
916       
917     // Other cases are autogenerated.
918     break;
919   case ISD::SHL: {
920     unsigned Imm, SH, MB, ME;
921     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
922         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
923       SDOperand Val;
924       Select(Val, N->getOperand(0).getOperand(0));
925       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, 
926                                     Val, getI32Imm(SH), getI32Imm(MB),
927                                     getI32Imm(ME));
928       return;
929     }
930     
931     // Other cases are autogenerated.
932     break;
933   }
934   case ISD::SRL: {
935     unsigned Imm, SH, MB, ME;
936     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
937         isRotateAndMask(N, Imm, true, SH, MB, ME)) { 
938       SDOperand Val;
939       Select(Val, N->getOperand(0).getOperand(0));
940       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, 
941                                     Val, getI32Imm(SH & 0x1F), getI32Imm(MB),
942                                     getI32Imm(ME));
943       return;
944     }
945     
946     // Other cases are autogenerated.
947     break;
948   }
949   case ISD::SELECT_CC: {
950     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
951     
952     // handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
953     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
954       if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
955         if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
956           if (N1C->isNullValue() && N3C->isNullValue() &&
957               N2C->getValue() == 1ULL && CC == ISD::SETNE) {
958             SDOperand LHS;
959             Select(LHS, N->getOperand(0));
960             SDNode *Tmp =
961               CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
962                                     LHS, getI32Imm(~0U));
963             Result = CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
964                                           SDOperand(Tmp, 0), LHS,
965                                           SDOperand(Tmp, 1));
966             return;
967           }
968
969     SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
970     unsigned BROpc = getBCCForSetCC(CC);
971
972     bool isFP = MVT::isFloatingPoint(N->getValueType(0));
973     unsigned SelectCCOp;
974     if (MVT::isInteger(N->getValueType(0)))
975       SelectCCOp = PPC::SELECT_CC_Int;
976     else if (N->getValueType(0) == MVT::f32)
977       SelectCCOp = PPC::SELECT_CC_F4;
978     else
979       SelectCCOp = PPC::SELECT_CC_F8;
980     SDOperand N2, N3;
981     Select(N2, N->getOperand(2));
982     Select(N3, N->getOperand(3));
983     Result = CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), CCReg,
984                                   N2, N3, getI32Imm(BROpc));
985     return;
986   }
987   case ISD::BR_CC:
988   case ISD::BRTWOWAY_CC: {
989     SDOperand Chain;
990     Select(Chain, N->getOperand(0));
991     MachineBasicBlock *Dest =
992       cast<BasicBlockSDNode>(N->getOperand(4))->getBasicBlock();
993     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
994     SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
995
996     // If this is a two way branch, then grab the fallthrough basic block
997     // argument and build a PowerPC branch pseudo-op, suitable for long branch
998     // conversion if necessary by the branch selection pass.  Otherwise, emit a
999     // standard conditional branch.
1000     if (N->getOpcode() == ISD::BRTWOWAY_CC) {
1001       SDOperand CondTrueBlock = N->getOperand(4);
1002       SDOperand CondFalseBlock = N->getOperand(5);
1003       unsigned Opc = getBCCForSetCC(CC);
1004       SDOperand CB =
1005         SDOperand(CurDAG->getTargetNode(PPC::COND_BRANCH, MVT::Other,
1006                                         CondCode, getI32Imm(Opc),
1007                                         CondTrueBlock, CondFalseBlock,
1008                                         Chain), 0);
1009       Result = CurDAG->SelectNodeTo(N, PPC::B, MVT::Other, CondFalseBlock, CB);
1010     } else {
1011       // Iterate to the next basic block
1012       ilist<MachineBasicBlock>::iterator It = BB;
1013       ++It;
1014
1015       // If the fallthrough path is off the end of the function, which would be
1016       // undefined behavior, set it to be the same as the current block because
1017       // we have nothing better to set it to, and leaving it alone will cause
1018       // the PowerPC Branch Selection pass to crash.
1019       if (It == BB->getParent()->end()) It = Dest;
1020       Result = CurDAG->SelectNodeTo(N, PPC::COND_BRANCH, MVT::Other, CondCode,
1021                                     getI32Imm(getBCCForSetCC(CC)), 
1022                                     N->getOperand(4), CurDAG->getBasicBlock(It),
1023                                     Chain);
1024     }
1025     return;
1026   }
1027   }
1028   
1029   SelectCode(Result, Op);
1030 }
1031
1032
1033 /// createPPCISelDag - This pass converts a legalized DAG into a 
1034 /// PowerPC-specific DAG, ready for instruction scheduling.
1035 ///
1036 FunctionPass *llvm::createPPCISelDag(TargetMachine &TM) {
1037   return new PPCDAGToDAGISel(TM);
1038 }
1039