Fix calls whose arguments fit entirely in registers to not break the Chain.
[oota-llvm.git] / lib / Target / PowerPC / PPCISelPattern.cpp
1 //===-- PPC32ISelPattern.cpp - A pattern matching inst selector for PPC32 -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Nate Begeman 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 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PowerPC.h"
15 #include "PowerPCInstrBuilder.h"
16 #include "PowerPCInstrInfo.h"
17 #include "PPC32RegisterInfo.h"
18 #include "llvm/Constants.h"                   // FIXME: REMOVE
19 #include "llvm/Function.h"
20 #include "llvm/CodeGen/MachineConstantPool.h" // FIXME: REMOVE
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/SelectionDAG.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/ADT/Statistic.h"
31 #include <set>
32 #include <algorithm>
33 using namespace llvm;
34
35 //===----------------------------------------------------------------------===//
36 //  PPC32TargetLowering - PPC32 Implementation of the TargetLowering interface
37 namespace {
38   class PPC32TargetLowering : public TargetLowering {
39     int VarArgsFrameIndex;            // FrameIndex for start of varargs area.
40     int ReturnAddrIndex;              // FrameIndex for return slot.
41   public:
42     PPC32TargetLowering(TargetMachine &TM) : TargetLowering(TM) {
43       // Set up the TargetLowering object.
44
45       // Set up the register classes.
46       addRegisterClass(MVT::i32, PPC32::GPRCRegisterClass);
47       addRegisterClass(MVT::f32, PPC32::FPRCRegisterClass);
48       addRegisterClass(MVT::f64, PPC32::FPRCRegisterClass);
49       
50       setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
51       setOperationAction(ISD::MEMSET, MVT::Other, Expand);
52       setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
53
54       computeRegisterProperties();
55     }
56
57     /// LowerArguments - This hook must be implemented to indicate how we should
58     /// lower the arguments for the specified function, into the specified DAG.
59     virtual std::vector<SDOperand>
60     LowerArguments(Function &F, SelectionDAG &DAG);
61     
62     /// LowerCallTo - This hook lowers an abstract call to a function into an
63     /// actual call.
64     virtual std::pair<SDOperand, SDOperand>
65     LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
66                 SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG);
67     
68     virtual std::pair<SDOperand, SDOperand>
69     LowerVAStart(SDOperand Chain, SelectionDAG &DAG);
70     
71     virtual std::pair<SDOperand,SDOperand>
72     LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
73                    const Type *ArgTy, SelectionDAG &DAG);
74
75     virtual std::pair<SDOperand, SDOperand>
76     LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
77                             SelectionDAG &DAG);
78   };
79 }
80
81
82 std::vector<SDOperand>
83 PPC32TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
84   //
85   // add beautiful description of PPC stack frame format, or at least some docs
86   //
87   MachineFunction &MF = DAG.getMachineFunction();
88   MachineFrameInfo *MFI = MF.getFrameInfo();
89   MachineBasicBlock& BB = MF.front();
90   std::vector<SDOperand> ArgValues;
91   
92   // Due to the rather complicated nature of the PowerPC ABI, rather than a 
93   // fixed size array of physical args, for the sake of simplicity let the STL
94   // handle tracking them for us.
95   std::vector<unsigned> argVR, argPR, argOp;
96   unsigned ArgOffset = 24;
97   unsigned GPR_remaining = 8;
98   unsigned FPR_remaining = 13;
99   unsigned GPR_idx = 0, FPR_idx = 0;
100   static const unsigned GPR[] = { 
101     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
102     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
103   };
104   static const unsigned FPR[] = {
105     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
106     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
107   };
108
109   // Add DAG nodes to load the arguments...  On entry to a function on PPC,
110   // the arguments start at offset 24, although they are likely to be passed
111   // in registers.
112   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
113     SDOperand newroot, argt;
114     unsigned ObjSize;
115     bool needsLoad = false;
116     MVT::ValueType ObjectVT = getValueType(I->getType());
117     
118     switch (ObjectVT) {
119     default: assert(0 && "Unhandled argument type!");
120     case MVT::i1:
121     case MVT::i8:
122     case MVT::i16:
123     case MVT::i32: 
124       ObjSize = 4;
125       if (GPR_remaining > 0) {
126         BuildMI(&BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
127         argt = newroot = DAG.getCopyFromReg(GPR[GPR_idx], MVT::i32,
128                                             DAG.getRoot());
129         if (ObjectVT != MVT::i32)
130           argt = DAG.getNode(ISD::TRUNCATE, ObjectVT, newroot);
131       } else {
132         needsLoad = true;
133       }
134       break;
135       case MVT::i64: ObjSize = 8;
136       // FIXME: can split 64b load between reg/mem if it is last arg in regs
137       if (GPR_remaining > 1) {
138         BuildMI(&BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
139         BuildMI(&BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx+1]);
140         // Copy the extracted halves into the virtual registers
141         SDOperand argHi = DAG.getCopyFromReg(GPR[GPR_idx], MVT::i32, 
142                                              DAG.getRoot());
143         SDOperand argLo = DAG.getCopyFromReg(GPR[GPR_idx+1], MVT::i32, argHi);
144         // Build the outgoing arg thingy
145         argt = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, argLo, argHi);
146         newroot = argLo;
147       } else {
148         needsLoad = true; 
149       }
150       break;
151       case MVT::f32: ObjSize = 4;
152       case MVT::f64: ObjSize = 8;
153       if (FPR_remaining > 0) {
154         BuildMI(&BB, PPC::IMPLICIT_DEF, 0, FPR[FPR_idx]);
155         argt = newroot = DAG.getCopyFromReg(FPR[FPR_idx], ObjectVT, 
156                                             DAG.getRoot());
157         --FPR_remaining;
158         ++FPR_idx;
159       } else {
160         needsLoad = true;
161       }
162       break;
163     }
164     
165     // We need to load the argument to a virtual register if we determined above
166     // that we ran out of physical registers of the appropriate type 
167     if (needsLoad) {
168       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
169       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
170       argt = newroot = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN);
171     }
172     
173     // Every 4 bytes of argument space consumes one of the GPRs available for
174     // argument passing.
175     if (GPR_remaining > 0) {
176       unsigned delta = (GPR_remaining > 1 && ObjSize == 8) ? 2 : 1;
177       GPR_remaining -= delta;
178       GPR_idx += delta;
179     }
180     ArgOffset += ObjSize;
181     
182     DAG.setRoot(newroot.getValue(1));
183     ArgValues.push_back(argt);
184   }
185
186   // If the function takes variable number of arguments, make a frame index for
187   // the start of the first vararg value... for expansion of llvm.va_start.
188   if (F.isVarArg())
189     VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
190
191   return ArgValues;
192 }
193
194 std::pair<SDOperand, SDOperand>
195 PPC32TargetLowering::LowerCallTo(SDOperand Chain,
196                                  const Type *RetTy, bool isVarArg,
197          SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG) {
198   // args_to_use will accumulate outgoing args for the ISD::CALL case in
199   // SelectExpr to use to put the arguments in the appropriate registers.
200   std::vector<SDOperand> args_to_use;
201
202   // Count how many bytes are to be pushed on the stack, including the linkage
203   // area, and parameter passing area.
204   unsigned NumBytes = 24;
205
206   if (Args.empty()) {
207     NumBytes = 0;    // Save zero bytes.
208   } else {
209     for (unsigned i = 0, e = Args.size(); i != e; ++i)
210       switch (getValueType(Args[i].second)) {
211       default: assert(0 && "Unknown value type!");
212       case MVT::i1:
213       case MVT::i8:
214       case MVT::i16:
215       case MVT::i32:
216       case MVT::f32:
217         NumBytes += 4;
218         break;
219       case MVT::i64:
220       case MVT::f64:
221         NumBytes += 8;
222         break;
223       }
224     
225     // Just to be safe, we'll always reserve the full 24 bytes of linkage area 
226     // plus 32 bytes of argument space in case any called code gets funky on us.
227     if (NumBytes < 56) NumBytes = 56;
228
229     // Adjust the stack pointer for the new arguments...
230     // These operations are automatically eliminated by the prolog/epilog pass
231     Chain = DAG.getNode(ISD::ADJCALLSTACKDOWN, MVT::Other, Chain,
232                         DAG.getConstant(NumBytes, getPointerTy()));
233
234     // Set up a copy of the stack pointer for use loading and storing any
235     // arguments that may not fit in the registers available for argument
236     // passing.
237     SDOperand StackPtr = DAG.getCopyFromReg(PPC::R1, MVT::i32,
238                                             DAG.getEntryNode());
239     
240     // Figure out which arguments are going to go in registers, and which in
241     // memory.  Also, if this is a vararg function, floating point operations
242     // must be stored to our stack, and loaded into integer regs as well, if
243     // any integer regs are available for argument passing.
244     unsigned ArgOffset = 24;
245     unsigned GPR_remaining = 8;
246     unsigned FPR_remaining = 13;
247     std::vector<SDOperand> Stores;
248     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
249       // PtrOff will be used to store the current argument to the stack if a
250       // register cannot be found for it.
251       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
252       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
253       MVT::ValueType ArgVT = getValueType(Args[i].second);
254       
255       switch (ArgVT) {
256       default: assert(0 && "Unexpected ValueType for argument!");
257       case MVT::i1:
258       case MVT::i8:
259       case MVT::i16:
260         // Promote the integer to 32 bits.  If the input type is signed use a
261         // sign extend, otherwise use a zero extend.
262         if (Args[i].second->isSigned())
263           Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
264         else
265           Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
266         // FALL THROUGH
267       case MVT::i32:
268         if (GPR_remaining > 0) {
269           args_to_use.push_back(Args[i].first);
270           --GPR_remaining;
271         } else {
272           Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
273                                        Args[i].first, PtrOff));
274         }
275         ArgOffset += 4;
276         break;
277       case MVT::i64:
278         // If we have one free GPR left, we can place the upper half of the i64
279         // in it, and store the other half to the stack.  If we have two or more
280         // free GPRs, then we can pass both halves of the i64 in registers.
281         if (GPR_remaining > 0) {
282           SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, 
283             Args[i].first, DAG.getConstant(1, MVT::i32));
284           SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, 
285             Args[i].first, DAG.getConstant(0, MVT::i32));
286           args_to_use.push_back(Hi);
287           if (GPR_remaining > 1) {
288             args_to_use.push_back(Lo);
289             GPR_remaining -= 2;
290           } else {
291             SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
292             PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
293             Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
294                                          Lo, PtrOff));
295             --GPR_remaining;
296           }
297         } else {
298           Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
299                                        Args[i].first, PtrOff));
300         }
301         ArgOffset += 8;
302         break;
303       case MVT::f32:
304       case MVT::f64:
305         if (FPR_remaining > 0) {
306           if (isVarArg) {
307             // FIXME: Need FunctionType information so we can conditionally
308             // store only the non-fixed arguments in a vararg function.
309             Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
310                                          Args[i].first, PtrOff));
311             // FIXME: Need a way to communicate to the ISD::CALL select code
312             // that a particular argument is non-fixed so that we can load them
313             // into the correct GPR to shadow the FPR
314           }
315           args_to_use.push_back(Args[i].first);
316           --FPR_remaining;
317           // If we have any FPRs remaining, we may also have GPRs remaining.
318           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
319           // GPRs.
320           if (GPR_remaining > 0) --GPR_remaining;
321           if (GPR_remaining > 0 && MVT::f64 == ArgVT) --GPR_remaining;
322         } else {
323           Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
324                                        Args[i].first, PtrOff));
325         }
326         ArgOffset += (ArgVT == MVT::f32) ? 4 : 8;
327         break;
328       }
329     }
330     if (!Stores.empty())
331       Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
332   }
333   
334   std::vector<MVT::ValueType> RetVals;
335   MVT::ValueType RetTyVT = getValueType(RetTy);
336   if (RetTyVT != MVT::isVoid)
337     RetVals.push_back(RetTyVT);
338   RetVals.push_back(MVT::Other);
339
340   SDOperand TheCall = SDOperand(DAG.getCall(RetVals, 
341                                             Chain, Callee, args_to_use), 0);
342   Chain = TheCall.getValue(RetTyVT != MVT::isVoid);
343   Chain = DAG.getNode(ISD::ADJCALLSTACKUP, MVT::Other, Chain,
344                       DAG.getConstant(NumBytes, getPointerTy()));
345   return std::make_pair(TheCall, Chain);
346 }
347
348 std::pair<SDOperand, SDOperand>
349 PPC32TargetLowering::LowerVAStart(SDOperand Chain, SelectionDAG &DAG) {
350   //vastart just returns the address of the VarArgsFrameIndex slot.
351   return std::make_pair(DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32), Chain);
352 }
353
354 std::pair<SDOperand,SDOperand> PPC32TargetLowering::
355 LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
356                const Type *ArgTy, SelectionDAG &DAG) {
357   MVT::ValueType ArgVT = getValueType(ArgTy);
358   SDOperand Result;
359   if (!isVANext) {
360     Result = DAG.getLoad(ArgVT, DAG.getEntryNode(), VAList);
361   } else {
362     unsigned Amt;
363     if (ArgVT == MVT::i32 || ArgVT == MVT::f32)
364       Amt = 4;
365     else {
366       assert((ArgVT == MVT::i64 || ArgVT == MVT::f64) &&
367              "Other types should have been promoted for varargs!");
368       Amt = 8;
369     }
370     Result = DAG.getNode(ISD::ADD, VAList.getValueType(), VAList,
371                          DAG.getConstant(Amt, VAList.getValueType()));
372   }
373   return std::make_pair(Result, Chain);
374 }
375                
376
377 std::pair<SDOperand, SDOperand> PPC32TargetLowering::
378 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
379                         SelectionDAG &DAG) {
380   assert(0 && "LowerFrameReturnAddress unimplemented");
381   abort();
382 }
383
384 namespace {
385
386 //===--------------------------------------------------------------------===//
387 /// ISel - PPC32 specific code to select PPC32 machine instructions for
388 /// SelectionDAG operations.
389 //===--------------------------------------------------------------------===//
390 class ISel : public SelectionDAGISel {
391   
392   /// Comment Here.
393   PPC32TargetLowering PPC32Lowering;
394   
395   /// ExprMap - As shared expressions are codegen'd, we keep track of which
396   /// vreg the value is produced in, so we only emit one copy of each compiled
397   /// tree.
398   std::map<SDOperand, unsigned> ExprMap;
399
400   unsigned GlobalBaseReg;
401   bool GlobalBaseInitialized;
402   
403 public:
404   ISel(TargetMachine &TM) : SelectionDAGISel(PPC32Lowering), PPC32Lowering(TM) 
405   {}
406   
407   /// runOnFunction - Override this function in order to reset our per-function
408   /// variables.
409   virtual bool runOnFunction(Function &Fn) {
410     // Make sure we re-emit a set of the global base reg if necessary
411     GlobalBaseInitialized = false;
412     return SelectionDAGISel::runOnFunction(Fn);
413   } 
414   
415   /// InstructionSelectBasicBlock - This callback is invoked by
416   /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
417   virtual void InstructionSelectBasicBlock(SelectionDAG &DAG) {
418     DEBUG(BB->dump());
419     // Codegen the basic block.
420     Select(DAG.getRoot());
421     
422     // Clear state used for selection.
423     ExprMap.clear();
424   }
425   
426   unsigned ISel::getGlobalBaseReg();
427   unsigned SelectExpr(SDOperand N);
428   unsigned SelectExprFP(SDOperand N, unsigned Result);
429   void Select(SDOperand N);
430   
431   void SelectAddr(SDOperand N, unsigned& Reg, int& offset);
432   void SelectBranchCC(SDOperand N);
433 };
434
435 /// canUseAsImmediateForOpcode - This method returns a value indicating whether
436 /// the ConstantSDNode N can be used as an immediate to Opcode.  The return
437 /// values are either 0, 1 or 2.  0 indicates that either N is not a
438 /// ConstantSDNode, or is not suitable for use by that opcode.  A return value 
439 /// of 1 indicates that the constant may be used in normal immediate form.  A
440 /// return value of 2 indicates that the constant may be used in shifted
441 /// immediate form.  If the return value is nonzero, the constant value is
442 /// placed in Imm.
443 ///
444 static unsigned canUseAsImmediateForOpcode(SDOperand N, unsigned Opcode,
445                                            unsigned& Imm) {
446   if (N.getOpcode() != ISD::Constant) return 0;
447
448   int v = (int)cast<ConstantSDNode>(N)->getSignExtended();
449   
450   switch(Opcode) {
451   default: return 0;
452   case ISD::ADD:
453     if (v <= 32767 && v >= -32768) { Imm = v & 0xFFFF; return 1; }
454     if ((v & 0x0000FFFF) == 0) { Imm = v >> 16; return 2; }
455     break;
456   case ISD::AND:
457   case ISD::XOR:
458   case ISD::OR:
459     if (v >= 0 && v <= 65535) { Imm = v & 0xFFFF; return 1; }
460     if ((v & 0x0000FFFF) == 0) { Imm = v >> 16; return 2; }
461     break;
462   case ISD::MUL:
463     if (v <= 32767 && v >= -32768) { Imm = v & 0xFFFF; return 1; }
464     break;
465   }
466   return 0;
467 }
468 }
469
470 /// getGlobalBaseReg - Output the instructions required to put the
471 /// base address to use for accessing globals into a register.
472 ///
473 unsigned ISel::getGlobalBaseReg() {
474   if (!GlobalBaseInitialized) {
475     // Insert the set of GlobalBaseReg into the first MBB of the function
476     MachineBasicBlock &FirstMBB = BB->getParent()->front();
477     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
478     GlobalBaseReg = MakeReg(MVT::i32);
479     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
480     BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg).addReg(PPC::LR);
481     GlobalBaseInitialized = true;
482   }
483   return GlobalBaseReg;
484 }
485
486 //Check to see if the load is a constant offset from a base register
487 void ISel::SelectAddr(SDOperand N, unsigned& Reg, int& offset)
488 {
489   Reg = SelectExpr(N);
490   offset = 0;
491   return;
492 }
493
494 void ISel::SelectBranchCC(SDOperand N)
495 {
496   assert(N.getOpcode() == ISD::BRCOND && "Not a BranchCC???");
497   MachineBasicBlock *Dest = 
498     cast<BasicBlockSDNode>(N.getOperand(2))->getBasicBlock();
499   unsigned Opc;
500   
501   Select(N.getOperand(0));  //chain
502   SDOperand CC = N.getOperand(1);
503   
504   //Give up and do the stupid thing
505   unsigned Tmp1 = SelectExpr(CC);
506   BuildMI(BB, PPC::CMPLWI, 2, PPC::CR0).addReg(Tmp1).addImm(0);
507   BuildMI(BB, PPC::BNE, 2).addReg(PPC::CR0).addMBB(Dest);
508   return;
509 }
510
511 unsigned ISel::SelectExprFP(SDOperand N, unsigned Result)
512 {
513   unsigned Tmp1, Tmp2, Tmp3;
514   unsigned Opc = 0;
515   SDNode *Node = N.Val;
516   MVT::ValueType DestType = N.getValueType();
517   unsigned opcode = N.getOpcode();
518
519   switch (opcode) {
520   default:
521     Node->dump();
522     assert(0 && "Node not handled!\n");
523
524   case ISD::SELECT: {
525     Tmp1 = SelectExpr(N.getOperand(0)); //Cond
526
527     // FIXME: generate FSEL here
528
529     // Create an iterator with which to insert the MBB for copying the false 
530     // value and the MBB to hold the PHI instruction for this SetCC.
531     MachineBasicBlock *thisMBB = BB;
532     const BasicBlock *LLVM_BB = BB->getBasicBlock();
533     ilist<MachineBasicBlock>::iterator It = BB;
534     ++It;
535
536     //  thisMBB:
537     //  ...
538     //   TrueVal = ...
539     //   cmpTY cr0, r1, r2
540     //   bCC copy1MBB
541     //   fallthrough --> copy0MBB
542     BuildMI(BB, PPC::CMPLWI, 2, PPC::CR0).addReg(Tmp1).addImm(0);
543     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
544     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
545     unsigned TrueValue = SelectExpr(N.getOperand(1)); //Use if TRUE
546     BuildMI(BB, PPC::BNE, 2).addReg(PPC::CR0).addMBB(sinkMBB);
547     MachineFunction *F = BB->getParent();
548     F->getBasicBlockList().insert(It, copy0MBB);
549     F->getBasicBlockList().insert(It, sinkMBB);
550     // Update machine-CFG edges
551     BB->addSuccessor(copy0MBB);
552     BB->addSuccessor(sinkMBB);
553
554     //  copy0MBB:
555     //   %FalseValue = ...
556     //   # fallthrough to sinkMBB
557     BB = copy0MBB;
558     unsigned FalseValue = SelectExpr(N.getOperand(2)); //Use if FALSE
559     // Update machine-CFG edges
560     BB->addSuccessor(sinkMBB);
561
562     //  sinkMBB:
563     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
564     //  ...
565     BB = sinkMBB;
566     BuildMI(BB, PPC::PHI, 4, Result).addReg(FalseValue)
567       .addMBB(copy0MBB).addReg(TrueValue).addMBB(thisMBB);
568     return Result;
569   }
570     
571   case ISD::FP_ROUND:
572     assert (DestType == MVT::f32 && 
573             N.getOperand(0).getValueType() == MVT::f64 && 
574             "only f64 to f32 conversion supported here");
575     Tmp1 = SelectExpr(N.getOperand(0));
576     BuildMI(BB, PPC::FRSP, 1, Result).addReg(Tmp1);
577     return Result;
578
579   case ISD::FP_EXTEND:
580     assert (DestType == MVT::f64 && 
581             N.getOperand(0).getValueType() == MVT::f32 && 
582             "only f32 to f64 conversion supported here");
583     Tmp1 = SelectExpr(N.getOperand(0));
584     BuildMI(BB, PPC::FMR, 1, Result).addReg(Tmp1);
585     return Result;
586
587   case ISD::CopyFromReg:
588     if (Result == 1)
589       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
590     Tmp1 = dyn_cast<RegSDNode>(Node)->getReg();
591     BuildMI(BB, PPC::FMR, 1, Result).addReg(Tmp1);
592     return Result;
593     
594   case ISD::LOAD:
595   case ISD::EXTLOAD: {
596     MVT::ValueType TypeBeingLoaded = (ISD::LOAD == opcode) ?
597       Node->getValueType(0) : cast<MVTSDNode>(Node)->getExtraValueType();
598
599     // Make sure we generate both values.
600     if (Result != 1)
601       ExprMap[N.getValue(1)] = 1;   // Generate the token
602     else
603       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
604
605     SDOperand Chain   = N.getOperand(0);
606     SDOperand Address = N.getOperand(1);
607     Select(Chain);
608
609     switch (TypeBeingLoaded) {
610     default: assert(0 && "Cannot fp load this type!");
611     case MVT::f32:  Opc = PPC::LFS; break;
612     case MVT::f64:  Opc = PPC::LFD; break;
613     }
614     
615     if(Address.getOpcode() == ISD::FrameIndex) {
616       Tmp1 = cast<FrameIndexSDNode>(Address)->getIndex();
617       addFrameReference(BuildMI(BB, Opc, 2, Result), (int)Tmp1);
618     } else {
619       int offset;
620       SelectAddr(Address, Tmp1, offset);
621       BuildMI(BB, Opc, 2, Result).addSImm(offset).addReg(Tmp1);
622     }
623     return Result;
624   }
625     
626   case ISD::ConstantFP:
627     assert(0 && "ISD::ConstantFP Unimplemented");
628     abort();
629     
630   case ISD::MUL:
631   case ISD::ADD:
632   case ISD::SUB:
633   case ISD::SDIV:
634     switch( opcode ) {
635     case ISD::MUL:  Opc = DestType == MVT::f64 ? PPC::FMUL : PPC::FMULS; break;
636     case ISD::ADD:  Opc = DestType == MVT::f64 ? PPC::FADD : PPC::FADDS; break;
637     case ISD::SUB:  Opc = DestType == MVT::f64 ? PPC::FSUB : PPC::FSUBS; break;
638     case ISD::SDIV: Opc = DestType == MVT::f64 ? PPC::FDIV : PPC::FDIVS; break;
639     };
640     Tmp1 = SelectExpr(N.getOperand(0));
641     Tmp2 = SelectExpr(N.getOperand(1));
642     BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
643     return Result;
644
645   case ISD::UINT_TO_FP:
646   case ISD::SINT_TO_FP: {
647     assert (N.getOperand(0).getValueType() == MVT::i32 
648             && "int to float must operate on i32");
649     bool IsUnsigned = (ISD::UINT_TO_FP == opcode);
650     Tmp1 = SelectExpr(N.getOperand(0));  // Get the operand register
651     Tmp2 = MakeReg(MVT::f64); // temp reg to load the integer value into
652     Tmp3 = MakeReg(MVT::i32); // temp reg to hold the conversion constant
653     unsigned ConstF = MakeReg(MVT::f64); // temp reg to hold the fp constant
654     
655     int FrameIdx = BB->getParent()->getFrameInfo()->CreateStackObject(8, 8);
656     MachineConstantPool *CP = BB->getParent()->getConstantPool();
657     
658     // FIXME: pull this FP constant generation stuff out into something like
659     // the simple ISel's getReg.
660     if (IsUnsigned) {
661       ConstantFP *CFP = ConstantFP::get(Type::DoubleTy, 0x1.000000p52);
662       unsigned CPI = CP->getConstantPoolIndex(CFP);
663       // Load constant fp value
664       unsigned Tmp4 = MakeReg(MVT::i32);
665       BuildMI(BB, PPC::LOADHiAddr, 2, Tmp4).addReg(getGlobalBaseReg())
666         .addConstantPoolIndex(CPI);
667       BuildMI(BB, PPC::LFD, 2, ConstF).addConstantPoolIndex(CPI).addReg(Tmp4);
668       // Store the hi & low halves of the fp value, currently in int regs
669       BuildMI(BB, PPC::LIS, 1, Tmp3).addSImm(0x4330);
670       addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(Tmp3), FrameIdx);
671       addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(Tmp1), FrameIdx, 4);
672       addFrameReference(BuildMI(BB, PPC::LFD, 2, Tmp2), FrameIdx);
673       // Generate the return value with a subtract
674       BuildMI(BB, PPC::FSUB, 2, Result).addReg(Tmp2).addReg(ConstF);
675     } else {
676       ConstantFP *CFP = ConstantFP::get(Type::DoubleTy, 0x1.000008p52);
677       unsigned CPI = CP->getConstantPoolIndex(CFP);
678       // Load constant fp value
679       unsigned Tmp4 = MakeReg(MVT::i32);
680       unsigned TmpL = MakeReg(MVT::i32);
681       BuildMI(BB, PPC::LOADHiAddr, 2, Tmp4).addReg(getGlobalBaseReg())
682         .addConstantPoolIndex(CPI);
683       BuildMI(BB, PPC::LFD, 2, ConstF).addConstantPoolIndex(CPI).addReg(Tmp4);
684       // Store the hi & low halves of the fp value, currently in int regs
685       BuildMI(BB, PPC::LIS, 1, Tmp3).addSImm(0x4330);
686       addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(Tmp3), FrameIdx);
687       BuildMI(BB, PPC::XORIS, 2, TmpL).addReg(Tmp1).addImm(0x8000);
688       addFrameReference(BuildMI(BB, PPC::STW, 3).addReg(TmpL), FrameIdx, 4);
689       addFrameReference(BuildMI(BB, PPC::LFD, 2, Tmp2), FrameIdx);
690       // Generate the return value with a subtract
691       BuildMI(BB, PPC::FSUB, 2, Result).addReg(Tmp2).addReg(ConstF);
692     }
693     return Result;
694   }
695   }
696   assert(0 && "should not get here");
697   return 0;
698 }
699
700 unsigned ISel::SelectExpr(SDOperand N) {
701   unsigned Result;
702   unsigned Tmp1, Tmp2, Tmp3;
703   unsigned Opc = 0;
704   unsigned opcode = N.getOpcode();
705
706   SDNode *Node = N.Val;
707   MVT::ValueType DestType = N.getValueType();
708
709   unsigned &Reg = ExprMap[N];
710   if (Reg) return Reg;
711
712   if (N.getOpcode() != ISD::CALL && N.getOpcode() != ISD::ADD_PARTS &&
713       N.getOpcode() != ISD::SUB_PARTS)
714     Reg = Result = (N.getValueType() != MVT::Other) ?
715       MakeReg(N.getValueType()) : 1;
716   else {
717     // If this is a call instruction, make sure to prepare ALL of the result
718     // values as well as the chain.
719     if (N.getOpcode() == ISD::CALL) {
720       if (Node->getNumValues() == 1)
721         Reg = Result = 1;  // Void call, just a chain.
722       else {
723         Result = MakeReg(Node->getValueType(0));
724         ExprMap[N.getValue(0)] = Result;
725         for (unsigned i = 1, e = N.Val->getNumValues()-1; i != e; ++i)
726           ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
727         ExprMap[SDOperand(Node, Node->getNumValues()-1)] = 1;
728       }
729     } else {
730       Result = MakeReg(Node->getValueType(0));
731       ExprMap[N.getValue(0)] = Result;
732       for (unsigned i = 1, e = N.Val->getNumValues(); i != e; ++i)
733         ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
734     }
735   }
736
737   if (DestType == MVT::f64 || DestType == MVT::f32)
738     return SelectExprFP(N, Result);
739
740   switch (opcode) {
741   default:
742     Node->dump();
743     assert(0 && "Node not handled!\n");
744  
745   case ISD::DYNAMIC_STACKALLOC:
746     // Generate both result values.  FIXME: Need a better commment here?
747     if (Result != 1)
748       ExprMap[N.getValue(1)] = 1;
749     else
750       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
751
752     // FIXME: We are currently ignoring the requested alignment for handling
753     // greater than the stack alignment.  This will need to be revisited at some
754     // point.  Align = N.getOperand(2);
755     if (!isa<ConstantSDNode>(N.getOperand(2)) ||
756         cast<ConstantSDNode>(N.getOperand(2))->getValue() != 0) {
757       std::cerr << "Cannot allocate stack object with greater alignment than"
758                 << " the stack alignment yet!";
759       abort();
760     }
761     Select(N.getOperand(0));
762     Tmp1 = SelectExpr(N.getOperand(1));
763     // Subtract size from stack pointer, thereby allocating some space.
764     BuildMI(BB, PPC::SUBF, 2, PPC::R1).addReg(Tmp1).addReg(PPC::R1);
765     // Put a pointer to the space into the result register by copying the SP
766     BuildMI(BB, PPC::OR, 2, Result).addReg(PPC::R1).addReg(PPC::R1);
767     return Result;
768
769   case ISD::ConstantPool:
770     Tmp1 = cast<ConstantPoolSDNode>(N)->getIndex();
771     Tmp2 = MakeReg(MVT::i32);
772     BuildMI(BB, PPC::LOADHiAddr, 2, Tmp2).addReg(getGlobalBaseReg())
773       .addConstantPoolIndex(Tmp1);
774     BuildMI(BB, PPC::LA, 2, Result).addReg(Tmp2).addConstantPoolIndex(Tmp1);
775     return Result;
776
777   case ISD::FrameIndex:
778     Tmp1 = cast<FrameIndexSDNode>(N)->getIndex();
779     addFrameReference(BuildMI(BB, PPC::ADDI, 2, Result), (int)Tmp1, 0, false);
780     return Result;
781   
782   case ISD::GlobalAddress: {
783     GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
784     Tmp1 = MakeReg(MVT::i32);
785     BuildMI(BB, PPC::LOADHiAddr, 2, Tmp1).addReg(getGlobalBaseReg())
786       .addGlobalAddress(GV);
787     if (GV->hasWeakLinkage() || GV->isExternal()) {
788       BuildMI(BB, PPC::LWZ, 2, Result).addGlobalAddress(GV).addReg(Tmp1);
789     } else {
790       BuildMI(BB, PPC::LA, 2, Result).addReg(Tmp1).addGlobalAddress(GV);
791     }
792     return Result;
793   }
794
795   case ISD::LOAD:
796   case ISD::EXTLOAD:
797   case ISD::ZEXTLOAD:
798   case ISD::SEXTLOAD: {
799     bool sext = (ISD::SEXTLOAD == opcode);
800     bool byte = (MVT::i8 == Node->getValueType(0));
801     MVT::ValueType TypeBeingLoaded = (ISD::LOAD == opcode) ?
802       Node->getValueType(0) : cast<MVTSDNode>(Node)->getExtraValueType();
803       
804     // Make sure we generate both values.
805     if (Result != 1)
806       ExprMap[N.getValue(1)] = 1;   // Generate the token
807     else
808       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
809
810     SDOperand Chain   = N.getOperand(0);
811     SDOperand Address = N.getOperand(1);
812     Select(Chain);
813
814     switch (TypeBeingLoaded) {
815     default: assert(0 && "Cannot load this type!");
816     case MVT::i1:  Opc = PPC::LBZ; break;
817     case MVT::i8:  Opc = PPC::LBZ; break;
818     case MVT::i16: Opc = sext ? PPC::LHA : PPC::LHZ; break;
819     case MVT::i32: Opc = PPC::LWZ; break;
820     }
821     
822     // Since there's no load byte & sign extend instruction we have to split
823     // byte SEXTLOADs into lbz + extsb.  This requires we make a temp register.
824     if (sext && byte) {
825       Tmp3 = Result;
826       Result = MakeReg(MVT::i32);
827     } else {
828       Tmp3 = 0;  // Silence GCC warning.
829     }
830     if(Address.getOpcode() == ISD::FrameIndex) {
831       Tmp1 = cast<FrameIndexSDNode>(Address)->getIndex();
832       addFrameReference(BuildMI(BB, Opc, 2, Result), (int)Tmp1);
833     } else {
834       int offset;
835       SelectAddr(Address, Tmp1, offset);
836       BuildMI(BB, Opc, 2, Result).addSImm(offset).addReg(Tmp1);
837     }
838     if (sext && byte) {
839       BuildMI(BB, PPC::EXTSB, 1, Tmp3).addReg(Result);
840       Result = Tmp3;
841     }
842     return Result;
843   }
844     
845   case ISD::CALL: {
846     // Lower the chain for this call.
847     Select(N.getOperand(0));
848     ExprMap[N.getValue(Node->getNumValues()-1)] = 1;
849       
850     // get the virtual reg for each argument
851     std::vector<unsigned> VRegs;
852     for(int i = 2, e = Node->getNumOperands(); i < e; ++i)
853       VRegs.push_back(SelectExpr(N.getOperand(i)));
854     
855     // The ABI specifies that the first 32 bytes of args may be passed in GPRs,
856     // and that 13 FPRs may also be used for passing any floating point args.
857     int GPR_remaining = 8, FPR_remaining = 13;
858     unsigned GPR_idx = 0, FPR_idx = 0;
859     static const unsigned GPR[] = { 
860       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
861       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
862     };
863     static const unsigned FPR[] = {
864       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, 
865       PPC::F7, PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, 
866       PPC::F13
867     };
868
869     // move the vregs into the appropriate architected register or stack slot
870     for(int i = 0, e = VRegs.size(); i < e; ++i) {
871         unsigned OperandType = N.getOperand(i+2).getValueType();
872         switch(OperandType) {
873         default: 
874           Node->dump(); 
875           N.getOperand(i).Val->dump();
876           std::cerr << "Type for " << i << " is: " << 
877             N.getOperand(i+2).getValueType() << "\n";
878           assert(0 && "Unknown value type for call");
879         case MVT::i1:
880         case MVT::i8:
881         case MVT::i16:
882         case MVT::i32:
883           if (GPR_remaining > 0)
884             BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(VRegs[i])
885               .addReg(VRegs[i]);
886           break;
887         case MVT::f32:
888         case MVT::f64:
889           if (FPR_remaining > 0) {
890             BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(VRegs[i]);
891             ++FPR_idx;
892             --FPR_remaining;
893           }
894           break;
895         }
896         // All arguments consume GPRs available for argument passing
897         if (GPR_remaining > 0) { 
898           ++GPR_idx; 
899           --GPR_remaining;
900         }
901         if (MVT::f64 == OperandType && GPR_remaining > 0) {
902           ++GPR_idx;
903           --GPR_remaining;
904         }
905     }
906
907     // Emit the correct call instruction based on the type of symbol called.
908     if (GlobalAddressSDNode *GASD = 
909         dyn_cast<GlobalAddressSDNode>(N.getOperand(1))) {
910       BuildMI(BB, PPC::CALLpcrel, 1).addGlobalAddress(GASD->getGlobal(), true);
911     } else if (ExternalSymbolSDNode *ESSDN = 
912                dyn_cast<ExternalSymbolSDNode>(N.getOperand(1))) {
913       BuildMI(BB, PPC::CALLpcrel, 1).addExternalSymbol(ESSDN->getSymbol(), true);
914     } else {
915       Tmp1 = SelectExpr(N.getOperand(1));
916       BuildMI(BB, PPC::OR, 2, PPC::R12).addReg(Tmp1).addReg(Tmp1);
917       BuildMI(BB, PPC::MTCTR, 1).addReg(PPC::R12);
918       BuildMI(BB, PPC::CALLindirect, 3).addImm(20).addImm(0).addReg(PPC::R12);
919     }
920
921     switch (Node->getValueType(0)) {
922     default: assert(0 && "Unknown value type for call result!");
923     case MVT::Other: return 1;
924     case MVT::i1:
925     case MVT::i8:
926     case MVT::i16:
927     case MVT::i32:
928       BuildMI(BB, PPC::OR, 2, Result).addReg(PPC::R3).addReg(PPC::R3);
929       if (Node->getValueType(1) == MVT::i32)
930         BuildMI(BB, PPC::OR, 2, Result+1).addReg(PPC::R4).addReg(PPC::R4);
931       break;
932     case MVT::f32:
933     case MVT::f64:
934       BuildMI(BB, PPC::FMR, 1, Result).addReg(PPC::F1);
935       break;
936     }
937     return Result+N.ResNo;
938   }
939
940   case ISD::SIGN_EXTEND:
941   case ISD::SIGN_EXTEND_INREG:
942     Tmp1 = SelectExpr(N.getOperand(0));
943     switch(cast<MVTSDNode>(Node)->getExtraValueType()) {
944     default: Node->dump(); assert(0 && "Unhandled SIGN_EXTEND type"); break;
945     case MVT::i16:  
946       BuildMI(BB, PPC::EXTSH, 1, Result).addReg(Tmp1); 
947       break;
948     case MVT::i8:   
949       BuildMI(BB, PPC::EXTSB, 1, Result).addReg(Tmp1); 
950       break;
951     case MVT::i1:
952       BuildMI(BB, PPC::SUBFIC, 2, Result).addReg(Tmp1).addSImm(0);
953       break;
954     }
955     return Result;
956     
957   case ISD::ZERO_EXTEND_INREG:
958     Tmp1 = SelectExpr(N.getOperand(0));
959     switch(cast<MVTSDNode>(Node)->getExtraValueType()) {
960     default: Node->dump(); assert(0 && "Unhandled ZERO_EXTEND type"); break;
961     case MVT::i16:  Tmp2 = 16; break;
962     case MVT::i8:   Tmp2 = 24; break;
963     case MVT::i1:   Tmp2 = 31; break;
964     }
965     BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(0).addImm(Tmp2)
966       .addImm(31);
967     return Result;
968     
969   case ISD::CopyFromReg:
970     if (Result == 1)
971       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
972     Tmp1 = dyn_cast<RegSDNode>(Node)->getReg();
973     BuildMI(BB, PPC::OR, 2, Result).addReg(Tmp1).addReg(Tmp1);
974     return Result;
975
976   case ISD::SHL:
977     Tmp1 = SelectExpr(N.getOperand(0));
978     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
979       Tmp2 = CN->getValue() & 0x1F;
980       BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(Tmp2).addImm(0)
981         .addImm(31-Tmp2);
982     } else {
983       Tmp2 = SelectExpr(N.getOperand(1));
984       BuildMI(BB, PPC::SLW, 2, Result).addReg(Tmp1).addReg(Tmp2);
985     }
986     return Result;
987     
988   case ISD::SRL:
989     Tmp1 = SelectExpr(N.getOperand(0));
990     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
991       Tmp2 = CN->getValue() & 0x1F;
992       BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(32-Tmp2)
993         .addImm(Tmp2).addImm(31);
994     } else {
995       Tmp2 = SelectExpr(N.getOperand(1));
996       BuildMI(BB, PPC::SRW, 2, Result).addReg(Tmp1).addReg(Tmp2);
997     }
998     return Result;
999     
1000   case ISD::SRA:
1001     Tmp1 = SelectExpr(N.getOperand(0));
1002     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1003       Tmp2 = CN->getValue() & 0x1F;
1004       BuildMI(BB, PPC::SRAWI, 2, Result).addReg(Tmp1).addImm(Tmp2);
1005     } else {
1006       Tmp2 = SelectExpr(N.getOperand(1));
1007       BuildMI(BB, PPC::SRAW, 2, Result).addReg(Tmp1).addReg(Tmp2);
1008     }
1009     return Result;
1010   
1011   case ISD::ADD:
1012     assert (DestType == MVT::i32 && "Only do arithmetic on i32s!");
1013     Tmp1 = SelectExpr(N.getOperand(0));
1014     switch(canUseAsImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
1015       default: assert(0 && "unhandled result code");
1016       case 0: // No immediate
1017         Tmp2 = SelectExpr(N.getOperand(1));
1018         BuildMI(BB, PPC::ADD, 2, Result).addReg(Tmp1).addReg(Tmp2);
1019         break;
1020       case 1: // Low immediate
1021         BuildMI(BB, PPC::ADDI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
1022         break;
1023       case 2: // Shifted immediate
1024         BuildMI(BB, PPC::ADDIS, 2, Result).addReg(Tmp1).addSImm(Tmp2);
1025         break;
1026     }
1027     return Result;
1028
1029   case ISD::AND:
1030   case ISD::OR:
1031   case ISD::XOR:
1032     assert (DestType == MVT::i32 && "Only do arithmetic on i32s!");
1033     Tmp1 = SelectExpr(N.getOperand(0));
1034     switch(canUseAsImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
1035       default: assert(0 && "unhandled result code");
1036       case 0: // No immediate
1037         Tmp2 = SelectExpr(N.getOperand(1));
1038         switch (opcode) {
1039         case ISD::AND: Opc = PPC::AND; break;
1040         case ISD::OR:  Opc = PPC::OR;  break;
1041         case ISD::XOR: Opc = PPC::XOR; break;
1042         }
1043         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1044         break;
1045       case 1: // Low immediate
1046         switch (opcode) {
1047         case ISD::AND: Opc = PPC::ANDIo; break;
1048         case ISD::OR:  Opc = PPC::ORI;   break;
1049         case ISD::XOR: Opc = PPC::XORI;  break;
1050         }
1051         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(Tmp2);
1052         break;
1053       case 2: // Shifted immediate
1054         switch (opcode) {
1055         case ISD::AND: Opc = PPC::ANDISo;  break;
1056         case ISD::OR:  Opc = PPC::ORIS;    break;
1057         case ISD::XOR: Opc = PPC::XORIS;   break;
1058         }
1059         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(Tmp2);
1060         break;
1061     }
1062     return Result;
1063
1064   case ISD::SUB:
1065     assert (DestType == MVT::i32 && "Only do arithmetic on i32s!");
1066     Tmp1 = SelectExpr(N.getOperand(0));
1067     Tmp2 = SelectExpr(N.getOperand(1));
1068     BuildMI(BB, PPC::SUBF, 2, Result).addReg(Tmp2).addReg(Tmp1);
1069     return Result;
1070     
1071   case ISD::MUL:
1072     assert (DestType == MVT::i32 && "Only do arithmetic on i32s!");
1073     Tmp1 = SelectExpr(N.getOperand(0));
1074     if (1 == canUseAsImmediateForOpcode(N.getOperand(1), opcode, Tmp2))
1075       BuildMI(BB, PPC::MULLI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
1076     else {
1077       Tmp2 = SelectExpr(N.getOperand(1));
1078       BuildMI(BB, PPC::MULLW, 2, Result).addReg(Tmp1).addReg(Tmp2);
1079     }
1080     return Result;
1081
1082   case ISD::SDIV:
1083   case ISD::UDIV:
1084     assert (DestType == MVT::i32 && "Only do arithmetic on i32s!");
1085     Tmp1 = SelectExpr(N.getOperand(0));
1086     Tmp2 = SelectExpr(N.getOperand(1));
1087     Opc = (ISD::UDIV == opcode) ? PPC::DIVWU : PPC::DIVW;
1088     BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1089     return Result;
1090
1091   case ISD::UREM:
1092   case ISD::SREM: {
1093     assert (DestType == MVT::i32 && "Only do arithmetic on i32s!");
1094     Tmp1 = SelectExpr(N.getOperand(0));
1095     Tmp2 = SelectExpr(N.getOperand(1));
1096     Tmp3 = MakeReg(MVT::i32);
1097     unsigned Tmp4 = MakeReg(MVT::i32);
1098     Opc = (ISD::UREM == opcode) ? PPC::DIVWU : PPC::DIVW;
1099     BuildMI(BB, Opc, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
1100     BuildMI(BB, PPC::MULLW, 2, Tmp4).addReg(Tmp3).addReg(Tmp2);
1101     BuildMI(BB, PPC::SUBF, 2, Result).addReg(Tmp4).addReg(Tmp1);
1102     return Result;
1103   }
1104
1105   case ISD::ADD_PARTS:
1106   case ISD::SUB_PARTS: {
1107     assert(N.getNumOperands() == 4 && N.getValueType() == MVT::i32 &&
1108            "Not an i64 add/sub!");
1109     // Emit all of the operands.
1110     std::vector<unsigned> InVals;
1111     for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)
1112       InVals.push_back(SelectExpr(N.getOperand(i)));
1113     if (N.getOpcode() == ISD::ADD_PARTS) {
1114       BuildMI(BB, PPC::ADDC, 2, Result+1).addReg(InVals[0]).addReg(InVals[2]);
1115       BuildMI(BB, PPC::ADDE, 2, Result).addReg(InVals[1]).addReg(InVals[3]);
1116     } else {
1117       BuildMI(BB, PPC::SUBFC, 2, Result+1).addReg(InVals[2]).addReg(InVals[0]);
1118       BuildMI(BB, PPC::SUBFE, 2, Result).addReg(InVals[3]).addReg(InVals[1]);
1119     }
1120     return Result+N.ResNo;
1121   }
1122     
1123   case ISD::FP_TO_UINT:
1124   case ISD::FP_TO_SINT:
1125     assert(0 && "FP_TO_S/UINT unimplemented");
1126     abort();
1127  
1128   case ISD::SETCC:
1129     if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(Node)) {
1130       bool U = false;
1131       bool IsInteger = MVT::isInteger(SetCC->getOperand(0).getValueType());
1132       
1133       switch (SetCC->getCondition()) {
1134       default: Node->dump(); assert(0 && "Unknown comparison!");
1135       case ISD::SETEQ:  Opc = PPC::BEQ; break;
1136       case ISD::SETNE:  Opc = PPC::BNE; break;
1137       case ISD::SETULT: U = true;
1138       case ISD::SETLT:  Opc = PPC::BLT; break;
1139       case ISD::SETULE: U = true;
1140       case ISD::SETLE:  Opc = PPC::BLE; break;
1141       case ISD::SETUGT: U = true;
1142       case ISD::SETGT:  Opc = PPC::BGT; break;
1143       case ISD::SETUGE: U = true;
1144       case ISD::SETGE:  Opc = PPC::BGE; break;
1145       }
1146       
1147       // FIXME: Is there a situation in which we would ever need to emit fcmpo?
1148       static const unsigned CompareOpcodes[] = 
1149         { PPC::FCMPU, PPC::FCMPU, PPC::CMPW, PPC::CMPLW };
1150       unsigned CompareOpc = CompareOpcodes[2 * IsInteger + U];
1151       
1152       // Create an iterator with which to insert the MBB for copying the false 
1153       // value and the MBB to hold the PHI instruction for this SetCC.
1154       MachineBasicBlock *thisMBB = BB;
1155       const BasicBlock *LLVM_BB = BB->getBasicBlock();
1156       ilist<MachineBasicBlock>::iterator It = BB;
1157       ++It;
1158   
1159       //  thisMBB:
1160       //  ...
1161       //   cmpTY cr0, r1, r2
1162       //   %TrueValue = li 1
1163       //   bCC sinkMBB
1164       Tmp1 = SelectExpr(N.getOperand(0));
1165       Tmp2 = SelectExpr(N.getOperand(1));
1166       BuildMI(BB, CompareOpc, 2, PPC::CR0).addReg(Tmp1).addReg(Tmp2);
1167       unsigned TrueValue = MakeReg(MVT::i32);
1168       BuildMI(BB, PPC::LI, 1, TrueValue).addSImm(1);
1169       MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1170       MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1171       BuildMI(BB, Opc, 2).addReg(PPC::CR0).addMBB(sinkMBB);
1172       MachineFunction *F = BB->getParent();
1173       F->getBasicBlockList().insert(It, copy0MBB);
1174       F->getBasicBlockList().insert(It, sinkMBB);
1175       // Update machine-CFG edges
1176       BB->addSuccessor(copy0MBB);
1177       BB->addSuccessor(sinkMBB);
1178
1179       //  copy0MBB:
1180       //   %FalseValue = li 0
1181       //   fallthrough
1182       BB = copy0MBB;
1183       unsigned FalseValue = MakeReg(MVT::i32);
1184       BuildMI(BB, PPC::LI, 1, FalseValue).addSImm(0);
1185       // Update machine-CFG edges
1186       BB->addSuccessor(sinkMBB);
1187
1188       //  sinkMBB:
1189       //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1190       //  ...
1191       BB = sinkMBB;
1192       BuildMI(BB, PPC::PHI, 4, Result).addReg(FalseValue)
1193         .addMBB(copy0MBB).addReg(TrueValue).addMBB(thisMBB);
1194       return Result;
1195     }
1196     assert(0 && "Is this legal?");
1197     return 0;
1198     
1199   case ISD::SELECT: {
1200     Tmp1 = SelectExpr(N.getOperand(0)); //Cond
1201
1202     // Create an iterator with which to insert the MBB for copying the false 
1203     // value and the MBB to hold the PHI instruction for this SetCC.
1204     MachineBasicBlock *thisMBB = BB;
1205     const BasicBlock *LLVM_BB = BB->getBasicBlock();
1206     ilist<MachineBasicBlock>::iterator It = BB;
1207     ++It;
1208
1209     //  thisMBB:
1210     //  ...
1211     //   TrueVal = ...
1212     //   cmpTY cr0, r1, r2
1213     //   bCC copy1MBB
1214     //   fallthrough --> copy0MBB
1215     BuildMI(BB, PPC::CMPLWI, 2, PPC::CR0).addReg(Tmp1).addImm(0);
1216     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1217     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1218     unsigned TrueValue = SelectExpr(N.getOperand(1)); //Use if TRUE
1219     BuildMI(BB, PPC::BNE, 2).addReg(PPC::CR0).addMBB(sinkMBB);
1220     MachineFunction *F = BB->getParent();
1221     F->getBasicBlockList().insert(It, copy0MBB);
1222     F->getBasicBlockList().insert(It, sinkMBB);
1223     // Update machine-CFG edges
1224     BB->addSuccessor(copy0MBB);
1225     BB->addSuccessor(sinkMBB);
1226
1227     //  copy0MBB:
1228     //   %FalseValue = ...
1229     //   # fallthrough to sinkMBB
1230     BB = copy0MBB;
1231     unsigned FalseValue = SelectExpr(N.getOperand(2)); //Use if FALSE
1232     // Update machine-CFG edges
1233     BB->addSuccessor(sinkMBB);
1234
1235     //  sinkMBB:
1236     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1237     //  ...
1238     BB = sinkMBB;
1239     BuildMI(BB, PPC::PHI, 4, Result).addReg(FalseValue)
1240       .addMBB(copy0MBB).addReg(TrueValue).addMBB(thisMBB);
1241
1242     // FIXME: Select i64?
1243     return Result;
1244   }
1245
1246   case ISD::Constant:
1247     switch (N.getValueType()) {
1248     default: assert(0 && "Cannot use constants of this type!");
1249     case MVT::i1:
1250       BuildMI(BB, PPC::LI, 1, Result)
1251         .addSImm(!cast<ConstantSDNode>(N)->isNullValue());
1252       break;
1253     case MVT::i32:
1254       {
1255         int v = (int)cast<ConstantSDNode>(N)->getSignExtended();
1256         if (v < 32768 && v >= -32768) {
1257           BuildMI(BB, PPC::LI, 1, Result).addSImm(v);
1258         } else {
1259           Tmp1 = MakeReg(MVT::i32);
1260           BuildMI(BB, PPC::LIS, 1, Tmp1).addSImm(v >> 16);
1261           BuildMI(BB, PPC::ORI, 2, Result).addReg(Tmp1).addImm(v & 0xFFFF);
1262         }
1263       }
1264     }
1265     return Result;
1266   }
1267
1268   return 0;
1269 }
1270
1271 void ISel::Select(SDOperand N) {
1272   unsigned Tmp1, Tmp2, Opc;
1273   unsigned opcode = N.getOpcode();
1274
1275   if (!ExprMap.insert(std::make_pair(N, 1)).second)
1276     return;  // Already selected.
1277
1278   SDNode *Node = N.Val;
1279   
1280   switch (Node->getOpcode()) {
1281   default:
1282     Node->dump(); std::cerr << "\n";
1283     assert(0 && "Node not handled yet!");
1284   case ISD::EntryToken: return;  // Noop
1285   case ISD::TokenFactor:
1286     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1287       Select(Node->getOperand(i));
1288     return;
1289   case ISD::ADJCALLSTACKDOWN:
1290   case ISD::ADJCALLSTACKUP:
1291     Select(N.getOperand(0));
1292     Tmp1 = cast<ConstantSDNode>(N.getOperand(1))->getValue();
1293     Opc = N.getOpcode() == ISD::ADJCALLSTACKDOWN ? PPC::ADJCALLSTACKDOWN :
1294       PPC::ADJCALLSTACKUP;
1295     BuildMI(BB, Opc, 1).addImm(Tmp1);
1296     return;
1297   case ISD::BR: {
1298     MachineBasicBlock *Dest =
1299       cast<BasicBlockSDNode>(N.getOperand(1))->getBasicBlock();
1300     Select(N.getOperand(0));
1301     BuildMI(BB, PPC::B, 1).addMBB(Dest);
1302     return;
1303   }
1304   case ISD::BRCOND: 
1305     SelectBranchCC(N);
1306     return;
1307   case ISD::CopyToReg:
1308     Select(N.getOperand(0));
1309     Tmp1 = SelectExpr(N.getOperand(1));
1310     Tmp2 = cast<RegSDNode>(N)->getReg();
1311     
1312     if (Tmp1 != Tmp2) {
1313       if (N.getOperand(1).getValueType() == MVT::f64 || 
1314           N.getOperand(1).getValueType() == MVT::f32)
1315         BuildMI(BB, PPC::FMR, 1, Tmp2).addReg(Tmp1);
1316       else
1317         BuildMI(BB, PPC::OR, 2, Tmp2).addReg(Tmp1).addReg(Tmp1);
1318     }
1319     return;
1320   case ISD::ImplicitDef:
1321     Select(N.getOperand(0));
1322     BuildMI(BB, PPC::IMPLICIT_DEF, 0, cast<RegSDNode>(N)->getReg());
1323     return;
1324   case ISD::RET:
1325     switch (N.getNumOperands()) {
1326     default:
1327       assert(0 && "Unknown return instruction!");
1328     case 3:
1329       assert(N.getOperand(1).getValueType() == MVT::i32 &&
1330              N.getOperand(2).getValueType() == MVT::i32 &&
1331                    "Unknown two-register value!");
1332       Select(N.getOperand(0));
1333       Tmp1 = SelectExpr(N.getOperand(1));
1334       Tmp2 = SelectExpr(N.getOperand(2));
1335       BuildMI(BB, PPC::OR, 2, PPC::R3).addReg(Tmp1).addReg(Tmp1);
1336       BuildMI(BB, PPC::OR, 2, PPC::R4).addReg(Tmp2).addReg(Tmp2);
1337       break;
1338     case 2:
1339       Select(N.getOperand(0));
1340       Tmp1 = SelectExpr(N.getOperand(1));
1341       switch (N.getOperand(1).getValueType()) {
1342         default:
1343           assert(0 && "Unknown return type!");
1344         case MVT::f64:
1345         case MVT::f32:
1346           BuildMI(BB, PPC::FMR, 1, PPC::F1).addReg(Tmp1);
1347           break;
1348         case MVT::i32:
1349           BuildMI(BB, PPC::OR, 2, PPC::R3).addReg(Tmp1).addReg(Tmp1);
1350           break;
1351       }
1352     case 1:
1353       Select(N.getOperand(0));
1354       break;
1355     }
1356     BuildMI(BB, PPC::BLR, 0); // Just emit a 'ret' instruction
1357     return;
1358   case ISD::TRUNCSTORE: 
1359   case ISD::STORE: 
1360     {
1361       SDOperand Chain   = N.getOperand(0);
1362       SDOperand Value   = N.getOperand(1);
1363       SDOperand Address = N.getOperand(2);
1364       Select(Chain);
1365
1366       Tmp1 = SelectExpr(Value); //value
1367
1368       if (opcode == ISD::STORE) {
1369         switch(Value.getValueType()) {
1370         default: assert(0 && "unknown Type in store");
1371         case MVT::i32: Opc = PPC::STW; break;
1372         case MVT::f64: Opc = PPC::STFD; break;
1373         case MVT::f32: Opc = PPC::STFS; break;
1374         }
1375       } else { //ISD::TRUNCSTORE
1376         switch(cast<MVTSDNode>(Node)->getExtraValueType()) {
1377         default: assert(0 && "unknown Type in store");
1378         case MVT::i1: //FIXME: DAG does not promote this load
1379         case MVT::i8: Opc  = PPC::STB; break;
1380         case MVT::i16: Opc = PPC::STH; break;
1381         }
1382       }
1383
1384       if (Address.getOpcode() == ISD::GlobalAddress)
1385       {
1386         BuildMI(BB, Opc, 2).addReg(Tmp1)
1387           .addGlobalAddress(cast<GlobalAddressSDNode>(Address)->getGlobal());
1388       }
1389       else if(Address.getOpcode() == ISD::FrameIndex)
1390       {
1391         Tmp2 = cast<FrameIndexSDNode>(Address)->getIndex();
1392         addFrameReference(BuildMI(BB, Opc, 3).addReg(Tmp1), (int)Tmp2);
1393       }
1394       else
1395       {
1396         int offset;
1397         SelectAddr(Address, Tmp2, offset);
1398         BuildMI(BB, Opc, 3).addReg(Tmp1).addImm(offset).addReg(Tmp2);
1399       }
1400       return;
1401     }
1402   case ISD::EXTLOAD:
1403   case ISD::SEXTLOAD:
1404   case ISD::ZEXTLOAD:
1405   case ISD::LOAD:
1406   case ISD::CopyFromReg:
1407   case ISD::CALL:
1408   case ISD::DYNAMIC_STACKALLOC:
1409     ExprMap.erase(N);
1410     SelectExpr(N);
1411     return;
1412   }
1413   assert(0 && "Should not be reached!");
1414 }
1415
1416
1417 /// createPPC32PatternInstructionSelector - This pass converts an LLVM function
1418 /// into a machine code representation using pattern matching and a machine
1419 /// description file.
1420 ///
1421 FunctionPass *llvm::createPPC32ISelPattern(TargetMachine &TM) {
1422   return new ISel(TM);  
1423 }
1424