Fix handling of FP constants with single precision, and loading of internal linkage...
[oota-llvm.git] / lib / Target / PowerPC / PPC32ISelSimple.cpp
1 //===-- InstSelectSimple.cpp - A simple instruction selector for PowerPC --===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9
10 #define DEBUG_TYPE "isel"
11 #include "PowerPC.h"
12 #include "PowerPCInstrBuilder.h"
13 #include "PowerPCInstrInfo.h"
14 #include "PPC32TargetMachine.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Pass.h"
20 #include "llvm/CodeGen/IntrinsicLowering.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/SSARegMap.h"
25 #include "llvm/Target/MRegisterInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/GetElementPtrTypeIterator.h"
28 #include "llvm/Support/InstVisitor.h"
29 #include "Support/Debug.h"
30 #include "Support/Statistic.h"
31 #include <vector>
32 using namespace llvm;
33
34 namespace {
35   Statistic<> GEPFolds("ppc-codegen", "Number of GEPs folded");
36
37   /// TypeClass - Used by the PowerPC backend to group LLVM types by their basic
38   /// PPC Representation.
39   ///
40   enum TypeClass {
41     cByte, cShort, cInt, cFP32, cFP64, cLong
42   };
43 }
44
45 /// getClass - Turn a primitive type into a "class" number which is based on the
46 /// size of the type, and whether or not it is floating point.
47 ///
48 static inline TypeClass getClass(const Type *Ty) {
49   switch (Ty->getTypeID()) {
50   case Type::SByteTyID:
51   case Type::UByteTyID:   return cByte;      // Byte operands are class #0
52   case Type::ShortTyID:
53   case Type::UShortTyID:  return cShort;     // Short operands are class #1
54   case Type::IntTyID:
55   case Type::UIntTyID:
56   case Type::PointerTyID: return cInt;       // Ints and pointers are class #2
57
58   case Type::FloatTyID:   return cFP32;      // Single float is #3
59   case Type::DoubleTyID:  return cFP64;      // Double Point is #4
60
61   case Type::LongTyID:
62   case Type::ULongTyID:   return cLong;      // Longs are class #5
63   default:
64     assert(0 && "Invalid type to getClass!");
65     return cByte;  // not reached
66   }
67 }
68
69 // getClassB - Just like getClass, but treat boolean values as ints.
70 static inline TypeClass getClassB(const Type *Ty) {
71   if (Ty == Type::BoolTy) return cByte;
72   return getClass(Ty);
73 }
74
75 namespace {
76   struct ISel : public FunctionPass, InstVisitor<ISel> {
77     PPC32TargetMachine &TM;
78     MachineFunction *F;                 // The function we are compiling into
79     MachineBasicBlock *BB;              // The current MBB we are compiling
80     int VarArgsFrameIndex;              // FrameIndex for start of varargs area
81     
82     std::map<Value*, unsigned> RegMap;  // Mapping between Values and SSA Regs
83
84     // External functions used in the Module
85     Function *fmodfFn, *fmodFn, *__cmpdi2Fn, *__moddi3Fn, *__divdi3Fn, 
86       *__umoddi3Fn,  *__udivdi3Fn, *__fixsfdiFn, *__fixdfdiFn, *__fixunssfdiFn,
87       *__fixunsdfdiFn, *__floatdisfFn, *__floatdidfFn, *mallocFn, *freeFn;
88
89     // MBBMap - Mapping between LLVM BB -> Machine BB
90     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
91
92     // AllocaMap - Mapping from fixed sized alloca instructions to the
93     // FrameIndex for the alloca.
94     std::map<AllocaInst*, unsigned> AllocaMap;
95
96     // A Reg to hold the base address used for global loads and stores, and a
97     // flag to set whether or not we need to emit it for this function.
98     unsigned GlobalBaseReg;
99     bool GlobalBaseInitialized;
100     
101     ISel(TargetMachine &tm) : TM(reinterpret_cast<PPC32TargetMachine&>(tm)), 
102       F(0), BB(0) {}
103
104     bool doInitialization(Module &M) {
105       // Add external functions that we may call
106       Type *i = Type::IntTy;
107       Type *d = Type::DoubleTy;
108       Type *f = Type::FloatTy;
109       Type *l = Type::LongTy;
110       Type *ul = Type::ULongTy;
111       Type *voidPtr = PointerType::get(Type::SByteTy);
112       // float fmodf(float, float);
113       fmodfFn = M.getOrInsertFunction("fmodf", f, f, f, 0);
114       // double fmod(double, double);
115       fmodFn = M.getOrInsertFunction("fmod", d, d, d, 0);
116       // int __cmpdi2(long, long);
117       __cmpdi2Fn = M.getOrInsertFunction("__cmpdi2", i, l, l, 0);
118       // long __moddi3(long, long);
119       __moddi3Fn = M.getOrInsertFunction("__moddi3", l, l, l, 0);
120       // long __divdi3(long, long);
121       __divdi3Fn = M.getOrInsertFunction("__divdi3", l, l, l, 0);
122       // unsigned long __umoddi3(unsigned long, unsigned long);
123       __umoddi3Fn = M.getOrInsertFunction("__umoddi3", ul, ul, ul, 0);
124       // unsigned long __udivdi3(unsigned long, unsigned long);
125       __udivdi3Fn = M.getOrInsertFunction("__udivdi3", ul, ul, ul, 0);
126       // long __fixsfdi(float)
127       __fixsfdiFn = M.getOrInsertFunction("__fixsfdi", l, f, 0);
128       // long __fixdfdi(double)
129       __fixdfdiFn = M.getOrInsertFunction("__fixdfdi", l, d, 0);
130       // unsigned long __fixunssfdi(float)
131       __fixunssfdiFn = M.getOrInsertFunction("__fixunssfdi", ul, f, 0);
132       // unsigned long __fixunsdfdi(double)
133       __fixunsdfdiFn = M.getOrInsertFunction("__fixunsdfdi", ul, d, 0);
134       // float __floatdisf(long)
135       __floatdisfFn = M.getOrInsertFunction("__floatdisf", f, l, 0);
136       // double __floatdidf(long)
137       __floatdidfFn = M.getOrInsertFunction("__floatdidf", d, l, 0);
138       // void* malloc(size_t)
139       mallocFn = M.getOrInsertFunction("malloc", voidPtr, Type::UIntTy, 0);
140       // void free(void*)
141       freeFn = M.getOrInsertFunction("free", Type::VoidTy, voidPtr, 0);
142       return false;
143     }
144
145     /// runOnFunction - Top level implementation of instruction selection for
146     /// the entire function.
147     ///
148     bool runOnFunction(Function &Fn) {
149       // First pass over the function, lower any unknown intrinsic functions
150       // with the IntrinsicLowering class.
151       LowerUnknownIntrinsicFunctionCalls(Fn);
152
153       F = &MachineFunction::construct(&Fn, TM);
154
155       // Create all of the machine basic blocks for the function...
156       for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
157         F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
158
159       BB = &F->front();
160
161       // Make sure we re-emit a set of the global base reg if necessary
162       GlobalBaseInitialized = false;
163
164       // Copy incoming arguments off of the stack...
165       LoadArgumentsToVirtualRegs(Fn);
166
167       // Instruction select everything except PHI nodes
168       visit(Fn);
169
170       // Select the PHI nodes
171       SelectPHINodes();
172
173       RegMap.clear();
174       MBBMap.clear();
175       AllocaMap.clear();
176       F = 0;
177       // We always build a machine code representation for the function
178       return true;
179     }
180
181     virtual const char *getPassName() const {
182       return "PowerPC Simple Instruction Selection";
183     }
184
185     /// visitBasicBlock - This method is called when we are visiting a new basic
186     /// block.  This simply creates a new MachineBasicBlock to emit code into
187     /// and adds it to the current MachineFunction.  Subsequent visit* for
188     /// instructions will be invoked for all instructions in the basic block.
189     ///
190     void visitBasicBlock(BasicBlock &LLVM_BB) {
191       BB = MBBMap[&LLVM_BB];
192     }
193
194     /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
195     /// function, lowering any calls to unknown intrinsic functions into the
196     /// equivalent LLVM code.
197     ///
198     void LowerUnknownIntrinsicFunctionCalls(Function &F);
199
200     /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
201     /// from the stack into virtual registers.
202     ///
203     void LoadArgumentsToVirtualRegs(Function &F);
204
205     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
206     /// because we have to generate our sources into the source basic blocks,
207     /// not the current one.
208     ///
209     void SelectPHINodes();
210
211     // Visitation methods for various instructions.  These methods simply emit
212     // fixed PowerPC code for each instruction.
213
214     // Control flow operators
215     void visitReturnInst(ReturnInst &RI);
216     void visitBranchInst(BranchInst &BI);
217
218     struct ValueRecord {
219       Value *Val;
220       unsigned Reg;
221       const Type *Ty;
222       ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
223       ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
224     };
225     
226     // This struct is for recording the necessary operations to emit the GEP
227     struct CollapsedGepOp {
228       bool isMul;
229       Value *index;
230       ConstantSInt *size;
231       CollapsedGepOp(bool mul, Value *i, ConstantSInt *s) :
232         isMul(mul), index(i), size(s) {}
233     };
234
235     void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
236                 const std::vector<ValueRecord> &Args, bool isVarArg);
237     void visitCallInst(CallInst &I);
238     void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
239
240     // Arithmetic operators
241     void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
242     void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
243     void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
244     void visitMul(BinaryOperator &B);
245
246     void visitDiv(BinaryOperator &B) { visitDivRem(B); }
247     void visitRem(BinaryOperator &B) { visitDivRem(B); }
248     void visitDivRem(BinaryOperator &B);
249
250     // Bitwise operators
251     void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
252     void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
253     void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
254
255     // Comparison operators...
256     void visitSetCondInst(SetCondInst &I);
257     unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
258                             MachineBasicBlock *MBB,
259                             MachineBasicBlock::iterator MBBI);
260     void visitSelectInst(SelectInst &SI);
261     
262     
263     // Memory Instructions
264     void visitLoadInst(LoadInst &I);
265     void visitStoreInst(StoreInst &I);
266     void visitGetElementPtrInst(GetElementPtrInst &I);
267     void visitAllocaInst(AllocaInst &I);
268     void visitMallocInst(MallocInst &I);
269     void visitFreeInst(FreeInst &I);
270     
271     // Other operators
272     void visitShiftInst(ShiftInst &I);
273     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
274     void visitCastInst(CastInst &I);
275     void visitVANextInst(VANextInst &I);
276     void visitVAArgInst(VAArgInst &I);
277
278     void visitInstruction(Instruction &I) {
279       std::cerr << "Cannot instruction select: " << I;
280       abort();
281     }
282
283     /// promote32 - Make a value 32-bits wide, and put it somewhere.
284     ///
285     void promote32(unsigned targetReg, const ValueRecord &VR);
286
287     /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
288     /// constant expression GEP support.
289     ///
290     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
291                           Value *Src, User::op_iterator IdxBegin,
292                           User::op_iterator IdxEnd, unsigned TargetReg,
293                           bool CollapseRemainder, ConstantSInt **Remainder,
294                           unsigned *PendingAddReg);
295
296     /// emitCastOperation - Common code shared between visitCastInst and
297     /// constant expression cast support.
298     ///
299     void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
300                            Value *Src, const Type *DestTy, unsigned TargetReg);
301
302     /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
303     /// and constant expression support.
304     ///
305     void emitSimpleBinaryOperation(MachineBasicBlock *BB,
306                                    MachineBasicBlock::iterator IP,
307                                    Value *Op0, Value *Op1,
308                                    unsigned OperatorClass, unsigned TargetReg);
309
310     /// emitBinaryFPOperation - This method handles emission of floating point
311     /// Add (0), Sub (1), Mul (2), and Div (3) operations.
312     void emitBinaryFPOperation(MachineBasicBlock *BB,
313                                MachineBasicBlock::iterator IP,
314                                Value *Op0, Value *Op1,
315                                unsigned OperatorClass, unsigned TargetReg);
316
317     void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
318                       Value *Op0, Value *Op1, unsigned TargetReg);
319
320     void doMultiply(MachineBasicBlock *MBB,
321                     MachineBasicBlock::iterator IP,
322                     unsigned DestReg, Value *Op0, Value *Op1);
323   
324     /// doMultiplyConst - This method will multiply the value in Op0Reg by the
325     /// value of the ContantInt *CI
326     void doMultiplyConst(MachineBasicBlock *MBB, 
327                          MachineBasicBlock::iterator IP,
328                          unsigned DestReg, Value *Op0, ConstantInt *CI);
329
330     void emitDivRemOperation(MachineBasicBlock *BB,
331                              MachineBasicBlock::iterator IP,
332                              Value *Op0, Value *Op1, bool isDiv,
333                              unsigned TargetReg);
334
335     /// emitSetCCOperation - Common code shared between visitSetCondInst and
336     /// constant expression support.
337     ///
338     void emitSetCCOperation(MachineBasicBlock *BB,
339                             MachineBasicBlock::iterator IP,
340                             Value *Op0, Value *Op1, unsigned Opcode,
341                             unsigned TargetReg);
342
343     /// emitShiftOperation - Common code shared between visitShiftInst and
344     /// constant expression support.
345     ///
346     void emitShiftOperation(MachineBasicBlock *MBB,
347                             MachineBasicBlock::iterator IP,
348                             Value *Op, Value *ShiftAmount, bool isLeftShift,
349                             const Type *ResultTy, unsigned DestReg);
350       
351     /// emitSelectOperation - Common code shared between visitSelectInst and the
352     /// constant expression support.
353     ///
354     void emitSelectOperation(MachineBasicBlock *MBB,
355                              MachineBasicBlock::iterator IP,
356                              Value *Cond, Value *TrueVal, Value *FalseVal,
357                              unsigned DestReg);
358
359     /// copyGlobalBaseToRegister - Output the instructions required to put the
360     /// base address to use for accessing globals into a register.
361     ///
362     void ISel::copyGlobalBaseToRegister(MachineBasicBlock *MBB,
363                                         MachineBasicBlock::iterator IP,
364                                         unsigned R);
365
366     /// copyConstantToRegister - Output the instructions required to put the
367     /// specified constant into the specified register.
368     ///
369     void copyConstantToRegister(MachineBasicBlock *MBB,
370                                 MachineBasicBlock::iterator MBBI,
371                                 Constant *C, unsigned Reg);
372
373     void emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
374                    unsigned LHS, unsigned RHS);
375
376     /// makeAnotherReg - This method returns the next register number we haven't
377     /// yet used.
378     ///
379     /// Long values are handled somewhat specially.  They are always allocated
380     /// as pairs of 32 bit integer values.  The register number returned is the
381     /// high 32 bits of the long value, and the regNum+1 is the low 32 bits.
382     ///
383     unsigned makeAnotherReg(const Type *Ty) {
384       assert(dynamic_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo()) &&
385              "Current target doesn't have PPC reg info??");
386       const PowerPCRegisterInfo *PPCRI =
387         static_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo());
388       if (Ty == Type::LongTy || Ty == Type::ULongTy) {
389         const TargetRegisterClass *RC = PPCRI->getRegClassForType(Type::IntTy);
390         // Create the upper part
391         F->getSSARegMap()->createVirtualRegister(RC);
392         // Create the lower part.
393         return F->getSSARegMap()->createVirtualRegister(RC)-1;
394       }
395
396       // Add the mapping of regnumber => reg class to MachineFunction
397       const TargetRegisterClass *RC = PPCRI->getRegClassForType(Ty);
398       return F->getSSARegMap()->createVirtualRegister(RC);
399     }
400
401     /// getReg - This method turns an LLVM value into a register number.
402     ///
403     unsigned getReg(Value &V) { return getReg(&V); }  // Allow references
404     unsigned getReg(Value *V) {
405       // Just append to the end of the current bb.
406       MachineBasicBlock::iterator It = BB->end();
407       return getReg(V, BB, It);
408     }
409     unsigned getReg(Value *V, MachineBasicBlock *MBB,
410                     MachineBasicBlock::iterator IPt);
411     
412     /// canUseAsImmediateForOpcode - This method returns whether a ConstantInt
413     /// is okay to use as an immediate argument to a certain binary operation
414     bool canUseAsImmediateForOpcode(ConstantInt *CI, unsigned Opcode);
415
416     /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
417     /// that is to be statically allocated with the initial stack frame
418     /// adjustment.
419     unsigned getFixedSizedAllocaFI(AllocaInst *AI);
420   };
421 }
422
423 /// dyn_castFixedAlloca - If the specified value is a fixed size alloca
424 /// instruction in the entry block, return it.  Otherwise, return a null
425 /// pointer.
426 static AllocaInst *dyn_castFixedAlloca(Value *V) {
427   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
428     BasicBlock *BB = AI->getParent();
429     if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
430       return AI;
431   }
432   return 0;
433 }
434
435 /// getReg - This method turns an LLVM value into a register number.
436 ///
437 unsigned ISel::getReg(Value *V, MachineBasicBlock *MBB,
438                       MachineBasicBlock::iterator IPt) {
439   if (Constant *C = dyn_cast<Constant>(V)) {
440     unsigned Reg = makeAnotherReg(V->getType());
441     copyConstantToRegister(MBB, IPt, C, Reg);
442     return Reg;
443   } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
444     unsigned Reg = makeAnotherReg(V->getType());
445     unsigned FI = getFixedSizedAllocaFI(AI);
446     addFrameReference(BuildMI(*MBB, IPt, PPC::ADDI, 2, Reg), FI, 0, false);
447     return Reg;
448   }
449
450   unsigned &Reg = RegMap[V];
451   if (Reg == 0) {
452     Reg = makeAnotherReg(V->getType());
453     RegMap[V] = Reg;
454   }
455
456   return Reg;
457 }
458
459 /// canUseAsImmediateForOpcode - This method returns whether a ConstantInt
460 /// is okay to use as an immediate argument to a certain binary operator.
461 ///
462 /// Operator is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for Xor.
463 bool ISel::canUseAsImmediateForOpcode(ConstantInt *CI, unsigned Operator) {
464   ConstantSInt *Op1Cs;
465   ConstantUInt *Op1Cu;
466       
467   // ADDI, Compare, and non-indexed Load take SIMM
468   bool cond1 = (Operator == 0) 
469     && (Op1Cs = dyn_cast<ConstantSInt>(CI))
470     && (Op1Cs->getValue() <= 32767)
471     && (Op1Cs->getValue() >= -32768);
472
473   // SUBI takes -SIMM since it is a mnemonic for ADDI
474   bool cond2 = (Operator == 1)
475     && (Op1Cs = dyn_cast<ConstantSInt>(CI)) 
476     && (Op1Cs->getValue() <= 32768)
477     && (Op1Cs->getValue() >= -32767);
478       
479   // ANDIo, ORI, and XORI take unsigned values
480   bool cond3 = (Operator >= 2)
481     && (Op1Cs = dyn_cast<ConstantSInt>(CI))
482     && (Op1Cs->getValue() >= 0)
483     && (Op1Cs->getValue() <= 32767);
484
485   // ADDI and SUBI take SIMMs, so we have to make sure the UInt would fit
486   bool cond4 = (Operator < 2)
487     && (Op1Cu = dyn_cast<ConstantUInt>(CI)) 
488     && (Op1Cu->getValue() <= 32767);
489
490   // ANDIo, ORI, and XORI take UIMMs, so they can be larger
491   bool cond5 = (Operator >= 2)
492     && (Op1Cu = dyn_cast<ConstantUInt>(CI))
493     && (Op1Cu->getValue() <= 65535);
494
495   if (cond1 || cond2 || cond3 || cond4 || cond5)
496     return true;
497
498   return false;
499 }
500
501 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
502 /// that is to be statically allocated with the initial stack frame
503 /// adjustment.
504 unsigned ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
505   // Already computed this?
506   std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
507   if (I != AllocaMap.end() && I->first == AI) return I->second;
508
509   const Type *Ty = AI->getAllocatedType();
510   ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
511   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
512   TySize *= CUI->getValue();   // Get total allocated size...
513   unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
514       
515   // Create a new stack object using the frame manager...
516   int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
517   AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
518   return FrameIdx;
519 }
520
521
522 /// copyGlobalBaseToRegister - Output the instructions required to put the
523 /// base address to use for accessing globals into a register.
524 ///
525 void ISel::copyGlobalBaseToRegister(MachineBasicBlock *MBB,
526                                     MachineBasicBlock::iterator IP,
527                                     unsigned R) {
528   if (!GlobalBaseInitialized) {
529     // Insert the set of GlobalBaseReg into the first MBB of the function
530     MachineBasicBlock &FirstMBB = F->front();
531     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
532     GlobalBaseReg = makeAnotherReg(Type::IntTy);
533     BuildMI(FirstMBB, MBBI, PPC::IMPLICIT_DEF, 0, PPC::LR);
534     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, GlobalBaseReg);
535     GlobalBaseInitialized = true;
536   }
537   // Emit our copy of GlobalBaseReg to the destination register in the
538   // current MBB
539   BuildMI(*MBB, IP, PPC::OR, 2, R).addReg(GlobalBaseReg)
540     .addReg(GlobalBaseReg);
541 }
542
543 /// copyConstantToRegister - Output the instructions required to put the
544 /// specified constant into the specified register.
545 ///
546 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
547                                   MachineBasicBlock::iterator IP,
548                                   Constant *C, unsigned R) {
549   if (C->getType()->isIntegral()) {
550     unsigned Class = getClassB(C->getType());
551
552     if (Class == cLong) {
553       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(C)) {
554         uint64_t uval = CUI->getValue();
555         unsigned hiUVal = uval >> 32;
556         unsigned loUVal = uval;
557         ConstantUInt *CUHi = ConstantUInt::get(Type::UIntTy, hiUVal);
558         ConstantUInt *CULo = ConstantUInt::get(Type::UIntTy, loUVal);
559         copyConstantToRegister(MBB, IP, CUHi, R);
560         copyConstantToRegister(MBB, IP, CULo, R+1);
561         return;
562       } else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(C)) {
563         int64_t sval = CSI->getValue();
564         int hiSVal = sval >> 32;
565         int loSVal = sval;
566         ConstantSInt *CSHi = ConstantSInt::get(Type::IntTy, hiSVal);
567         ConstantSInt *CSLo = ConstantSInt::get(Type::IntTy, loSVal);
568         copyConstantToRegister(MBB, IP, CSHi, R);
569         copyConstantToRegister(MBB, IP, CSLo, R+1);
570         return;
571       } else {
572         std::cerr << "Unhandled long constant type!\n";
573         abort();
574       }
575     }
576     
577     assert(Class <= cInt && "Type not handled yet!");
578
579     // Handle bool
580     if (C->getType() == Type::BoolTy) {
581       BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(C == ConstantBool::True);
582       return;
583     }
584     
585     // Handle int
586     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(C)) {
587       unsigned uval = CUI->getValue();
588       if (uval < 32768) {
589         BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(uval);
590       } else {
591         unsigned Temp = makeAnotherReg(Type::IntTy);
592         BuildMI(*MBB, IP, PPC::LIS, 1, Temp).addSImm(uval >> 16);
593         BuildMI(*MBB, IP, PPC::ORI, 2, R).addReg(Temp).addImm(uval);
594       }
595       return;
596     } else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(C)) {
597       int sval = CSI->getValue();
598       if (sval < 32768 && sval >= -32768) {
599         BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(sval);
600       } else {
601         unsigned Temp = makeAnotherReg(Type::IntTy);
602         BuildMI(*MBB, IP, PPC::LIS, 1, Temp).addSImm(sval >> 16);
603         BuildMI(*MBB, IP, PPC::ORI, 2, R).addReg(Temp).addImm(sval);
604       }
605       return;
606     }
607     std::cerr << "Unhandled integer constant!\n";
608     abort();
609   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
610     // We need to spill the constant to memory...
611     MachineConstantPool *CP = F->getConstantPool();
612     unsigned CPI = CP->getConstantPoolIndex(CFP);
613     const Type *Ty = CFP->getType();
614
615     assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
616
617     // Load addr of constant to reg; constant is located at base + distance
618     unsigned GlobalBase = makeAnotherReg(Type::IntTy);
619     unsigned Reg1 = makeAnotherReg(Type::IntTy);
620     unsigned Reg2 = makeAnotherReg(Type::IntTy);
621     // Move value at base + distance into return reg
622     copyGlobalBaseToRegister(MBB, IP, GlobalBase);
623     BuildMI(*MBB, IP, PPC::LOADHiAddr, 2, Reg1).addReg(GlobalBase)
624       .addConstantPoolIndex(CPI);
625     BuildMI(*MBB, IP, PPC::LOADLoDirect, 2, Reg2).addReg(Reg1)
626       .addConstantPoolIndex(CPI);
627     BuildMI(*MBB, IP, PPC::LFD, 2, R).addSImm(0).addReg(Reg2);
628   } else if (isa<ConstantPointerNull>(C)) {
629     // Copy zero (null pointer) to the register.
630     BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(0);
631   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
632     // GV is located at base + distance
633     unsigned GlobalBase = makeAnotherReg(Type::IntTy);
634     unsigned TmpReg = makeAnotherReg(GV->getType());
635     unsigned Opcode = (GV->hasWeakLinkage() || GV->isExternal() 
636                                             || dyn_cast<Function>(GV)) ? 
637       PPC::LOADLoIndirect : PPC::LOADLoDirect;
638     
639     // Move value at base + distance into return reg
640     copyGlobalBaseToRegister(MBB, IP, GlobalBase);
641     BuildMI(*MBB, IP, PPC::LOADHiAddr, 2, TmpReg).addReg(GlobalBase)
642       .addGlobalAddress(GV);
643     BuildMI(*MBB, IP, Opcode, 2, R).addReg(TmpReg).addGlobalAddress(GV);
644   
645     // Add the GV to the list of things whose addresses have been taken.
646     TM.AddressTaken.insert(GV);
647   } else {
648     std::cerr << "Offending constant: " << *C << "\n";
649     assert(0 && "Type not handled yet!");
650   }
651 }
652
653 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
654 /// the stack into virtual registers.
655 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
656   unsigned ArgOffset = 24;
657   unsigned GPR_remaining = 8;
658   unsigned FPR_remaining = 13;
659   unsigned GPR_idx = 0, FPR_idx = 0;
660   static const unsigned GPR[] = { 
661     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
662     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
663   };
664   static const unsigned FPR[] = {
665     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
666     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
667   };
668     
669   MachineFrameInfo *MFI = F->getFrameInfo();
670  
671   for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
672     bool ArgLive = !I->use_empty();
673     unsigned Reg = ArgLive ? getReg(*I) : 0;
674     int FI;          // Frame object index
675
676     switch (getClassB(I->getType())) {
677     case cByte:
678       if (ArgLive) {
679         FI = MFI->CreateFixedObject(4, ArgOffset);
680         if (GPR_remaining > 0) {
681           BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
682           BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
683             .addReg(GPR[GPR_idx]);
684         } else {
685           addFrameReference(BuildMI(BB, PPC::LBZ, 2, Reg), FI);
686         }
687       }
688       break;
689     case cShort:
690       if (ArgLive) {
691         FI = MFI->CreateFixedObject(4, ArgOffset);
692         if (GPR_remaining > 0) {
693           BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
694           BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
695             .addReg(GPR[GPR_idx]);
696         } else {
697           addFrameReference(BuildMI(BB, PPC::LHZ, 2, Reg), FI);
698         }
699       }
700       break;
701     case cInt:
702       if (ArgLive) {
703         FI = MFI->CreateFixedObject(4, ArgOffset);
704         if (GPR_remaining > 0) {
705           BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
706           BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
707             .addReg(GPR[GPR_idx]);
708         } else {
709           addFrameReference(BuildMI(BB, PPC::LWZ, 2, Reg), FI);
710         }
711       }
712       break;
713     case cLong:
714       if (ArgLive) {
715         FI = MFI->CreateFixedObject(8, ArgOffset);
716         if (GPR_remaining > 1) {
717           BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
718           BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx+1]);
719           BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
720             .addReg(GPR[GPR_idx]);
721           BuildMI(BB, PPC::OR, 2, Reg+1).addReg(GPR[GPR_idx+1])
722             .addReg(GPR[GPR_idx+1]);
723         } else {
724           addFrameReference(BuildMI(BB, PPC::LWZ, 2, Reg), FI);
725           addFrameReference(BuildMI(BB, PPC::LWZ, 2, Reg+1), FI, 4);
726         }
727       }
728       // longs require 4 additional bytes and use 2 GPRs
729       ArgOffset += 4;
730       if (GPR_remaining > 1) {
731         GPR_remaining--;
732         GPR_idx++;
733       }
734       break;
735     case cFP32:
736      if (ArgLive) {
737         FI = MFI->CreateFixedObject(4, ArgOffset);
738
739         if (FPR_remaining > 0) {
740           BuildMI(BB, PPC::IMPLICIT_DEF, 0, FPR[FPR_idx]);
741           BuildMI(BB, PPC::FMR, 1, Reg).addReg(FPR[FPR_idx]);
742           FPR_remaining--;
743           FPR_idx++;
744         } else {
745           addFrameReference(BuildMI(BB, PPC::LFS, 2, Reg), FI);
746         }
747       }
748       break;
749     case cFP64:
750       if (ArgLive) {
751         FI = MFI->CreateFixedObject(8, ArgOffset);
752
753         if (FPR_remaining > 0) {
754           BuildMI(BB, PPC::IMPLICIT_DEF, 0, FPR[FPR_idx]);
755           BuildMI(BB, PPC::FMR, 1, Reg).addReg(FPR[FPR_idx]);
756           FPR_remaining--;
757           FPR_idx++;
758         } else {
759           addFrameReference(BuildMI(BB, PPC::LFD, 2, Reg), FI);
760         }
761       }
762
763       // doubles require 4 additional bytes and use 2 GPRs of param space
764       ArgOffset += 4;   
765       if (GPR_remaining > 0) {
766         GPR_remaining--;
767         GPR_idx++;
768       }
769       break;
770     default:
771       assert(0 && "Unhandled argument type!");
772     }
773     ArgOffset += 4;  // Each argument takes at least 4 bytes on the stack...
774     if (GPR_remaining > 0) {
775       GPR_remaining--;    // uses up 2 GPRs
776       GPR_idx++;
777     }
778   }
779
780   // If the function takes variable number of arguments, add a frame offset for
781   // the start of the first vararg value... this is used to expand
782   // llvm.va_start.
783   if (Fn.getFunctionType()->isVarArg())
784     VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
785 }
786
787
788 /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
789 /// because we have to generate our sources into the source basic blocks, not
790 /// the current one.
791 ///
792 void ISel::SelectPHINodes() {
793   const TargetInstrInfo &TII = *TM.getInstrInfo();
794   const Function &LF = *F->getFunction();  // The LLVM function...
795   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
796     const BasicBlock *BB = I;
797     MachineBasicBlock &MBB = *MBBMap[I];
798
799     // Loop over all of the PHI nodes in the LLVM basic block...
800     MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
801     for (BasicBlock::const_iterator I = BB->begin();
802          PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
803
804       // Create a new machine instr PHI node, and insert it.
805       unsigned PHIReg = getReg(*PN);
806       MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
807                                     PPC::PHI, PN->getNumOperands(), PHIReg);
808
809       MachineInstr *LongPhiMI = 0;
810       if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
811         LongPhiMI = BuildMI(MBB, PHIInsertPoint,
812                             PPC::PHI, PN->getNumOperands(), PHIReg+1);
813
814       // PHIValues - Map of blocks to incoming virtual registers.  We use this
815       // so that we only initialize one incoming value for a particular block,
816       // even if the block has multiple entries in the PHI node.
817       //
818       std::map<MachineBasicBlock*, unsigned> PHIValues;
819
820       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
821         MachineBasicBlock *PredMBB = 0;
822         for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
823              PE = MBB.pred_end (); PI != PE; ++PI)
824           if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
825             PredMBB = *PI;
826             break;
827           }
828         assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
829
830         unsigned ValReg;
831         std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
832           PHIValues.lower_bound(PredMBB);
833
834         if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
835           // We already inserted an initialization of the register for this
836           // predecessor.  Recycle it.
837           ValReg = EntryIt->second;
838         } else {
839           // Get the incoming value into a virtual register.
840           //
841           Value *Val = PN->getIncomingValue(i);
842
843           // If this is a constant or GlobalValue, we may have to insert code
844           // into the basic block to compute it into a virtual register.
845           if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
846               isa<GlobalValue>(Val)) {
847             // Simple constants get emitted at the end of the basic block,
848             // before any terminator instructions.  We "know" that the code to
849             // move a constant into a register will never clobber any flags.
850             ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
851           } else {
852             // Because we don't want to clobber any values which might be in
853             // physical registers with the computation of this constant (which
854             // might be arbitrarily complex if it is a constant expression),
855             // just insert the computation at the top of the basic block.
856             MachineBasicBlock::iterator PI = PredMBB->begin();
857
858             // Skip over any PHI nodes though!
859             while (PI != PredMBB->end() && PI->getOpcode() == PPC::PHI)
860               ++PI;
861
862             ValReg = getReg(Val, PredMBB, PI);
863           }
864
865           // Remember that we inserted a value for this PHI for this predecessor
866           PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
867         }
868
869         PhiMI->addRegOperand(ValReg);
870         PhiMI->addMachineBasicBlockOperand(PredMBB);
871         if (LongPhiMI) {
872           LongPhiMI->addRegOperand(ValReg+1);
873           LongPhiMI->addMachineBasicBlockOperand(PredMBB);
874         }
875       }
876
877       // Now that we emitted all of the incoming values for the PHI node, make
878       // sure to reposition the InsertPoint after the PHI that we just added.
879       // This is needed because we might have inserted a constant into this
880       // block, right after the PHI's which is before the old insert point!
881       PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
882       ++PHIInsertPoint;
883     }
884   }
885 }
886
887
888 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
889 // it into the conditional branch or select instruction which is the only user
890 // of the cc instruction.  This is the case if the conditional branch is the
891 // only user of the setcc, and if the setcc is in the same basic block as the
892 // conditional branch.
893 //
894 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
895   if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
896     if (SCI->hasOneUse()) {
897       Instruction *User = cast<Instruction>(SCI->use_back());
898       if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
899           SCI->getParent() == User->getParent())
900         return SCI;
901     }
902   return 0;
903 }
904
905
906 // canFoldGEPIntoLoadOrStore - Return the GEP instruction if we can fold it into
907 // the load or store instruction that is the only user of the GEP.
908 //
909 static GetElementPtrInst *canFoldGEPIntoLoadOrStore(Value *V) {
910   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V))
911     if (GEPI->hasOneUse()) {
912       Instruction *User = cast<Instruction>(GEPI->use_back());
913       if (isa<StoreInst>(User) &&
914           GEPI->getParent() == User->getParent() &&
915           User->getOperand(0) != GEPI &&
916           User->getOperand(1) == GEPI) {
917         ++GEPFolds;
918         return GEPI;
919       }
920       if (isa<LoadInst>(User) &&
921           GEPI->getParent() == User->getParent() &&
922           User->getOperand(0) == GEPI) {
923         ++GEPFolds;
924         return GEPI;
925       }
926     }
927   return 0;
928 }
929
930
931 // Return a fixed numbering for setcc instructions which does not depend on the
932 // order of the opcodes.
933 //
934 static unsigned getSetCCNumber(unsigned Opcode) {
935   switch (Opcode) {
936   default: assert(0 && "Unknown setcc instruction!");
937   case Instruction::SetEQ: return 0;
938   case Instruction::SetNE: return 1;
939   case Instruction::SetLT: return 2;
940   case Instruction::SetGE: return 3;
941   case Instruction::SetGT: return 4;
942   case Instruction::SetLE: return 5;
943   }
944 }
945
946 static unsigned getPPCOpcodeForSetCCNumber(unsigned Opcode) {
947   switch (Opcode) {
948   default: assert(0 && "Unknown setcc instruction!");
949   case Instruction::SetEQ: return PPC::BEQ;
950   case Instruction::SetNE: return PPC::BNE;
951   case Instruction::SetLT: return PPC::BLT;
952   case Instruction::SetGE: return PPC::BGE;
953   case Instruction::SetGT: return PPC::BGT;
954   case Instruction::SetLE: return PPC::BLE;
955   }
956 }
957
958 /// emitUCOM - emits an unordered FP compare.
959 void ISel::emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
960                      unsigned LHS, unsigned RHS) {
961     BuildMI(*MBB, IP, PPC::FCMPU, 2, PPC::CR0).addReg(LHS).addReg(RHS);
962 }
963
964 /// EmitComparison - emits a comparison of the two operands, returning the
965 /// extended setcc code to use.  The result is in CR0.
966 ///
967 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
968                               MachineBasicBlock *MBB,
969                               MachineBasicBlock::iterator IP) {
970   // The arguments are already supposed to be of the same type.
971   const Type *CompTy = Op0->getType();
972   unsigned Class = getClassB(CompTy);
973   unsigned Op0r = getReg(Op0, MBB, IP);
974
975   // Before we do a comparison, we have to make sure that we're truncating our
976   // registers appropriately.
977   if (Class == cByte) {
978     unsigned TmpReg = makeAnotherReg(CompTy);
979     if (CompTy->isSigned())
980       BuildMI(*MBB, IP, PPC::EXTSB, 1, TmpReg).addReg(Op0r);
981     else
982       BuildMI(*MBB, IP, PPC::RLWINM, 4, TmpReg).addReg(Op0r).addImm(0)
983         .addImm(24).addImm(31);
984     Op0r = TmpReg;
985   } else if (Class == cShort) {
986     unsigned TmpReg = makeAnotherReg(CompTy);
987     if (CompTy->isSigned())
988       BuildMI(*MBB, IP, PPC::EXTSH, 1, TmpReg).addReg(Op0r);
989     else
990       BuildMI(*MBB, IP, PPC::RLWINM, 4, TmpReg).addReg(Op0r).addImm(0)
991         .addImm(16).addImm(31);
992     Op0r = TmpReg;
993   }
994   
995   // Use crand for lt, gt and crandc for le, ge
996   unsigned CROpcode = (OpNum == 2 || OpNum == 4) ? PPC::CRAND : PPC::CRANDC;
997   // ? cr1[lt] : cr1[gt]
998   unsigned CR1field = (OpNum == 2 || OpNum == 3) ? 4 : 5;
999   // ? cr0[lt] : cr0[gt]
1000   unsigned CR0field = (OpNum == 2 || OpNum == 5) ? 0 : 1;
1001   unsigned Opcode = CompTy->isSigned() ? PPC::CMPW : PPC::CMPLW;
1002   unsigned OpcodeImm = CompTy->isSigned() ? PPC::CMPWI : PPC::CMPLWI;
1003
1004   // Special case handling of: cmp R, i
1005   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1006     if (Class == cByte || Class == cShort || Class == cInt) {
1007       unsigned Op1v = CI->getRawValue() & 0xFFFF;
1008
1009       // Treat compare like ADDI for the purposes of immediate suitability
1010       if (canUseAsImmediateForOpcode(CI, 0)) {
1011         BuildMI(*MBB, IP, OpcodeImm, 2, PPC::CR0).addReg(Op0r).addSImm(Op1v);
1012       } else {
1013         unsigned Op1r = getReg(Op1, MBB, IP);
1014         BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r).addReg(Op1r);
1015       }
1016       return OpNum;
1017     } else {
1018       assert(Class == cLong && "Unknown integer class!");
1019       unsigned LowCst = CI->getRawValue();
1020       unsigned HiCst = CI->getRawValue() >> 32;
1021       if (OpNum < 2) {    // seteq, setne
1022         unsigned LoLow = makeAnotherReg(Type::IntTy);
1023         unsigned LoTmp = makeAnotherReg(Type::IntTy);
1024         unsigned HiLow = makeAnotherReg(Type::IntTy);
1025         unsigned HiTmp = makeAnotherReg(Type::IntTy);
1026         unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1027
1028         BuildMI(*MBB, IP, PPC::XORI, 2, LoLow).addReg(Op0r+1)
1029           .addImm(LowCst & 0xFFFF);
1030         BuildMI(*MBB, IP, PPC::XORIS, 2, LoTmp).addReg(LoLow)
1031           .addImm(LowCst >> 16);
1032         BuildMI(*MBB, IP, PPC::XORI, 2, HiLow).addReg(Op0r)
1033           .addImm(HiCst & 0xFFFF);
1034         BuildMI(*MBB, IP, PPC::XORIS, 2, HiTmp).addReg(HiLow)
1035           .addImm(HiCst >> 16);
1036         BuildMI(*MBB, IP, PPC::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1037         return OpNum;
1038       } else {
1039         unsigned ConstReg = makeAnotherReg(CompTy);
1040         copyConstantToRegister(MBB, IP, CI, ConstReg);
1041
1042         // cr0 = r3 ccOpcode r5 or (r3 == r5 AND r4 ccOpcode r6)
1043         BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r)
1044           .addReg(ConstReg);
1045         BuildMI(*MBB, IP, Opcode, 2, PPC::CR1).addReg(Op0r+1)
1046           .addReg(ConstReg+1);
1047         BuildMI(*MBB, IP, PPC::CRAND, 3).addImm(2).addImm(2).addImm(CR1field);
1048         BuildMI(*MBB, IP, PPC::CROR, 3).addImm(CR0field).addImm(CR0field)
1049           .addImm(2);
1050         return OpNum;
1051       }
1052     }
1053   }
1054
1055   unsigned Op1r = getReg(Op1, MBB, IP);
1056
1057   switch (Class) {
1058   default: assert(0 && "Unknown type class!");
1059   case cByte:
1060   case cShort:
1061   case cInt:
1062     BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r).addReg(Op1r);
1063     break;
1064
1065   case cFP32:
1066   case cFP64:
1067     emitUCOM(MBB, IP, Op0r, Op1r);
1068     break;
1069
1070   case cLong:
1071     if (OpNum < 2) {    // seteq, setne
1072       unsigned LoTmp = makeAnotherReg(Type::IntTy);
1073       unsigned HiTmp = makeAnotherReg(Type::IntTy);
1074       unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1075       BuildMI(*MBB, IP, PPC::XOR, 2, HiTmp).addReg(Op0r).addReg(Op1r);
1076       BuildMI(*MBB, IP, PPC::XOR, 2, LoTmp).addReg(Op0r+1).addReg(Op1r+1);
1077       BuildMI(*MBB, IP, PPC::ORo,  2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1078       break;  // Allow the sete or setne to be generated from flags set by OR
1079     } else {
1080       unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
1081       unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1082
1083       // cr0 = r3 ccOpcode r5 or (r3 == r5 AND r4 ccOpcode r6)
1084       BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r).addReg(Op1r);
1085       BuildMI(*MBB, IP, Opcode, 2, PPC::CR1).addReg(Op0r+1).addReg(Op1r+1);
1086       BuildMI(*MBB, IP, PPC::CRAND, 3).addImm(2).addImm(2).addImm(CR1field);
1087       BuildMI(*MBB, IP, PPC::CROR, 3).addImm(CR0field).addImm(CR0field)
1088         .addImm(2);
1089       return OpNum;
1090     }
1091   }
1092   return OpNum;
1093 }
1094
1095 /// visitSetCondInst - emit code to calculate the condition via
1096 /// EmitComparison(), and possibly store a 0 or 1 to a register as a result
1097 ///
1098 void ISel::visitSetCondInst(SetCondInst &I) {
1099   if (canFoldSetCCIntoBranchOrSelect(&I))
1100     return;
1101
1102   unsigned DestReg = getReg(I);
1103   unsigned OpNum = I.getOpcode();
1104   const Type *Ty = I.getOperand (0)->getType();
1105
1106   EmitComparison(OpNum, I.getOperand(0), I.getOperand(1), BB, BB->end());
1107   
1108   unsigned Opcode = getPPCOpcodeForSetCCNumber(OpNum);
1109   MachineBasicBlock *thisMBB = BB;
1110   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1111   ilist<MachineBasicBlock>::iterator It = BB;
1112   ++It;
1113   
1114   //  thisMBB:
1115   //  ...
1116   //   cmpTY cr0, r1, r2
1117   //   bCC copy1MBB
1118   //   b copy0MBB
1119
1120   // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1121   // if we could insert other, non-terminator instructions after the
1122   // bCC. But MBB->getFirstTerminator() can't understand this.
1123   MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
1124   F->getBasicBlockList().insert(It, copy1MBB);
1125   BuildMI(BB, Opcode, 2).addReg(PPC::CR0).addMBB(copy1MBB);
1126   MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1127   F->getBasicBlockList().insert(It, copy0MBB);
1128   BuildMI(BB, PPC::B, 1).addMBB(copy0MBB);
1129   MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1130   F->getBasicBlockList().insert(It, sinkMBB);
1131   // Update machine-CFG edges
1132   BB->addSuccessor(copy1MBB);
1133   BB->addSuccessor(copy0MBB);
1134
1135   //  copy1MBB:
1136   //   %TrueValue = li 1
1137   //   b sinkMBB
1138   BB = copy1MBB;
1139   unsigned TrueValue = makeAnotherReg(I.getType());
1140   BuildMI(BB, PPC::LI, 1, TrueValue).addSImm(1);
1141   BuildMI(BB, PPC::B, 1).addMBB(sinkMBB);
1142   // Update machine-CFG edges
1143   BB->addSuccessor(sinkMBB);
1144
1145   //  copy0MBB:
1146   //   %FalseValue = li 0
1147   //   fallthrough
1148   BB = copy0MBB;
1149   unsigned FalseValue = makeAnotherReg(I.getType());
1150   BuildMI(BB, PPC::LI, 1, FalseValue).addSImm(0);
1151   // Update machine-CFG edges
1152   BB->addSuccessor(sinkMBB);
1153
1154   //  sinkMBB:
1155   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1156   //  ...
1157   BB = sinkMBB;
1158   BuildMI(BB, PPC::PHI, 4, DestReg).addReg(FalseValue)
1159     .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
1160 }
1161
1162 void ISel::visitSelectInst(SelectInst &SI) {
1163   unsigned DestReg = getReg(SI);
1164   MachineBasicBlock::iterator MII = BB->end();
1165   emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1166                       SI.getFalseValue(), DestReg);
1167 }
1168  
1169 /// emitSelect - Common code shared between visitSelectInst and the constant
1170 /// expression support.
1171 /// FIXME: this is most likely broken in one or more ways.  Namely, PowerPC has
1172 /// no select instruction.  FSEL only works for comparisons against zero.
1173 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1174                                MachineBasicBlock::iterator IP,
1175                                Value *Cond, Value *TrueVal, Value *FalseVal,
1176                                unsigned DestReg) {
1177   unsigned SelectClass = getClassB(TrueVal->getType());
1178   unsigned Opcode;
1179
1180   // See if we can fold the setcc into the select instruction, or if we have
1181   // to get the register of the Cond value
1182   if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1183     // We successfully folded the setcc into the select instruction.
1184     unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1185     OpNum = EmitComparison(OpNum, SCI->getOperand(0),SCI->getOperand(1),MBB,IP);
1186     Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1187   } else {
1188     unsigned CondReg = getReg(Cond, MBB, IP);
1189     BuildMI(*MBB, IP, PPC::CMPI, 2, PPC::CR0).addReg(CondReg).addSImm(0);
1190     Opcode = getPPCOpcodeForSetCCNumber(Instruction::SetNE);
1191   }
1192
1193   //  thisMBB:
1194   //  ...
1195   //   cmpTY cr0, r1, r2
1196   //   bCC copy1MBB
1197   //   b copy0MBB
1198
1199   MachineBasicBlock *thisMBB = BB;
1200   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1201   ilist<MachineBasicBlock>::iterator It = BB;
1202   ++It;
1203
1204   // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1205   // if we could insert other, non-terminator instructions after the
1206   // bCC. But MBB->getFirstTerminator() can't understand this.
1207   MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
1208   F->getBasicBlockList().insert(It, copy1MBB);
1209   BuildMI(BB, Opcode, 2).addReg(PPC::CR0).addMBB(copy1MBB);
1210   MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1211   F->getBasicBlockList().insert(It, copy0MBB);
1212   BuildMI(BB, PPC::B, 1).addMBB(copy0MBB);
1213   MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1214   F->getBasicBlockList().insert(It, sinkMBB);
1215   // Update machine-CFG edges
1216   BB->addSuccessor(copy1MBB);
1217   BB->addSuccessor(copy0MBB);
1218
1219   //  copy1MBB:
1220   //   %TrueValue = ...
1221   //   b sinkMBB
1222   BB = copy1MBB;
1223   unsigned TrueValue = getReg(TrueVal, BB, BB->begin());
1224   BuildMI(BB, PPC::B, 1).addMBB(sinkMBB);
1225   // Update machine-CFG edges
1226   BB->addSuccessor(sinkMBB);
1227
1228   //  copy0MBB:
1229   //   %FalseValue = ...
1230   //   fallthrough
1231   BB = copy0MBB;
1232   unsigned FalseValue = getReg(FalseVal, BB, BB->begin());
1233   // Update machine-CFG edges
1234   BB->addSuccessor(sinkMBB);
1235
1236   //  sinkMBB:
1237   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1238   //  ...
1239   BB = sinkMBB;
1240   BuildMI(BB, PPC::PHI, 4, DestReg).addReg(FalseValue)
1241     .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
1242   // For a register pair representing a long value, define the second reg
1243   if (getClassB(TrueVal->getType()) == cLong)
1244     BuildMI(BB, PPC::LI, 1, DestReg+1).addImm(0);
1245   return;
1246 }
1247
1248
1249
1250 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1251 /// operand, in the specified target register.
1252 ///
1253 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1254   bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
1255
1256   Value *Val = VR.Val;
1257   const Type *Ty = VR.Ty;
1258   if (Val) {
1259     if (Constant *C = dyn_cast<Constant>(Val)) {
1260       Val = ConstantExpr::getCast(C, Type::IntTy);
1261       if (isa<ConstantExpr>(Val))   // Could not fold
1262         Val = C;
1263       else
1264         Ty = Type::IntTy;           // Folded!
1265     }
1266
1267     // If this is a simple constant, just emit a load directly to avoid the copy
1268     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1269       int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1270
1271       if (TheVal < 32768 && TheVal >= -32768) {
1272         BuildMI(BB, PPC::LI, 1, targetReg).addSImm(TheVal);
1273       } else {
1274         unsigned TmpReg = makeAnotherReg(Type::IntTy);
1275         BuildMI(BB, PPC::LIS, 1, TmpReg).addSImm(TheVal >> 16);
1276         BuildMI(BB, PPC::ORI, 2, targetReg).addReg(TmpReg)
1277           .addImm(TheVal & 0xFFFF);
1278       }
1279       return;
1280     }
1281   }
1282
1283   // Make sure we have the register number for this value...
1284   unsigned Reg = Val ? getReg(Val) : VR.Reg;
1285   switch (getClassB(Ty)) {
1286   case cByte:
1287     // Extend value into target register (8->32)
1288     if (isUnsigned)
1289       BuildMI(BB, PPC::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1290         .addZImm(24).addZImm(31);
1291     else
1292       BuildMI(BB, PPC::EXTSB, 1, targetReg).addReg(Reg);
1293     break;
1294   case cShort:
1295     // Extend value into target register (16->32)
1296     if (isUnsigned)
1297       BuildMI(BB, PPC::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1298         .addZImm(16).addZImm(31);
1299     else
1300       BuildMI(BB, PPC::EXTSH, 1, targetReg).addReg(Reg);
1301     break;
1302   case cInt:
1303     // Move value into target register (32->32)
1304     BuildMI(BB, PPC::OR, 2, targetReg).addReg(Reg).addReg(Reg);
1305     break;
1306   default:
1307     assert(0 && "Unpromotable operand class in promote32");
1308   }
1309 }
1310
1311 /// visitReturnInst - implemented with BLR
1312 ///
1313 void ISel::visitReturnInst(ReturnInst &I) {
1314   // Only do the processing if this is a non-void return
1315   if (I.getNumOperands() > 0) {
1316     Value *RetVal = I.getOperand(0);
1317     switch (getClassB(RetVal->getType())) {
1318     case cByte:   // integral return values: extend or move into r3 and return
1319     case cShort:
1320     case cInt:
1321       promote32(PPC::R3, ValueRecord(RetVal));
1322       break;
1323     case cFP32:
1324     case cFP64: {   // Floats & Doubles: Return in f1
1325       unsigned RetReg = getReg(RetVal);
1326       BuildMI(BB, PPC::FMR, 1, PPC::F1).addReg(RetReg);
1327       break;
1328     }
1329     case cLong: {
1330       unsigned RetReg = getReg(RetVal);
1331       BuildMI(BB, PPC::OR, 2, PPC::R3).addReg(RetReg).addReg(RetReg);
1332       BuildMI(BB, PPC::OR, 2, PPC::R4).addReg(RetReg+1).addReg(RetReg+1);
1333       break;
1334     }
1335     default:
1336       visitInstruction(I);
1337     }
1338   }
1339   BuildMI(BB, PPC::BLR, 1).addImm(0);
1340 }
1341
1342 // getBlockAfter - Return the basic block which occurs lexically after the
1343 // specified one.
1344 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1345   Function::iterator I = BB; ++I;  // Get iterator to next block
1346   return I != BB->getParent()->end() ? &*I : 0;
1347 }
1348
1349 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
1350 /// that since code layout is frozen at this point, that if we are trying to
1351 /// jump to a block that is the immediate successor of the current block, we can
1352 /// just make a fall-through (but we don't currently).
1353 ///
1354 void ISel::visitBranchInst(BranchInst &BI) {
1355   // Update machine-CFG edges
1356   BB->addSuccessor(MBBMap[BI.getSuccessor(0)]);
1357   if (BI.isConditional())
1358     BB->addSuccessor(MBBMap[BI.getSuccessor(1)]);
1359   
1360   BasicBlock *NextBB = getBlockAfter(BI.getParent());  // BB after current one
1361
1362   if (!BI.isConditional()) {  // Unconditional branch?
1363     if (BI.getSuccessor(0) != NextBB) 
1364       BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1365     return;
1366   }
1367   
1368   // See if we can fold the setcc into the branch itself...
1369   SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1370   if (SCI == 0) {
1371     // Nope, cannot fold setcc into this branch.  Emit a branch on a condition
1372     // computed some other way...
1373     unsigned condReg = getReg(BI.getCondition());
1374     BuildMI(BB, PPC::CMPLI, 3, PPC::CR0).addImm(0).addReg(condReg)
1375       .addImm(0);
1376     if (BI.getSuccessor(1) == NextBB) {
1377       if (BI.getSuccessor(0) != NextBB)
1378         BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(PPC::BNE)
1379           .addMBB(MBBMap[BI.getSuccessor(0)])
1380           .addMBB(MBBMap[BI.getSuccessor(1)]);
1381     } else {
1382       BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(PPC::BEQ)
1383         .addMBB(MBBMap[BI.getSuccessor(1)])
1384         .addMBB(MBBMap[BI.getSuccessor(0)]);
1385       if (BI.getSuccessor(0) != NextBB)
1386         BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1387     }
1388     return;
1389   }
1390
1391   unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1392   unsigned Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1393   MachineBasicBlock::iterator MII = BB->end();
1394   OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1395   
1396   if (BI.getSuccessor(0) != NextBB) {
1397     BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(Opcode)
1398       .addMBB(MBBMap[BI.getSuccessor(0)])
1399       .addMBB(MBBMap[BI.getSuccessor(1)]);
1400     if (BI.getSuccessor(1) != NextBB)
1401       BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1402   } else {
1403     // Change to the inverse condition...
1404     if (BI.getSuccessor(1) != NextBB) {
1405       Opcode = PowerPCInstrInfo::invertPPCBranchOpcode(Opcode);
1406       BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(Opcode)
1407         .addMBB(MBBMap[BI.getSuccessor(1)])
1408         .addMBB(MBBMap[BI.getSuccessor(0)]);
1409     }
1410   }
1411 }
1412
1413 /// doCall - This emits an abstract call instruction, setting up the arguments
1414 /// and the return value as appropriate.  For the actual function call itself,
1415 /// it inserts the specified CallMI instruction into the stream.
1416 ///
1417 /// FIXME: See Documentation at the following URL for "correct" behavior
1418 /// <http://developer.apple.com/documentation/DeveloperTools/Conceptual/MachORuntime/2rt_powerpc_abi/chapter_9_section_5.html>
1419 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1420                   const std::vector<ValueRecord> &Args, bool isVarArg) {
1421   // Count how many bytes are to be pushed on the stack, including the linkage
1422   // area, and parameter passing area.
1423   unsigned NumBytes = 24;
1424   unsigned ArgOffset = 24;
1425
1426   if (!Args.empty()) {
1427     for (unsigned i = 0, e = Args.size(); i != e; ++i)
1428       switch (getClassB(Args[i].Ty)) {
1429       case cByte: case cShort: case cInt:
1430         NumBytes += 4; break;
1431       case cLong:
1432         NumBytes += 8; break;
1433       case cFP32:
1434         NumBytes += 4; break;
1435       case cFP64:
1436         NumBytes += 8; break;
1437         break;
1438       default: assert(0 && "Unknown class!");
1439       }
1440
1441     // Just to be safe, we'll always reserve the full 32 bytes worth of
1442     // argument passing space in case any called code gets funky on us.
1443     if (NumBytes < 24 + 32) NumBytes = 24 + 32;
1444
1445     // Adjust the stack pointer for the new arguments...
1446     // These functions are automatically eliminated by the prolog/epilog pass
1447     BuildMI(BB, PPC::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1448
1449     // Arguments go on the stack in reverse order, as specified by the ABI.
1450     // Offset to the paramater area on the stack is 24.
1451     int GPR_remaining = 8, FPR_remaining = 13;
1452     unsigned GPR_idx = 0, FPR_idx = 0;
1453     static const unsigned GPR[] = { 
1454       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1455       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1456     };
1457     static const unsigned FPR[] = {
1458       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, 
1459       PPC::F7, PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, 
1460       PPC::F13
1461     };
1462     
1463     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1464       unsigned ArgReg;
1465       switch (getClassB(Args[i].Ty)) {
1466       case cByte:
1467       case cShort:
1468         // Promote arg to 32 bits wide into a temporary register...
1469         ArgReg = makeAnotherReg(Type::UIntTy);
1470         promote32(ArgReg, Args[i]);
1471           
1472         // Reg or stack?
1473         if (GPR_remaining > 0) {
1474           BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1475             .addReg(ArgReg);
1476           CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1477         }
1478         if (GPR_remaining <= 0 || isVarArg) {
1479           BuildMI(BB, PPC::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1480             .addReg(PPC::R1);
1481         }
1482         break;
1483       case cInt:
1484         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1485
1486         // Reg or stack?
1487         if (GPR_remaining > 0) {
1488           BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1489             .addReg(ArgReg);
1490           CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1491         }
1492         if (GPR_remaining <= 0 || isVarArg) {
1493           BuildMI(BB, PPC::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1494             .addReg(PPC::R1);
1495         }
1496         break;
1497       case cLong:
1498         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1499
1500         // Reg or stack?  Note that PPC calling conventions state that long args
1501         // are passed rN = hi, rN+1 = lo, opposite of LLVM.
1502         if (GPR_remaining > 1) {
1503           BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1504             .addReg(ArgReg);
1505           BuildMI(BB, PPC::OR, 2, GPR[GPR_idx+1]).addReg(ArgReg+1)
1506             .addReg(ArgReg+1);
1507           CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1508           CallMI->addRegOperand(GPR[GPR_idx+1], MachineOperand::Use);
1509         }
1510         if (GPR_remaining <= 1 || isVarArg) {
1511           BuildMI(BB, PPC::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1512             .addReg(PPC::R1);
1513           BuildMI(BB, PPC::STW, 3).addReg(ArgReg+1).addSImm(ArgOffset+4)
1514             .addReg(PPC::R1);
1515         }
1516
1517         ArgOffset += 4;        // 8 byte entry, not 4.
1518         GPR_remaining -= 1;    // uses up 2 GPRs
1519         GPR_idx += 1;
1520         break;
1521       case cFP32:
1522         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1523         // Reg or stack?
1524         if (FPR_remaining > 0) {
1525           BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1526           CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1527           FPR_remaining--;
1528           FPR_idx++;
1529           
1530           // If this is a vararg function, and there are GPRs left, also
1531           // pass the float in an int.  Otherwise, put it on the stack.
1532           if (isVarArg) {
1533             BuildMI(BB, PPC::STFS, 3).addReg(ArgReg).addSImm(ArgOffset)
1534             .addReg(PPC::R1);
1535             if (GPR_remaining > 0) {
1536               BuildMI(BB, PPC::LWZ, 2, GPR[GPR_idx])
1537               .addSImm(ArgOffset).addReg(PPC::R1);
1538               CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1539             }
1540           }
1541         } else {
1542           BuildMI(BB, PPC::STFS, 3).addReg(ArgReg).addSImm(ArgOffset)
1543           .addReg(PPC::R1);
1544         }
1545         break;
1546       case cFP64:
1547         ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1548         // Reg or stack?
1549         if (FPR_remaining > 0) {
1550           BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1551           CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1552           FPR_remaining--;
1553           FPR_idx++;
1554           // For vararg functions, must pass doubles via int regs as well
1555           if (isVarArg) {
1556             BuildMI(BB, PPC::STFD, 3).addReg(ArgReg).addSImm(ArgOffset)
1557             .addReg(PPC::R1);
1558             
1559             // Doubles can be split across reg + stack for varargs
1560             if (GPR_remaining > 0) {
1561               BuildMI(BB, PPC::LWZ, 2, GPR[GPR_idx]).addSImm(ArgOffset)
1562               .addReg(PPC::R1);
1563               CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1564             }
1565             if (GPR_remaining > 1) {
1566               BuildMI(BB, PPC::LWZ, 2, GPR[GPR_idx+1])
1567                 .addSImm(ArgOffset+4).addReg(PPC::R1);
1568               CallMI->addRegOperand(GPR[GPR_idx+1], MachineOperand::Use);
1569             }
1570           }
1571         } else {
1572           BuildMI(BB, PPC::STFD, 3).addReg(ArgReg).addSImm(ArgOffset)
1573           .addReg(PPC::R1);
1574         }
1575         // Doubles use 8 bytes, and 2 GPRs worth of param space
1576         ArgOffset += 4;
1577         GPR_remaining--;
1578         GPR_idx++;
1579         break;
1580         
1581       default: assert(0 && "Unknown class!");
1582       }
1583       ArgOffset += 4;
1584       GPR_remaining--;
1585       GPR_idx++;
1586     }
1587   } else {
1588     BuildMI(BB, PPC::ADJCALLSTACKDOWN, 1).addImm(0);
1589   }
1590
1591   BuildMI(BB, PPC::IMPLICIT_DEF, 0, PPC::LR);
1592   BB->push_back(CallMI);
1593   
1594   // These functions are automatically eliminated by the prolog/epilog pass
1595   BuildMI(BB, PPC::ADJCALLSTACKUP, 1).addImm(NumBytes);
1596
1597   // If there is a return value, scavenge the result from the location the call
1598   // leaves it in...
1599   //
1600   if (Ret.Ty != Type::VoidTy) {
1601     unsigned DestClass = getClassB(Ret.Ty);
1602     switch (DestClass) {
1603     case cByte:
1604     case cShort:
1605     case cInt:
1606       // Integral results are in r3
1607       BuildMI(BB, PPC::OR, 2, Ret.Reg).addReg(PPC::R3).addReg(PPC::R3);
1608       break;
1609     case cFP32:   // Floating-point return values live in f1
1610     case cFP64:
1611       BuildMI(BB, PPC::FMR, 1, Ret.Reg).addReg(PPC::F1);
1612       break;
1613     case cLong:   // Long values are in r3:r4
1614       BuildMI(BB, PPC::OR, 2, Ret.Reg).addReg(PPC::R3).addReg(PPC::R3);
1615       BuildMI(BB, PPC::OR, 2, Ret.Reg+1).addReg(PPC::R4).addReg(PPC::R4);
1616       break;
1617     default: assert(0 && "Unknown class!");
1618     }
1619   }
1620 }
1621
1622
1623 /// visitCallInst - Push args on stack and do a procedure call instruction.
1624 void ISel::visitCallInst(CallInst &CI) {
1625   MachineInstr *TheCall;
1626   Function *F = CI.getCalledFunction();
1627   if (F) {
1628     // Is it an intrinsic function call?
1629     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1630       visitIntrinsicCall(ID, CI);   // Special intrinsics are not handled here
1631       return;
1632     }
1633     // Emit a CALL instruction with PC-relative displacement.
1634     TheCall = BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(F, true);
1635     // Add it to the set of functions called to be used by the Printer
1636     TM.CalledFunctions.insert(F);
1637   } else {  // Emit an indirect call through the CTR
1638     unsigned Reg = getReg(CI.getCalledValue());
1639     BuildMI(BB, PPC::MTCTR, 1).addReg(Reg);
1640     TheCall = BuildMI(PPC::CALLindirect, 2).addZImm(20).addZImm(0);
1641   }
1642
1643   std::vector<ValueRecord> Args;
1644   for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1645     Args.push_back(ValueRecord(CI.getOperand(i)));
1646
1647   unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1648   bool isVarArg = F ? F->getFunctionType()->isVarArg() : true;
1649   doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args, isVarArg);
1650 }         
1651
1652
1653 /// dyncastIsNan - Return the operand of an isnan operation if this is an isnan.
1654 ///
1655 static Value *dyncastIsNan(Value *V) {
1656   if (CallInst *CI = dyn_cast<CallInst>(V))
1657     if (Function *F = CI->getCalledFunction())
1658       if (F->getIntrinsicID() == Intrinsic::isunordered)
1659         return CI->getOperand(1);
1660   return 0;
1661 }
1662
1663 /// isOnlyUsedByUnorderedComparisons - Return true if this value is only used by
1664 /// or's whos operands are all calls to the isnan predicate.
1665 static bool isOnlyUsedByUnorderedComparisons(Value *V) {
1666   assert(dyncastIsNan(V) && "The value isn't an isnan call!");
1667
1668   // Check all uses, which will be or's of isnans if this predicate is true.
1669   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1670     Instruction *I = cast<Instruction>(*UI);
1671     if (I->getOpcode() != Instruction::Or) return false;
1672     if (I->getOperand(0) != V && !dyncastIsNan(I->getOperand(0))) return false;
1673     if (I->getOperand(1) != V && !dyncastIsNan(I->getOperand(1))) return false;
1674   }
1675
1676   return true;
1677 }
1678
1679 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1680 /// function, lowering any calls to unknown intrinsic functions into the
1681 /// equivalent LLVM code.
1682 ///
1683 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1684   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1685     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1686       if (CallInst *CI = dyn_cast<CallInst>(I++))
1687         if (Function *F = CI->getCalledFunction())
1688           switch (F->getIntrinsicID()) {
1689           case Intrinsic::not_intrinsic:
1690           case Intrinsic::vastart:
1691           case Intrinsic::vacopy:
1692           case Intrinsic::vaend:
1693           case Intrinsic::returnaddress:
1694           case Intrinsic::frameaddress:
1695             // FIXME: should lower these ourselves
1696             // case Intrinsic::isunordered:
1697             // case Intrinsic::memcpy: -> doCall().  system memcpy almost
1698             // guaranteed to be faster than anything we generate ourselves
1699             // We directly implement these intrinsics
1700             break;
1701           case Intrinsic::readio: {
1702             // On PPC, memory operations are in-order.  Lower this intrinsic
1703             // into a volatile load.
1704             Instruction *Before = CI->getPrev();
1705             LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1706             CI->replaceAllUsesWith(LI);
1707             BB->getInstList().erase(CI);
1708             break;
1709           }
1710           case Intrinsic::writeio: {
1711             // On PPC, memory operations are in-order.  Lower this intrinsic
1712             // into a volatile store.
1713             Instruction *Before = CI->getPrev();
1714             StoreInst *SI = new StoreInst(CI->getOperand(1),
1715                                           CI->getOperand(2), true, CI);
1716             CI->replaceAllUsesWith(SI);
1717             BB->getInstList().erase(CI);
1718             break;
1719           }
1720           default:
1721             // All other intrinsic calls we must lower.
1722             Instruction *Before = CI->getPrev();
1723             TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1724             if (Before) {        // Move iterator to instruction after call
1725               I = Before; ++I;
1726             } else {
1727               I = BB->begin();
1728             }
1729           }
1730 }
1731
1732 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1733   unsigned TmpReg1, TmpReg2, TmpReg3;
1734   switch (ID) {
1735   case Intrinsic::vastart:
1736     // Get the address of the first vararg value...
1737     TmpReg1 = getReg(CI);
1738     addFrameReference(BuildMI(BB, PPC::ADDI, 2, TmpReg1), VarArgsFrameIndex, 
1739                       0, false);
1740     return;
1741
1742   case Intrinsic::vacopy:
1743     TmpReg1 = getReg(CI);
1744     TmpReg2 = getReg(CI.getOperand(1));
1745     BuildMI(BB, PPC::OR, 2, TmpReg1).addReg(TmpReg2).addReg(TmpReg2);
1746     return;
1747   case Intrinsic::vaend: return;
1748
1749   case Intrinsic::returnaddress:
1750     TmpReg1 = getReg(CI);
1751     if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1752       MachineFrameInfo *MFI = F->getFrameInfo();
1753       unsigned NumBytes = MFI->getStackSize();
1754       
1755       BuildMI(BB, PPC::LWZ, 2, TmpReg1).addSImm(NumBytes+8)
1756         .addReg(PPC::R1);
1757     } else {
1758       // Values other than zero are not implemented yet.
1759       BuildMI(BB, PPC::LI, 1, TmpReg1).addSImm(0);
1760     }
1761     return;
1762
1763   case Intrinsic::frameaddress:
1764     TmpReg1 = getReg(CI);
1765     if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1766       BuildMI(BB, PPC::OR, 2, TmpReg1).addReg(PPC::R1).addReg(PPC::R1);
1767     } else {
1768       // Values other than zero are not implemented yet.
1769       BuildMI(BB, PPC::LI, 1, TmpReg1).addSImm(0);
1770     }
1771     return;
1772     
1773 #if 0
1774     // This may be useful for supporting isunordered
1775   case Intrinsic::isnan:
1776     // If this is only used by 'isunordered' style comparisons, don't emit it.
1777     if (isOnlyUsedByUnorderedComparisons(&CI)) return;
1778     TmpReg1 = getReg(CI.getOperand(1));
1779     emitUCOM(BB, BB->end(), TmpReg1, TmpReg1);
1780     TmpReg2 = makeAnotherReg(Type::IntTy);
1781     BuildMI(BB, PPC::MFCR, TmpReg2);
1782     TmpReg3 = getReg(CI);
1783     BuildMI(BB, PPC::RLWINM, 4, TmpReg3).addReg(TmpReg2).addImm(4).addImm(31).addImm(31);
1784     return;
1785 #endif
1786     
1787   default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1788   }
1789 }
1790
1791 /// visitSimpleBinary - Implement simple binary operators for integral types...
1792 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1793 /// Xor.
1794 ///
1795 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1796   unsigned DestReg = getReg(B);
1797   MachineBasicBlock::iterator MI = BB->end();
1798   Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1799   unsigned Class = getClassB(B.getType());
1800
1801   emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1802 }
1803
1804 /// emitBinaryFPOperation - This method handles emission of floating point
1805 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
1806 void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
1807                                  MachineBasicBlock::iterator IP,
1808                                  Value *Op0, Value *Op1,
1809                                  unsigned OperatorClass, unsigned DestReg) {
1810
1811   static const unsigned OpcodeTab[][4] = {
1812     { PPC::FADDS, PPC::FSUBS, PPC::FMULS, PPC::FDIVS },  // Float
1813     { PPC::FADD,  PPC::FSUB,  PPC::FMUL,  PPC::FDIV },   // Double
1814   };
1815
1816   // Special case: op Reg, <const fp>
1817   if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1818     // Create a constant pool entry for this constant.
1819     MachineConstantPool *CP = F->getConstantPool();
1820     unsigned CPI = CP->getConstantPoolIndex(Op1C);
1821     const Type *Ty = Op1->getType();
1822     assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1823
1824     unsigned Opcode = OpcodeTab[1][OperatorClass];
1825     unsigned Op1Reg = getReg(Op1C, BB, IP);
1826     unsigned Op0Reg = getReg(Op0, BB, IP);
1827     if (Ty == Type::DoubleTy) {
1828       BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
1829     } else {
1830       unsigned TmpReg = makeAnotherReg(Type::DoubleTy);
1831       BuildMI(*BB, IP, Opcode, 2, TmpReg).addReg(Op0Reg).addReg(Op1Reg);
1832       BuildMI(*BB, IP, PPC::FRSP, 1, DestReg).addReg(TmpReg);
1833     }
1834     return;
1835   }
1836   
1837   // Special case: R1 = op <const fp>, R2
1838   if (ConstantFP *Op0C = dyn_cast<ConstantFP>(Op0))
1839     if (Op0C->isExactlyValue(-0.0) && OperatorClass == 1) {
1840       // -0.0 - X === -X
1841       unsigned op1Reg = getReg(Op1, BB, IP);
1842       BuildMI(*BB, IP, PPC::FNEG, 1, DestReg).addReg(op1Reg);
1843       return;
1844     } else {
1845       // Create a constant pool entry for this constant.
1846       MachineConstantPool *CP = F->getConstantPool();
1847       unsigned CPI = CP->getConstantPoolIndex(Op0C);
1848       const Type *Ty = Op0C->getType();
1849       assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1850
1851       unsigned Opcode = OpcodeTab[1][OperatorClass];
1852       unsigned Op0Reg = getReg(Op0C, BB, IP);
1853       unsigned Op1Reg = getReg(Op1, BB, IP);
1854       if (Ty == Type::DoubleTy) {
1855         BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
1856       } else {
1857         unsigned TmpReg = makeAnotherReg(Type::DoubleTy);
1858         BuildMI(*BB, IP, Opcode, 2, TmpReg).addReg(Op0Reg).addReg(Op1Reg);
1859         BuildMI(*BB, IP, PPC::FRSP, 1, DestReg).addReg(TmpReg);
1860       }
1861       return;
1862     }
1863
1864   unsigned Opcode = OpcodeTab[Op0->getType() != Type::FloatTy][OperatorClass];
1865   //unsigned Opcode = OpcodeTab[OperatorClass];
1866   unsigned Op0r = getReg(Op0, BB, IP);
1867   unsigned Op1r = getReg(Op1, BB, IP);
1868   BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1869 }
1870
1871 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1872 /// types...  OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1873 /// Or, 4 for Xor.
1874 ///
1875 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1876 /// and constant expression support.
1877 ///
1878 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1879                                      MachineBasicBlock::iterator IP,
1880                                      Value *Op0, Value *Op1,
1881                                      unsigned OperatorClass, unsigned DestReg) {
1882   unsigned Class = getClassB(Op0->getType());
1883
1884   // Arithmetic and Bitwise operators
1885   static const unsigned OpcodeTab[] = {
1886     PPC::ADD, PPC::SUB, PPC::AND, PPC::OR, PPC::XOR
1887   };
1888   static const unsigned ImmOpcodeTab[] = {
1889     PPC::ADDI, PPC::SUBI, PPC::ANDIo, PPC::ORI, PPC::XORI
1890   };
1891   static const unsigned RImmOpcodeTab[] = {
1892     PPC::ADDI, PPC::SUBFIC, PPC::ANDIo, PPC::ORI, PPC::XORI
1893   };
1894
1895   // Otherwise, code generate the full operation with a constant.
1896   static const unsigned BottomTab[] = {
1897     PPC::ADDC, PPC::SUBC, PPC::AND, PPC::OR, PPC::XOR
1898   };
1899   static const unsigned TopTab[] = {
1900     PPC::ADDE, PPC::SUBFE, PPC::AND, PPC::OR, PPC::XOR
1901   };
1902   
1903   if (Class == cFP32 || Class == cFP64) {
1904     assert(OperatorClass < 2 && "No logical ops for FP!");
1905     emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
1906     return;
1907   }
1908
1909   if (Op0->getType() == Type::BoolTy) {
1910     if (OperatorClass == 3)
1911       // If this is an or of two isnan's, emit an FP comparison directly instead
1912       // of or'ing two isnan's together.
1913       if (Value *LHS = dyncastIsNan(Op0))
1914         if (Value *RHS = dyncastIsNan(Op1)) {
1915           unsigned Op0Reg = getReg(RHS, MBB, IP), Op1Reg = getReg(LHS, MBB, IP);
1916           unsigned TmpReg = makeAnotherReg(Type::IntTy);
1917           emitUCOM(MBB, IP, Op0Reg, Op1Reg);
1918           BuildMI(*MBB, IP, PPC::MFCR, TmpReg);
1919           BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(TmpReg).addImm(4)
1920             .addImm(31).addImm(31);
1921           return;
1922         }
1923   }
1924
1925   // Special case: op <const int>, Reg
1926   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
1927     // sub 0, X -> subfic
1928     if (OperatorClass == 1 && canUseAsImmediateForOpcode(CI, 0)) {
1929       unsigned Op1r = getReg(Op1, MBB, IP);
1930       int imm = CI->getRawValue() & 0xFFFF;
1931
1932       if (Class == cLong) {
1933         BuildMI(*MBB, IP, PPC::SUBFIC, 2, DestReg+1).addReg(Op1r+1)
1934           .addSImm(imm);
1935         BuildMI(*MBB, IP, PPC::SUBFZE, 1, DestReg).addReg(Op1r);
1936       } else {
1937         BuildMI(*MBB, IP, PPC::SUBFIC, 2, DestReg).addReg(Op1r).addSImm(imm);
1938       }
1939       return;
1940     }
1941     
1942     // If it is easy to do, swap the operands and emit an immediate op
1943     if (Class != cLong && OperatorClass != 1 && 
1944         canUseAsImmediateForOpcode(CI, OperatorClass)) {
1945       unsigned Op1r = getReg(Op1, MBB, IP);
1946       int imm = CI->getRawValue() & 0xFFFF;
1947     
1948       if (OperatorClass < 2)
1949         BuildMI(*MBB, IP, RImmOpcodeTab[OperatorClass], 2, DestReg).addReg(Op1r)
1950           .addSImm(imm);
1951       else
1952         BuildMI(*MBB, IP, RImmOpcodeTab[OperatorClass], 2, DestReg).addReg(Op1r)
1953           .addZImm(imm);
1954       return;
1955     }
1956   }
1957
1958   // Special case: op Reg, <const int>
1959   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1960     unsigned Op0r = getReg(Op0, MBB, IP);
1961
1962     // xor X, -1 -> not X
1963     if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1964       BuildMI(*MBB, IP, PPC::NOR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1965       if (Class == cLong)  // Invert the low part too
1966         BuildMI(*MBB, IP, PPC::NOR, 2, DestReg+1).addReg(Op0r+1)
1967           .addReg(Op0r+1);
1968       return;
1969     }
1970     
1971     if (Class != cLong) {
1972       if (canUseAsImmediateForOpcode(Op1C, OperatorClass)) {
1973         int immediate = Op1C->getRawValue() & 0xFFFF;
1974         
1975         if (OperatorClass < 2)
1976           BuildMI(*MBB, IP, ImmOpcodeTab[OperatorClass], 2,DestReg).addReg(Op0r)
1977             .addSImm(immediate);
1978         else
1979           BuildMI(*MBB, IP, ImmOpcodeTab[OperatorClass], 2,DestReg).addReg(Op0r)
1980             .addZImm(immediate);
1981       } else {
1982         unsigned Op1r = getReg(Op1, MBB, IP);
1983         BuildMI(*MBB, IP, OpcodeTab[OperatorClass], 2, DestReg).addReg(Op0r)
1984           .addReg(Op1r);
1985       }
1986       return;
1987     }
1988
1989     unsigned Op1r = getReg(Op1, MBB, IP);
1990
1991     BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1992       .addReg(Op1r+1);
1993     BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg).addReg(Op0r)
1994       .addReg(Op1r);
1995     return;
1996   }
1997   
1998   // We couldn't generate an immediate variant of the op, load both halves into
1999   // registers and emit the appropriate opcode.
2000   unsigned Op0r = getReg(Op0, MBB, IP);
2001   unsigned Op1r = getReg(Op1, MBB, IP);
2002
2003   if (Class != cLong) {
2004     unsigned Opcode = OpcodeTab[OperatorClass];
2005     BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2006   } else {
2007     BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
2008       .addReg(Op1r+1);
2009     BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg).addReg(Op0r)
2010       .addReg(Op1r);
2011   }
2012   return;
2013 }
2014
2015 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
2016 // returns zero when the input is not exactly a power of two.
2017 static unsigned ExactLog2(unsigned Val) {
2018   if (Val == 0 || (Val & (Val-1))) return 0;
2019   unsigned Count = 0;
2020   while (Val != 1) {
2021     Val >>= 1;
2022     ++Count;
2023   }
2024   return Count;
2025 }
2026
2027 /// doMultiply - Emit appropriate instructions to multiply together the
2028 /// Values Op0 and Op1, and put the result in DestReg.
2029 ///
2030 void ISel::doMultiply(MachineBasicBlock *MBB,
2031                       MachineBasicBlock::iterator IP,
2032                       unsigned DestReg, Value *Op0, Value *Op1) {
2033   unsigned Class0 = getClass(Op0->getType());
2034   unsigned Class1 = getClass(Op1->getType());
2035   
2036   unsigned Op0r = getReg(Op0, MBB, IP);
2037   unsigned Op1r = getReg(Op1, MBB, IP);
2038   
2039   // 64 x 64 -> 64
2040   if (Class0 == cLong && Class1 == cLong) {
2041     unsigned Tmp1 = makeAnotherReg(Type::IntTy);
2042     unsigned Tmp2 = makeAnotherReg(Type::IntTy);
2043     unsigned Tmp3 = makeAnotherReg(Type::IntTy);
2044     unsigned Tmp4 = makeAnotherReg(Type::IntTy);
2045     BuildMI(*MBB, IP, PPC::MULHWU, 2, Tmp1).addReg(Op0r+1).addReg(Op1r+1);
2046     BuildMI(*MBB, IP, PPC::MULLW, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
2047     BuildMI(*MBB, IP, PPC::MULLW, 2, Tmp2).addReg(Op0r+1).addReg(Op1r);
2048     BuildMI(*MBB, IP, PPC::ADD, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
2049     BuildMI(*MBB, IP, PPC::MULLW, 2, Tmp4).addReg(Op0r).addReg(Op1r+1);
2050     BuildMI(*MBB, IP, PPC::ADD, 2, DestReg).addReg(Tmp3).addReg(Tmp4);
2051     return;
2052   }
2053   
2054   // 64 x 32 or less, promote 32 to 64 and do a 64 x 64
2055   if (Class0 == cLong && Class1 <= cInt) {
2056     unsigned Tmp0 = makeAnotherReg(Type::IntTy);
2057     unsigned Tmp1 = makeAnotherReg(Type::IntTy);
2058     unsigned Tmp2 = makeAnotherReg(Type::IntTy);
2059     unsigned Tmp3 = makeAnotherReg(Type::IntTy);
2060     unsigned Tmp4 = makeAnotherReg(Type::IntTy);
2061     if (Op1->getType()->isSigned())
2062       BuildMI(*MBB, IP, PPC::SRAWI, 2, Tmp0).addReg(Op1r).addImm(31);
2063     else
2064       BuildMI(*MBB, IP, PPC::LI, 2, Tmp0).addSImm(0);
2065     BuildMI(*MBB, IP, PPC::MULHWU, 2, Tmp1).addReg(Op0r+1).addReg(Op1r);
2066     BuildMI(*MBB, IP, PPC::MULLW, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r);
2067     BuildMI(*MBB, IP, PPC::MULLW, 2, Tmp2).addReg(Op0r+1).addReg(Tmp0);
2068     BuildMI(*MBB, IP, PPC::ADD, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
2069     BuildMI(*MBB, IP, PPC::MULLW, 2, Tmp4).addReg(Op0r).addReg(Op1r);
2070     BuildMI(*MBB, IP, PPC::ADD, 2, DestReg).addReg(Tmp3).addReg(Tmp4);
2071     return;
2072   }
2073   
2074   // 32 x 32 -> 32
2075   if (Class0 <= cInt && Class1 <= cInt) {
2076     BuildMI(*MBB, IP, PPC::MULLW, 2, DestReg).addReg(Op0r).addReg(Op1r);
2077     return;
2078   }
2079   
2080   assert(0 && "doMultiply cannot operate on unknown type!");
2081 }
2082
2083 /// doMultiplyConst - This method will multiply the value in Op0 by the
2084 /// value of the ContantInt *CI
2085 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
2086                            MachineBasicBlock::iterator IP,
2087                            unsigned DestReg, Value *Op0, ConstantInt *CI) {
2088   unsigned Class = getClass(Op0->getType());
2089
2090   // Mul op0, 0 ==> 0
2091   if (CI->isNullValue()) {
2092     BuildMI(*MBB, IP, PPC::LI, 1, DestReg).addSImm(0);
2093     if (Class == cLong)
2094       BuildMI(*MBB, IP, PPC::LI, 1, DestReg+1).addSImm(0);
2095     return;
2096   }
2097   
2098   // Mul op0, 1 ==> op0
2099   if (CI->equalsInt(1)) {
2100     unsigned Op0r = getReg(Op0, MBB, IP);
2101     BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(Op0r).addReg(Op0r);
2102     if (Class == cLong)
2103       BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(Op0r+1).addReg(Op0r+1);
2104     return;
2105   }
2106
2107   // If the element size is exactly a power of 2, use a shift to get it.
2108   if (unsigned Shift = ExactLog2(CI->getRawValue())) {
2109     ConstantUInt *ShiftCI = ConstantUInt::get(Type::UByteTy, Shift);
2110     emitShiftOperation(MBB, IP, Op0, ShiftCI, true, Op0->getType(), DestReg);
2111     return;
2112   }
2113   
2114   // If 32 bits or less and immediate is in right range, emit mul by immediate
2115   if (Class == cByte || Class == cShort || Class == cInt) {
2116     if (canUseAsImmediateForOpcode(CI, 0)) {
2117       unsigned Op0r = getReg(Op0, MBB, IP);
2118       unsigned imm = CI->getRawValue() & 0xFFFF;
2119       BuildMI(*MBB, IP, PPC::MULLI, 2, DestReg).addReg(Op0r).addSImm(imm);
2120       return;
2121     }
2122   }
2123   
2124   doMultiply(MBB, IP, DestReg, Op0, CI);
2125 }
2126
2127 void ISel::visitMul(BinaryOperator &I) {
2128   unsigned ResultReg = getReg(I);
2129
2130   Value *Op0 = I.getOperand(0);
2131   Value *Op1 = I.getOperand(1);
2132
2133   MachineBasicBlock::iterator IP = BB->end();
2134   emitMultiply(BB, IP, Op0, Op1, ResultReg);
2135 }
2136
2137 void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2138                         Value *Op0, Value *Op1, unsigned DestReg) {
2139   TypeClass Class = getClass(Op0->getType());
2140
2141   switch (Class) {
2142   case cByte:
2143   case cShort:
2144   case cInt:
2145   case cLong:
2146     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2147       doMultiplyConst(MBB, IP, DestReg, Op0, CI);
2148     } else {
2149       doMultiply(MBB, IP, DestReg, Op0, Op1);
2150     }
2151     return;
2152   case cFP32:
2153   case cFP64:
2154     emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2155     return;
2156     break;
2157   }
2158 }
2159
2160
2161 /// visitDivRem - Handle division and remainder instructions... these
2162 /// instruction both require the same instructions to be generated, they just
2163 /// select the result from a different register.  Note that both of these
2164 /// instructions work differently for signed and unsigned operands.
2165 ///
2166 void ISel::visitDivRem(BinaryOperator &I) {
2167   unsigned ResultReg = getReg(I);
2168   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2169
2170   MachineBasicBlock::iterator IP = BB->end();
2171   emitDivRemOperation(BB, IP, Op0, Op1, I.getOpcode() == Instruction::Div,
2172                       ResultReg);
2173 }
2174
2175 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
2176                                MachineBasicBlock::iterator IP,
2177                                Value *Op0, Value *Op1, bool isDiv,
2178                                unsigned ResultReg) {
2179   const Type *Ty = Op0->getType();
2180   unsigned Class = getClass(Ty);
2181   switch (Class) {
2182   case cFP32:
2183     if (isDiv) {
2184       // Floating point divide...
2185       emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2186       return;
2187     } else {
2188       // Floating point remainder via fmodf(float x, float y);
2189       unsigned Op0Reg = getReg(Op0, BB, IP);
2190       unsigned Op1Reg = getReg(Op1, BB, IP);
2191       MachineInstr *TheCall =
2192         BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(fmodfFn, true);
2193       std::vector<ValueRecord> Args;
2194       Args.push_back(ValueRecord(Op0Reg, Type::FloatTy));
2195       Args.push_back(ValueRecord(Op1Reg, Type::FloatTy));
2196       doCall(ValueRecord(ResultReg, Type::FloatTy), TheCall, Args, false);
2197       TM.CalledFunctions.insert(fmodfFn);
2198     }
2199     return;
2200   case cFP64:
2201     if (isDiv) {
2202       // Floating point divide...
2203       emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2204       return;
2205     } else {               
2206       // Floating point remainder via fmod(double x, double y);
2207       unsigned Op0Reg = getReg(Op0, BB, IP);
2208       unsigned Op1Reg = getReg(Op1, BB, IP);
2209       MachineInstr *TheCall =
2210         BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(fmodFn, true);
2211       std::vector<ValueRecord> Args;
2212       Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2213       Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2214       doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args, false);
2215       TM.CalledFunctions.insert(fmodFn);
2216     }
2217     return;
2218   case cLong: {
2219     static Function* const Funcs[] =
2220       { __moddi3Fn, __divdi3Fn, __umoddi3Fn, __udivdi3Fn };
2221     unsigned Op0Reg = getReg(Op0, BB, IP);
2222     unsigned Op1Reg = getReg(Op1, BB, IP);
2223     unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2224     MachineInstr *TheCall =
2225       BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(Funcs[NameIdx], true);
2226
2227     std::vector<ValueRecord> Args;
2228     Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2229     Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2230     doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args, false);
2231     TM.CalledFunctions.insert(Funcs[NameIdx]);
2232     return;
2233   }
2234   case cByte: case cShort: case cInt:
2235     break;          // Small integrals, handled below...
2236   default: assert(0 && "Unknown class!");
2237   }
2238
2239   // Special case signed division by power of 2.
2240   if (isDiv)
2241     if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
2242       assert(Class != cLong && "This doesn't handle 64-bit divides!");
2243       int V = CI->getValue();
2244
2245       if (V == 1) {       // X /s 1 => X
2246         unsigned Op0Reg = getReg(Op0, BB, IP);
2247         BuildMI(*BB, IP, PPC::OR, 2, ResultReg).addReg(Op0Reg).addReg(Op0Reg);
2248         return;
2249       }
2250
2251       if (V == -1) {      // X /s -1 => -X
2252         unsigned Op0Reg = getReg(Op0, BB, IP);
2253         BuildMI(*BB, IP, PPC::NEG, 1, ResultReg).addReg(Op0Reg);
2254         return;
2255       }
2256
2257       unsigned log2V = ExactLog2(V);
2258       if (log2V != 0 && Ty->isSigned()) {
2259         unsigned Op0Reg = getReg(Op0, BB, IP);
2260         unsigned TmpReg = makeAnotherReg(Op0->getType());
2261         
2262         BuildMI(*BB, IP, PPC::SRAWI, 2, TmpReg).addReg(Op0Reg).addImm(log2V);
2263         BuildMI(*BB, IP, PPC::ADDZE, 1, ResultReg).addReg(TmpReg);
2264         return;
2265       }
2266     }
2267
2268   unsigned Op0Reg = getReg(Op0, BB, IP);
2269   unsigned Op1Reg = getReg(Op1, BB, IP);
2270   unsigned Opcode = Ty->isSigned() ? PPC::DIVW : PPC::DIVWU;
2271   
2272   if (isDiv) {
2273     BuildMI(*BB, IP, Opcode, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2274   } else { // Remainder
2275     unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2276     unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2277     
2278     BuildMI(*BB, IP, Opcode, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2279     BuildMI(*BB, IP, PPC::MULLW, 2, TmpReg2).addReg(TmpReg1).addReg(Op1Reg);
2280     BuildMI(*BB, IP, PPC::SUBF, 2, ResultReg).addReg(TmpReg2).addReg(Op0Reg);
2281   }
2282 }
2283
2284
2285 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2286 /// for constant immediate shift values, and for constant immediate
2287 /// shift values equal to 1. Even the general case is sort of special,
2288 /// because the shift amount has to be in CL, not just any old register.
2289 ///
2290 void ISel::visitShiftInst(ShiftInst &I) {
2291   MachineBasicBlock::iterator IP = BB->end();
2292   emitShiftOperation(BB, IP, I.getOperand(0), I.getOperand(1),
2293                      I.getOpcode() == Instruction::Shl, I.getType(),
2294                      getReg(I));
2295 }
2296
2297 /// emitShiftOperation - Common code shared between visitShiftInst and
2298 /// constant expression support.
2299 ///
2300 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2301                               MachineBasicBlock::iterator IP,
2302                               Value *Op, Value *ShiftAmount, bool isLeftShift,
2303                               const Type *ResultTy, unsigned DestReg) {
2304   unsigned SrcReg = getReg (Op, MBB, IP);
2305   bool isSigned = ResultTy->isSigned ();
2306   unsigned Class = getClass (ResultTy);
2307   
2308   // Longs, as usual, are handled specially...
2309   if (Class == cLong) {
2310     // If we have a constant shift, we can generate much more efficient code
2311     // than otherwise...
2312     //
2313     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2314       unsigned Amount = CUI->getValue();
2315       if (Amount < 32) {
2316         if (isLeftShift) {
2317           // FIXME: RLWIMI is a use-and-def of DestReg+1, but that violates SSA
2318           BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2319             .addImm(Amount).addImm(0).addImm(31-Amount);
2320           BuildMI(*MBB, IP, PPC::RLWIMI, 5).addReg(DestReg).addReg(SrcReg+1)
2321             .addImm(Amount).addImm(32-Amount).addImm(31);
2322           BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2323             .addImm(Amount).addImm(0).addImm(31-Amount);
2324         } else {
2325           // FIXME: RLWIMI is a use-and-def of DestReg, but that violates SSA
2326           BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2327             .addImm(32-Amount).addImm(Amount).addImm(31);
2328           BuildMI(*MBB, IP, PPC::RLWIMI, 5).addReg(DestReg+1).addReg(SrcReg)
2329             .addImm(32-Amount).addImm(0).addImm(Amount-1);
2330           BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2331             .addImm(32-Amount).addImm(Amount).addImm(31);
2332         }
2333       } else {                 // Shifting more than 32 bits
2334         Amount -= 32;
2335         if (isLeftShift) {
2336           if (Amount != 0) {
2337             BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg+1)
2338               .addImm(Amount).addImm(0).addImm(31-Amount);
2339           } else {
2340             BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg+1)
2341               .addReg(SrcReg+1);
2342           }
2343           BuildMI(*MBB, IP, PPC::LI, 1, DestReg+1).addSImm(0);
2344         } else {
2345           if (Amount != 0) {
2346             if (isSigned)
2347               BuildMI(*MBB, IP, PPC::SRAWI, 2, DestReg+1).addReg(SrcReg)
2348                 .addImm(Amount);
2349             else
2350               BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg+1).addReg(SrcReg)
2351                 .addImm(32-Amount).addImm(Amount).addImm(31);
2352           } else {
2353             BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
2354               .addReg(SrcReg);
2355           }
2356           BuildMI(*MBB, IP,PPC::LI, 1, DestReg).addSImm(0);
2357         }
2358       }
2359     } else {
2360       unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
2361       unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2362       unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2363       unsigned TmpReg4 = makeAnotherReg(Type::IntTy);
2364       unsigned TmpReg5 = makeAnotherReg(Type::IntTy);
2365       unsigned TmpReg6 = makeAnotherReg(Type::IntTy);
2366       unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2367       
2368       if (isLeftShift) {
2369         BuildMI(*MBB, IP, PPC::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2370           .addSImm(32);
2371         BuildMI(*MBB, IP, PPC::SLW, 2, TmpReg2).addReg(SrcReg)
2372           .addReg(ShiftAmountReg);
2373         BuildMI(*MBB, IP, PPC::SRW, 2, TmpReg3).addReg(SrcReg+1)
2374           .addReg(TmpReg1);
2375         BuildMI(*MBB, IP, PPC::OR, 2,TmpReg4).addReg(TmpReg2).addReg(TmpReg3);
2376         BuildMI(*MBB, IP, PPC::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2377           .addSImm(-32);
2378         BuildMI(*MBB, IP, PPC::SLW, 2, TmpReg6).addReg(SrcReg+1)
2379           .addReg(TmpReg5);
2380         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(TmpReg4)
2381           .addReg(TmpReg6);
2382         BuildMI(*MBB, IP, PPC::SLW, 2, DestReg+1).addReg(SrcReg+1)
2383           .addReg(ShiftAmountReg);
2384       } else {
2385         if (isSigned) {
2386           // FIXME: Unimplemented
2387           // Page C-3 of the PowerPC 32bit Programming Environments Manual
2388           std::cerr << "ERROR: Unimplemented: signed right shift of long\n";
2389           abort();
2390         } else {
2391           BuildMI(*MBB, IP, PPC::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2392             .addSImm(32);
2393           BuildMI(*MBB, IP, PPC::SRW, 2, TmpReg2).addReg(SrcReg+1)
2394             .addReg(ShiftAmountReg);
2395           BuildMI(*MBB, IP, PPC::SLW, 2, TmpReg3).addReg(SrcReg)
2396             .addReg(TmpReg1);
2397           BuildMI(*MBB, IP, PPC::OR, 2, TmpReg4).addReg(TmpReg2)
2398             .addReg(TmpReg3);
2399           BuildMI(*MBB, IP, PPC::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2400             .addSImm(-32);
2401           BuildMI(*MBB, IP, PPC::SRW, 2, TmpReg6).addReg(SrcReg)
2402             .addReg(TmpReg5);
2403           BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(TmpReg4)
2404             .addReg(TmpReg6);
2405           BuildMI(*MBB, IP, PPC::SRW, 2, DestReg).addReg(SrcReg)
2406             .addReg(ShiftAmountReg);
2407         }
2408       }
2409     }
2410     return;
2411   }
2412
2413   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2414     // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2415     assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2416     unsigned Amount = CUI->getValue();
2417
2418     if (isLeftShift) {
2419       BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2420         .addImm(Amount).addImm(0).addImm(31-Amount);
2421     } else {
2422       if (isSigned) {
2423         BuildMI(*MBB, IP, PPC::SRAWI,2,DestReg).addReg(SrcReg).addImm(Amount);
2424       } else {
2425         BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2426           .addImm(32-Amount).addImm(Amount).addImm(31);
2427       }
2428     }
2429   } else {                  // The shift amount is non-constant.
2430     unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2431
2432     if (isLeftShift) {
2433       BuildMI(*MBB, IP, PPC::SLW, 2, DestReg).addReg(SrcReg)
2434         .addReg(ShiftAmountReg);
2435     } else {
2436       BuildMI(*MBB, IP, isSigned ? PPC::SRAW : PPC::SRW, 2, DestReg)
2437         .addReg(SrcReg).addReg(ShiftAmountReg);
2438     }
2439   }
2440 }
2441
2442
2443 /// visitLoadInst - Implement LLVM load instructions.  Pretty straightforward
2444 /// mapping of LLVM classes to PPC load instructions, with the exception of
2445 /// signed byte loads, which need a sign extension following them.
2446 ///
2447 void ISel::visitLoadInst(LoadInst &I) {
2448   // Immediate opcodes, for reg+imm addressing
2449   static const unsigned ImmOpcodes[] = { 
2450     PPC::LBZ, PPC::LHZ, PPC::LWZ, 
2451     PPC::LFS, PPC::LFD, PPC::LWZ
2452   };
2453   // Indexed opcodes, for reg+reg addressing
2454   static const unsigned IdxOpcodes[] = {
2455     PPC::LBZX, PPC::LHZX, PPC::LWZX,
2456     PPC::LFSX, PPC::LFDX, PPC::LWZX
2457   };
2458
2459   unsigned Class     = getClassB(I.getType());
2460   unsigned ImmOpcode = ImmOpcodes[Class];
2461   unsigned IdxOpcode = IdxOpcodes[Class];
2462   unsigned DestReg   = getReg(I);
2463   Value *SourceAddr  = I.getOperand(0);
2464   
2465   if (Class == cShort && I.getType()->isSigned()) ImmOpcode = PPC::LHA;
2466   if (Class == cShort && I.getType()->isSigned()) IdxOpcode = PPC::LHAX;
2467
2468   if (AllocaInst *AI = dyn_castFixedAlloca(SourceAddr)) {
2469     unsigned FI = getFixedSizedAllocaFI(AI);
2470     if (Class == cLong) {
2471       addFrameReference(BuildMI(BB, ImmOpcode, 2, DestReg), FI);
2472       addFrameReference(BuildMI(BB, ImmOpcode, 2, DestReg+1), FI, 4);
2473     } else if (Class == cByte && I.getType()->isSigned()) {
2474       unsigned TmpReg = makeAnotherReg(I.getType());
2475       addFrameReference(BuildMI(BB, ImmOpcode, 2, TmpReg), FI);
2476       BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2477     } else {
2478       addFrameReference(BuildMI(BB, ImmOpcode, 2, DestReg), FI);
2479     }
2480     return;
2481   }
2482   
2483   // If this load is the only use of the GEP instruction that is its address,
2484   // then we can fold the GEP directly into the load instruction.
2485   // emitGEPOperation with a second to last arg of 'true' will place the
2486   // base register for the GEP into baseReg, and the constant offset from that
2487   // into offset.  If the offset fits in 16 bits, we can emit a reg+imm store
2488   // otherwise, we copy the offset into another reg, and use reg+reg addressing.
2489   if (GetElementPtrInst *GEPI = canFoldGEPIntoLoadOrStore(SourceAddr)) {
2490     unsigned baseReg = getReg(GEPI);
2491     unsigned pendingAdd;
2492     ConstantSInt *offset;
2493     
2494     emitGEPOperation(BB, BB->end(), GEPI->getOperand(0), GEPI->op_begin()+1, 
2495                      GEPI->op_end(), baseReg, true, &offset, &pendingAdd);
2496
2497     if (pendingAdd == 0 && Class != cLong && 
2498         canUseAsImmediateForOpcode(offset, 0)) {
2499       if (Class == cByte && I.getType()->isSigned()) {
2500         unsigned TmpReg = makeAnotherReg(I.getType());
2501         BuildMI(BB, ImmOpcode, 2, TmpReg).addSImm(offset->getValue())
2502           .addReg(baseReg);
2503         BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2504       } else {
2505         BuildMI(BB, ImmOpcode, 2, DestReg).addSImm(offset->getValue())
2506           .addReg(baseReg);
2507       }
2508       return;
2509     }
2510     
2511     unsigned indexReg = (pendingAdd != 0) ? pendingAdd : getReg(offset);
2512
2513     if (Class == cLong) {
2514       unsigned indexPlus4 = makeAnotherReg(Type::IntTy);
2515       BuildMI(BB, PPC::ADDI, 2, indexPlus4).addReg(indexReg).addSImm(4);
2516       BuildMI(BB, IdxOpcode, 2, DestReg).addReg(indexReg).addReg(baseReg);
2517       BuildMI(BB, IdxOpcode, 2, DestReg+1).addReg(indexPlus4).addReg(baseReg);
2518     } else if (Class == cByte && I.getType()->isSigned()) {
2519       unsigned TmpReg = makeAnotherReg(I.getType());
2520       BuildMI(BB, IdxOpcode, 2, TmpReg).addReg(indexReg).addReg(baseReg);
2521       BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2522     } else {
2523       BuildMI(BB, IdxOpcode, 2, DestReg).addReg(indexReg).addReg(baseReg);
2524     }
2525     return;
2526   }
2527   
2528   // The fallback case, where the load was from a source that could not be
2529   // folded into the load instruction. 
2530   unsigned SrcAddrReg = getReg(SourceAddr);
2531     
2532   if (Class == cLong) {
2533     BuildMI(BB, ImmOpcode, 2, DestReg).addSImm(0).addReg(SrcAddrReg);
2534     BuildMI(BB, ImmOpcode, 2, DestReg+1).addSImm(4).addReg(SrcAddrReg);
2535   } else if (Class == cByte && I.getType()->isSigned()) {
2536     unsigned TmpReg = makeAnotherReg(I.getType());
2537     BuildMI(BB, ImmOpcode, 2, TmpReg).addSImm(0).addReg(SrcAddrReg);
2538     BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2539   } else {
2540     BuildMI(BB, ImmOpcode, 2, DestReg).addSImm(0).addReg(SrcAddrReg);
2541   }
2542 }
2543
2544 /// visitStoreInst - Implement LLVM store instructions
2545 ///
2546 void ISel::visitStoreInst(StoreInst &I) {
2547   // Immediate opcodes, for reg+imm addressing
2548   static const unsigned ImmOpcodes[] = {
2549     PPC::STB, PPC::STH, PPC::STW, 
2550     PPC::STFS, PPC::STFD, PPC::STW
2551   };
2552   // Indexed opcodes, for reg+reg addressing
2553   static const unsigned IdxOpcodes[] = {
2554     PPC::STBX, PPC::STHX, PPC::STWX, 
2555     PPC::STFSX, PPC::STFDX, PPC::STWX
2556   };
2557   
2558   Value *SourceAddr  = I.getOperand(1);
2559   const Type *ValTy  = I.getOperand(0)->getType();
2560   unsigned Class     = getClassB(ValTy);
2561   unsigned ImmOpcode = ImmOpcodes[Class];
2562   unsigned IdxOpcode = IdxOpcodes[Class];
2563   unsigned ValReg    = getReg(I.getOperand(0));
2564
2565   // If this store is the only use of the GEP instruction that is its address,
2566   // then we can fold the GEP directly into the store instruction.
2567   // emitGEPOperation with a second to last arg of 'true' will place the
2568   // base register for the GEP into baseReg, and the constant offset from that
2569   // into offset.  If the offset fits in 16 bits, we can emit a reg+imm store
2570   // otherwise, we copy the offset into another reg, and use reg+reg addressing.
2571   if (GetElementPtrInst *GEPI = canFoldGEPIntoLoadOrStore(SourceAddr)) {
2572     unsigned baseReg = getReg(GEPI);
2573     unsigned pendingAdd;
2574     ConstantSInt *offset;
2575     
2576     emitGEPOperation(BB, BB->end(), GEPI->getOperand(0), GEPI->op_begin()+1, 
2577                      GEPI->op_end(), baseReg, true, &offset, &pendingAdd);
2578
2579     if (0 == pendingAdd && Class != cLong && 
2580         canUseAsImmediateForOpcode(offset, 0)) {
2581       BuildMI(BB, ImmOpcode, 3).addReg(ValReg).addSImm(offset->getValue())
2582         .addReg(baseReg);
2583       return;
2584     }
2585     
2586     unsigned indexReg = (pendingAdd != 0) ? pendingAdd : getReg(offset);
2587
2588     if (Class == cLong) {
2589       unsigned indexPlus4 = makeAnotherReg(Type::IntTy);
2590       BuildMI(BB, PPC::ADDI, 2, indexPlus4).addReg(indexReg).addSImm(4);
2591       BuildMI(BB, IdxOpcode, 3).addReg(ValReg).addReg(indexReg).addReg(baseReg);
2592       BuildMI(BB, IdxOpcode, 3).addReg(ValReg+1).addReg(indexPlus4)
2593         .addReg(baseReg);
2594       return;
2595     }
2596     BuildMI(BB, IdxOpcode, 3).addReg(ValReg).addReg(indexReg).addReg(baseReg);
2597     return;
2598   }
2599   
2600   // If the store address wasn't the only use of a GEP, we fall back to the
2601   // standard path: store the ValReg at the value in AddressReg.
2602   unsigned AddressReg  = getReg(I.getOperand(1));
2603   if (Class == cLong) {
2604     BuildMI(BB, ImmOpcode, 3).addReg(ValReg).addSImm(0).addReg(AddressReg);
2605     BuildMI(BB, ImmOpcode, 3).addReg(ValReg+1).addSImm(4).addReg(AddressReg);
2606     return;
2607   }
2608   BuildMI(BB, ImmOpcode, 3).addReg(ValReg).addSImm(0).addReg(AddressReg);
2609 }
2610
2611
2612 /// visitCastInst - Here we have various kinds of copying with or without sign
2613 /// extension going on.
2614 ///
2615 void ISel::visitCastInst(CastInst &CI) {
2616   Value *Op = CI.getOperand(0);
2617
2618   unsigned SrcClass = getClassB(Op->getType());
2619   unsigned DestClass = getClassB(CI.getType());
2620
2621   // If this is a cast from a 32-bit integer to a Long type, and the only uses
2622   // of the case are GEP instructions, then the cast does not need to be
2623   // generated explicitly, it will be folded into the GEP.
2624   if (DestClass == cLong && SrcClass == cInt) {
2625     bool AllUsesAreGEPs = true;
2626     for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2627       if (!isa<GetElementPtrInst>(*I)) {
2628         AllUsesAreGEPs = false;
2629         break;
2630       }        
2631
2632     // No need to codegen this cast if all users are getelementptr instrs...
2633     if (AllUsesAreGEPs) return;
2634   }
2635
2636   unsigned DestReg = getReg(CI);
2637   MachineBasicBlock::iterator MI = BB->end();
2638   emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2639 }
2640
2641 /// emitCastOperation - Common code shared between visitCastInst and constant
2642 /// expression cast support.
2643 ///
2644 void ISel::emitCastOperation(MachineBasicBlock *MBB,
2645                              MachineBasicBlock::iterator IP,
2646                              Value *Src, const Type *DestTy,
2647                              unsigned DestReg) {
2648   const Type *SrcTy = Src->getType();
2649   unsigned SrcClass = getClassB(SrcTy);
2650   unsigned DestClass = getClassB(DestTy);
2651   unsigned SrcReg = getReg(Src, MBB, IP);
2652
2653   // Implement casts to bool by using compare on the operand followed by set if
2654   // not zero on the result.
2655   if (DestTy == Type::BoolTy) {
2656     switch (SrcClass) {
2657     case cByte:
2658     case cShort:
2659     case cInt: {
2660       unsigned TmpReg = makeAnotherReg(Type::IntTy);
2661       BuildMI(*MBB, IP, PPC::ADDIC, 2, TmpReg).addReg(SrcReg).addSImm(-1);
2662       BuildMI(*MBB, IP, PPC::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg);
2663       break;
2664     }
2665     case cLong: {
2666       unsigned TmpReg = makeAnotherReg(Type::IntTy);
2667       unsigned SrcReg2 = makeAnotherReg(Type::IntTy);
2668       BuildMI(*MBB, IP, PPC::OR, 2, SrcReg2).addReg(SrcReg).addReg(SrcReg+1);
2669       BuildMI(*MBB, IP, PPC::ADDIC, 2, TmpReg).addReg(SrcReg2).addSImm(-1);
2670       BuildMI(*MBB, IP, PPC::SUBFE, 2, DestReg).addReg(TmpReg)
2671         .addReg(SrcReg2);
2672       break;
2673     }
2674     case cFP32:
2675     case cFP64:
2676       // FSEL perhaps?
2677       std::cerr << "ERROR: Cast fp-to-bool not implemented!\n";
2678       abort();
2679     }
2680     return;
2681   }
2682
2683   // Handle cast of Float -> Double
2684   if (SrcClass == cFP32 && DestClass == cFP64) {
2685     BuildMI(*MBB, IP, PPC::FMR, 1, DestReg).addReg(SrcReg);
2686     return;
2687   }
2688   
2689   // Handle cast of Double -> Float
2690   if (SrcClass == cFP64 && DestClass == cFP32) {
2691     BuildMI(*MBB, IP, PPC::FRSP, 1, DestReg).addReg(SrcReg);
2692     return;
2693   }
2694   
2695   // Handle casts from integer to floating point now...
2696   if (DestClass == cFP32 || DestClass == cFP64) {
2697
2698     // Emit a library call for long to float conversion
2699     if (SrcClass == cLong) {
2700       std::vector<ValueRecord> Args;
2701       Args.push_back(ValueRecord(SrcReg, SrcTy));
2702       Function *floatFn = (DestClass == cFP32) ? __floatdisfFn : __floatdidfFn;
2703       MachineInstr *TheCall =
2704         BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2705       doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2706       TM.CalledFunctions.insert(floatFn);
2707       return;
2708     }
2709     
2710     // Make sure we're dealing with a full 32 bits
2711     unsigned TmpReg = makeAnotherReg(Type::IntTy);
2712     promote32(TmpReg, ValueRecord(SrcReg, SrcTy));
2713
2714     SrcReg = TmpReg;
2715     
2716     // Spill the integer to memory and reload it from there.
2717     // Also spill room for a special conversion constant
2718     int ConstantFrameIndex = 
2719       F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2720     int ValueFrameIdx =
2721       F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2722
2723     unsigned constantHi = makeAnotherReg(Type::IntTy);
2724     unsigned constantLo = makeAnotherReg(Type::IntTy);
2725     unsigned ConstF = makeAnotherReg(Type::DoubleTy);
2726     unsigned TempF = makeAnotherReg(Type::DoubleTy);
2727     
2728     if (!SrcTy->isSigned()) {
2729       BuildMI(*BB, IP, PPC::LIS, 1, constantHi).addSImm(0x4330);
2730       BuildMI(*BB, IP, PPC::LI, 1, constantLo).addSImm(0);
2731       addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantHi), 
2732                         ConstantFrameIndex);
2733       addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantLo), 
2734                         ConstantFrameIndex, 4);
2735       addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantHi), 
2736                         ValueFrameIdx);
2737       addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(SrcReg), 
2738                         ValueFrameIdx, 4);
2739       addFrameReference(BuildMI(*BB, IP, PPC::LFD, 2, ConstF), 
2740                         ConstantFrameIndex);
2741       addFrameReference(BuildMI(*BB, IP, PPC::LFD, 2, TempF), ValueFrameIdx);
2742       BuildMI(*BB, IP, PPC::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2743     } else {
2744       unsigned TempLo = makeAnotherReg(Type::IntTy);
2745       BuildMI(*BB, IP, PPC::LIS, 1, constantHi).addSImm(0x4330);
2746       BuildMI(*BB, IP, PPC::LIS, 1, constantLo).addSImm(0x8000);
2747       addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantHi), 
2748                         ConstantFrameIndex);
2749       addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantLo), 
2750                         ConstantFrameIndex, 4);
2751       addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantHi), 
2752                         ValueFrameIdx);
2753       BuildMI(*BB, IP, PPC::XORIS, 2, TempLo).addReg(SrcReg).addImm(0x8000);
2754       addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(TempLo), 
2755                         ValueFrameIdx, 4);
2756       addFrameReference(BuildMI(*BB, IP, PPC::LFD, 2, ConstF), 
2757                         ConstantFrameIndex);
2758       addFrameReference(BuildMI(*BB, IP, PPC::LFD, 2, TempF), ValueFrameIdx);
2759       BuildMI(*BB, IP, PPC::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2760     }
2761     return;
2762   }
2763
2764   // Handle casts from floating point to integer now...
2765   if (SrcClass == cFP32 || SrcClass == cFP64) {
2766     static Function* const Funcs[] =
2767       { __fixsfdiFn, __fixdfdiFn, __fixunssfdiFn, __fixunsdfdiFn };
2768     // emit library call
2769     if (DestClass == cLong) {
2770       bool isDouble = SrcClass == cFP64;
2771       unsigned nameIndex = 2 * DestTy->isSigned() + isDouble;
2772       std::vector<ValueRecord> Args;
2773       Args.push_back(ValueRecord(SrcReg, SrcTy));
2774       Function *floatFn = Funcs[nameIndex];
2775       MachineInstr *TheCall =
2776         BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2777       doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2778       TM.CalledFunctions.insert(floatFn);
2779       return;
2780     }
2781
2782     int ValueFrameIdx =
2783       F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2784
2785     if (DestTy->isSigned()) {
2786       unsigned TempReg = makeAnotherReg(Type::DoubleTy);
2787       
2788       // Convert to integer in the FP reg and store it to a stack slot
2789       BuildMI(*BB, IP, PPC::FCTIWZ, 1, TempReg).addReg(SrcReg);
2790       addFrameReference(BuildMI(*BB, IP, PPC::STFD, 3)
2791                           .addReg(TempReg), ValueFrameIdx);
2792
2793       // There is no load signed byte opcode, so we must emit a sign extend for
2794       // that particular size.  Make sure to source the new integer from the 
2795       // correct offset.
2796       if (DestClass == cByte) {
2797         unsigned TempReg2 = makeAnotherReg(DestTy);
2798         addFrameReference(BuildMI(*BB, IP, PPC::LBZ, 2, TempReg2), 
2799                           ValueFrameIdx, 7);
2800         BuildMI(*BB, IP, PPC::EXTSB, 1, DestReg).addReg(TempReg2);
2801       } else {
2802         int offset = (DestClass == cShort) ? 6 : 4;
2803         unsigned LoadOp = (DestClass == cShort) ? PPC::LHA : PPC::LWZ;
2804         addFrameReference(BuildMI(*BB, IP, LoadOp, 2, DestReg), 
2805                           ValueFrameIdx, offset);
2806       }
2807     } else {
2808       unsigned Zero = getReg(ConstantFP::get(Type::DoubleTy, 0.0f));
2809       double maxInt = (1LL << 32) - 1;
2810       unsigned MaxInt = getReg(ConstantFP::get(Type::DoubleTy, maxInt));
2811       double border = 1LL << 31;
2812       unsigned Border = getReg(ConstantFP::get(Type::DoubleTy, border));
2813       unsigned UseZero = makeAnotherReg(Type::DoubleTy);
2814       unsigned UseMaxInt = makeAnotherReg(Type::DoubleTy);
2815       unsigned UseChoice = makeAnotherReg(Type::DoubleTy);
2816       unsigned TmpReg = makeAnotherReg(Type::DoubleTy);
2817       unsigned TmpReg2 = makeAnotherReg(Type::DoubleTy);
2818       unsigned ConvReg = makeAnotherReg(Type::DoubleTy);
2819       unsigned IntTmp = makeAnotherReg(Type::IntTy);
2820       unsigned XorReg = makeAnotherReg(Type::IntTy);
2821       int FrameIdx = 
2822         F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2823       // Update machine-CFG edges
2824       MachineBasicBlock *XorMBB = new MachineBasicBlock(BB->getBasicBlock());
2825       MachineBasicBlock *PhiMBB = new MachineBasicBlock(BB->getBasicBlock());
2826       MachineBasicBlock *OldMBB = BB;
2827       ilist<MachineBasicBlock>::iterator It = BB; ++It;
2828       F->getBasicBlockList().insert(It, XorMBB);
2829       F->getBasicBlockList().insert(It, PhiMBB);
2830       BB->addSuccessor(XorMBB);
2831       BB->addSuccessor(PhiMBB);
2832
2833       // Convert from floating point to unsigned 32-bit value
2834       // Use 0 if incoming value is < 0.0
2835       BuildMI(*BB, IP, PPC::FSEL, 3, UseZero).addReg(SrcReg).addReg(SrcReg)
2836         .addReg(Zero);
2837       // Use 2**32 - 1 if incoming value is >= 2**32
2838       BuildMI(*BB, IP, PPC::FSUB, 2, UseMaxInt).addReg(MaxInt).addReg(SrcReg);
2839       BuildMI(*BB, IP, PPC::FSEL, 3, UseChoice).addReg(UseMaxInt)
2840         .addReg(UseZero).addReg(MaxInt);
2841       // Subtract 2**31
2842       BuildMI(*BB, IP, PPC::FSUB, 2, TmpReg).addReg(UseChoice).addReg(Border);
2843       // Use difference if >= 2**31
2844       BuildMI(*BB, IP, PPC::FCMPU, 2, PPC::CR0).addReg(UseChoice)
2845         .addReg(Border);
2846       BuildMI(*BB, IP, PPC::FSEL, 3, TmpReg2).addReg(TmpReg).addReg(TmpReg)
2847         .addReg(UseChoice);
2848       // Convert to integer
2849       BuildMI(*BB, IP, PPC::FCTIWZ, 1, ConvReg).addReg(TmpReg2);
2850       addFrameReference(BuildMI(*BB, IP, PPC::STFD, 3).addReg(ConvReg),
2851                         FrameIdx);
2852       if (DestClass == cByte) {
2853         addFrameReference(BuildMI(*BB, IP, PPC::LBZ, 2, DestReg),
2854                           FrameIdx, 7);
2855       } else if (DestClass == cShort) {
2856         addFrameReference(BuildMI(*BB, IP, PPC::LHZ, 2, DestReg),
2857                           FrameIdx, 6);
2858       } if (DestClass == cInt) {
2859         addFrameReference(BuildMI(*BB, IP, PPC::LWZ, 2, IntTmp),
2860                           FrameIdx, 4);
2861         BuildMI(*BB, IP, PPC::BLT, 2).addReg(PPC::CR0).addMBB(PhiMBB);
2862         BuildMI(*BB, IP, PPC::B, 1).addMBB(XorMBB);
2863
2864         // XorMBB:
2865         //   add 2**31 if input was >= 2**31
2866         BB = XorMBB;
2867         BuildMI(BB, PPC::XORIS, 2, XorReg).addReg(IntTmp).addImm(0x8000);
2868         XorMBB->addSuccessor(PhiMBB);
2869
2870         // PhiMBB:
2871         //   DestReg = phi [ IntTmp, OldMBB ], [ XorReg, XorMBB ]
2872         BB = PhiMBB;
2873         BuildMI(BB, PPC::PHI, 2, DestReg).addReg(IntTmp).addMBB(OldMBB)
2874           .addReg(XorReg).addMBB(XorMBB);
2875       }
2876     }
2877     return;
2878   }
2879
2880   // Check our invariants
2881   assert((SrcClass <= cInt || SrcClass == cLong) && 
2882          "Unhandled source class for cast operation!");
2883   assert((DestClass <= cInt || DestClass == cLong) && 
2884          "Unhandled destination class for cast operation!");
2885
2886   bool sourceUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2887   bool destUnsigned = DestTy->isUnsigned();
2888
2889   // Unsigned -> Unsigned, clear if larger, 
2890   if (sourceUnsigned && destUnsigned) {
2891     // handle long dest class now to keep switch clean
2892     if (DestClass == cLong) {
2893       if (SrcClass == cLong) {
2894         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2895         BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg+1)
2896           .addReg(SrcReg+1);
2897       } else {
2898         BuildMI(*MBB, IP, PPC::LI, 1, DestReg).addSImm(0);
2899         BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
2900           .addReg(SrcReg);
2901       }
2902       return;
2903     }
2904
2905     // handle u{ byte, short, int } x u{ byte, short, int }
2906     unsigned clearBits = (SrcClass == cByte || DestClass == cByte) ? 24 : 16;
2907     switch (SrcClass) {
2908     case cByte:
2909     case cShort:
2910       if (SrcClass == DestClass)
2911         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2912       else
2913         BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2914           .addImm(0).addImm(clearBits).addImm(31);
2915       break;
2916     case cLong:
2917       ++SrcReg;
2918       // Fall through
2919     case cInt:
2920       if (DestClass == cInt)
2921         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2922       else
2923         BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2924           .addImm(0).addImm(clearBits).addImm(31);
2925       break;
2926     }
2927     return;
2928   }
2929
2930   // Signed -> Signed
2931   if (!sourceUnsigned && !destUnsigned) {
2932     // handle long dest class now to keep switch clean
2933     if (DestClass == cLong) {
2934       if (SrcClass == cLong) {
2935         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2936         BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg+1)
2937           .addReg(SrcReg+1);
2938       } else {
2939         BuildMI(*MBB, IP, PPC::SRAWI, 2, DestReg).addReg(SrcReg).addImm(31);
2940         BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
2941           .addReg(SrcReg);
2942       }
2943       return;
2944     }
2945
2946     // handle { byte, short, int } x { byte, short, int }
2947     switch (SrcClass) {
2948     case cByte:
2949       if (DestClass == cByte)
2950         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2951       else
2952         BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2953       break;
2954     case cShort:
2955       if (DestClass == cByte)
2956         BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2957       else if (DestClass == cShort)
2958         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2959       else
2960         BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
2961       break;
2962     case cLong:
2963       ++SrcReg;
2964       // Fall through
2965     case cInt:
2966       if (DestClass == cByte)
2967         BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2968       else if (DestClass == cShort)
2969         BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
2970       else
2971         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2972       break;
2973     }
2974     return;
2975   }
2976
2977   // Unsigned -> Signed
2978   if (sourceUnsigned && !destUnsigned) {
2979     // handle long dest class now to keep switch clean
2980     if (DestClass == cLong) {
2981       if (SrcClass == cLong) {
2982         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2983         BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg+1).
2984           addReg(SrcReg+1);
2985       } else {
2986         BuildMI(*MBB, IP, PPC::LI, 1, DestReg).addSImm(0);
2987         BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
2988           .addReg(SrcReg);
2989       }
2990       return;
2991     }
2992
2993     // handle u{ byte, short, int } -> { byte, short, int }
2994     switch (SrcClass) {
2995     case cByte:
2996       if (DestClass == cByte)
2997         // uByte 255 -> signed byte == -1
2998         BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2999       else
3000         // uByte 255 -> signed short/int == 255
3001         BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg).addImm(0)
3002           .addImm(24).addImm(31);
3003       break;
3004     case cShort:
3005       if (DestClass == cByte)
3006         BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3007       else if (DestClass == cShort)
3008         BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
3009       else
3010         BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg).addImm(0)
3011           .addImm(16).addImm(31);
3012       break;
3013     case cLong:
3014       ++SrcReg;
3015       // Fall through
3016     case cInt:
3017       if (DestClass == cByte)
3018         BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3019       else if (DestClass == cShort)
3020         BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
3021       else
3022         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3023       break;
3024     }
3025     return;
3026   }
3027
3028   // Signed -> Unsigned
3029   if (!sourceUnsigned && destUnsigned) {
3030     // handle long dest class now to keep switch clean
3031     if (DestClass == cLong) {
3032       if (SrcClass == cLong) {
3033         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3034         BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg+1)
3035           .addReg(SrcReg+1);
3036       } else {
3037         BuildMI(*MBB, IP, PPC::SRAWI, 2, DestReg).addReg(SrcReg).addImm(31);
3038         BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
3039           .addReg(SrcReg);
3040       }
3041       return;
3042     }
3043
3044     // handle { byte, short, int } -> u{ byte, short, int }
3045     unsigned clearBits = (DestClass == cByte) ? 24 : 16;
3046     switch (SrcClass) {
3047     case cByte:
3048     case cShort:
3049       if (DestClass == cByte || DestClass == cShort)
3050         // sbyte -1 -> ubyte 0x000000FF
3051         BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
3052           .addImm(0).addImm(clearBits).addImm(31);
3053       else
3054         // sbyte -1 -> ubyte 0xFFFFFFFF
3055         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3056       break;
3057     case cLong:
3058       ++SrcReg;
3059       // Fall through
3060     case cInt:
3061       if (DestClass == cInt)
3062         BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3063       else
3064         BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
3065           .addImm(0).addImm(clearBits).addImm(31);
3066       break;
3067     }
3068     return;
3069   }
3070
3071   // Anything we haven't handled already, we can't (yet) handle at all.
3072   std::cerr << "Unhandled cast from " << SrcTy->getDescription()
3073             << "to " << DestTy->getDescription() << '\n';
3074   abort();
3075 }
3076
3077 /// visitVANextInst - Implement the va_next instruction...
3078 ///
3079 void ISel::visitVANextInst(VANextInst &I) {
3080   unsigned VAList = getReg(I.getOperand(0));
3081   unsigned DestReg = getReg(I);
3082
3083   unsigned Size;
3084   switch (I.getArgType()->getTypeID()) {
3085   default:
3086     std::cerr << I;
3087     assert(0 && "Error: bad type for va_next instruction!");
3088     return;
3089   case Type::PointerTyID:
3090   case Type::UIntTyID:
3091   case Type::IntTyID:
3092     Size = 4;
3093     break;
3094   case Type::ULongTyID:
3095   case Type::LongTyID:
3096   case Type::DoubleTyID:
3097     Size = 8;
3098     break;
3099   }
3100
3101   // Increment the VAList pointer...
3102   BuildMI(BB, PPC::ADDI, 2, DestReg).addReg(VAList).addSImm(Size);
3103 }
3104
3105 void ISel::visitVAArgInst(VAArgInst &I) {
3106   unsigned VAList = getReg(I.getOperand(0));
3107   unsigned DestReg = getReg(I);
3108
3109   switch (I.getType()->getTypeID()) {
3110   default:
3111     std::cerr << I;
3112     assert(0 && "Error: bad type for va_next instruction!");
3113     return;
3114   case Type::PointerTyID:
3115   case Type::UIntTyID:
3116   case Type::IntTyID:
3117     BuildMI(BB, PPC::LWZ, 2, DestReg).addSImm(0).addReg(VAList);
3118     break;
3119   case Type::ULongTyID:
3120   case Type::LongTyID:
3121     BuildMI(BB, PPC::LWZ, 2, DestReg).addSImm(0).addReg(VAList);
3122     BuildMI(BB, PPC::LWZ, 2, DestReg+1).addSImm(4).addReg(VAList);
3123     break;
3124   case Type::FloatTyID:
3125     BuildMI(BB, PPC::LFS, 2, DestReg).addSImm(0).addReg(VAList);
3126     break;
3127   case Type::DoubleTyID:
3128     BuildMI(BB, PPC::LFD, 2, DestReg).addSImm(0).addReg(VAList);
3129     break;
3130   }
3131 }
3132
3133 /// visitGetElementPtrInst - instruction-select GEP instructions
3134 ///
3135 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
3136   if (canFoldGEPIntoLoadOrStore(&I))
3137     return;
3138
3139   unsigned outputReg = getReg(I);
3140   emitGEPOperation(BB, BB->end(), I.getOperand(0), I.op_begin()+1, I.op_end(), 
3141                    outputReg, false, 0, 0);
3142 }
3143
3144 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
3145 /// constant expression GEP support.
3146 ///
3147 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
3148                             MachineBasicBlock::iterator IP,
3149                             Value *Src, User::op_iterator IdxBegin,
3150                             User::op_iterator IdxEnd, unsigned TargetReg,
3151                             bool GEPIsFolded, ConstantSInt **RemainderPtr,
3152                             unsigned *PendingAddReg) {
3153   const TargetData &TD = TM.getTargetData();
3154   const Type *Ty = Src->getType();
3155   unsigned basePtrReg = getReg(Src, MBB, IP);
3156   int64_t constValue = 0;
3157   
3158   // Record the operations to emit the GEP in a vector so that we can emit them
3159   // after having analyzed the entire instruction.
3160   std::vector<CollapsedGepOp> ops;
3161   
3162   // GEPs have zero or more indices; we must perform a struct access
3163   // or array access for each one.
3164   for (GetElementPtrInst::op_iterator oi = IdxBegin, oe = IdxEnd; oi != oe;
3165        ++oi) {
3166     Value *idx = *oi;
3167     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3168       // It's a struct access.  idx is the index into the structure,
3169       // which names the field. Use the TargetData structure to
3170       // pick out what the layout of the structure is in memory.
3171       // Use the (constant) structure index's value to find the
3172       // right byte offset from the StructLayout class's list of
3173       // structure member offsets.
3174       unsigned fieldIndex = cast<ConstantUInt>(idx)->getValue();
3175       unsigned memberOffset =
3176         TD.getStructLayout(StTy)->MemberOffsets[fieldIndex];
3177
3178       // StructType member offsets are always constant values.  Add it to the
3179       // running total.
3180       constValue += memberOffset;
3181
3182       // The next type is the member of the structure selected by the
3183       // index.
3184       Ty = StTy->getElementType (fieldIndex);
3185     } else if (const SequentialType *SqTy = dyn_cast<SequentialType> (Ty)) {
3186       // Many GEP instructions use a [cast (int/uint) to LongTy] as their
3187       // operand.  Handle this case directly now...
3188       if (CastInst *CI = dyn_cast<CastInst>(idx))
3189         if (CI->getOperand(0)->getType() == Type::IntTy ||
3190             CI->getOperand(0)->getType() == Type::UIntTy)
3191           idx = CI->getOperand(0);
3192
3193       // It's an array or pointer access: [ArraySize x ElementType].
3194       // We want to add basePtrReg to (idxReg * sizeof ElementType). First, we
3195       // must find the size of the pointed-to type (Not coincidentally, the next
3196       // type is the type of the elements in the array).
3197       Ty = SqTy->getElementType();
3198       unsigned elementSize = TD.getTypeSize(Ty);
3199       
3200       if (ConstantInt *C = dyn_cast<ConstantInt>(idx)) {
3201         if (ConstantSInt *CS = dyn_cast<ConstantSInt>(C))
3202           constValue += CS->getValue() * elementSize;
3203         else if (ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
3204           constValue += CU->getValue() * elementSize;
3205         else
3206           assert(0 && "Invalid ConstantInt GEP index type!");
3207       } else {
3208         // Push current gep state to this point as an add
3209         ops.push_back(CollapsedGepOp(false, 0, 
3210           ConstantSInt::get(Type::IntTy,constValue)));
3211         
3212         // Push multiply gep op and reset constant value
3213         ops.push_back(CollapsedGepOp(true, idx, 
3214           ConstantSInt::get(Type::IntTy, elementSize)));
3215         
3216         constValue = 0;
3217       }
3218     }
3219   }
3220   // Emit instructions for all the collapsed ops
3221   bool pendingAdd = false;
3222   unsigned pendingAddReg = 0;
3223   
3224   for(std::vector<CollapsedGepOp>::iterator cgo_i = ops.begin(),
3225       cgo_e = ops.end(); cgo_i != cgo_e; ++cgo_i) {
3226     CollapsedGepOp& cgo = *cgo_i;
3227     unsigned nextBasePtrReg = makeAnotherReg(Type::IntTy);
3228   
3229     // If we didn't emit an add last time through the loop, we need to now so
3230     // that the base reg is updated appropriately.
3231     if (pendingAdd) {
3232       assert(pendingAddReg != 0 && "Uninitialized register in pending add!");
3233       BuildMI(*MBB, IP, PPC::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
3234         .addReg(pendingAddReg);
3235       basePtrReg = nextBasePtrReg;
3236       nextBasePtrReg = makeAnotherReg(Type::IntTy);
3237       pendingAddReg = 0;
3238       pendingAdd = false;
3239     }
3240
3241     if (cgo.isMul) {
3242       // We know the elementSize is a constant, so we can emit a constant mul
3243       unsigned TmpReg = makeAnotherReg(Type::IntTy);
3244       doMultiplyConst(MBB, IP, nextBasePtrReg, cgo.index, cgo.size);
3245       pendingAddReg = basePtrReg;
3246       pendingAdd = true;
3247     } else {
3248       // Try and generate an immediate addition if possible
3249       if (cgo.size->isNullValue()) {
3250         BuildMI(*MBB, IP, PPC::OR, 2, nextBasePtrReg).addReg(basePtrReg)
3251           .addReg(basePtrReg);
3252       } else if (canUseAsImmediateForOpcode(cgo.size, 0)) {
3253         BuildMI(*MBB, IP, PPC::ADDI, 2, nextBasePtrReg).addReg(basePtrReg)
3254           .addSImm(cgo.size->getValue());
3255       } else {
3256         unsigned Op1r = getReg(cgo.size, MBB, IP);
3257         BuildMI(*MBB, IP, PPC::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
3258           .addReg(Op1r);
3259       }
3260     }
3261
3262     basePtrReg = nextBasePtrReg;
3263   }
3264   // Add the current base register plus any accumulated constant value
3265   ConstantSInt *remainder = ConstantSInt::get(Type::IntTy, constValue);
3266   
3267   // If we are emitting this during a fold, copy the current base register to
3268   // the target, and save the current constant offset so the folding load or
3269   // store can try and use it as an immediate.
3270   if (GEPIsFolded) {
3271     // If this is a folded GEP and the last element was an index, then we need
3272     // to do some extra work to turn a shift/add/stw into a shift/stwx
3273     if (pendingAdd && 0 == remainder->getValue()) {
3274       assert(pendingAddReg != 0 && "Uninitialized register in pending add!");
3275       *PendingAddReg = pendingAddReg;
3276     } else {
3277       *PendingAddReg = 0;
3278       if (pendingAdd) {
3279         unsigned nextBasePtrReg = makeAnotherReg(Type::IntTy);
3280         assert(pendingAddReg != 0 && "Uninitialized register in pending add!");
3281         BuildMI(*MBB, IP, PPC::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
3282           .addReg(pendingAddReg);
3283         basePtrReg = nextBasePtrReg;
3284       }
3285     }
3286     BuildMI (*MBB, IP, PPC::OR, 2, TargetReg).addReg(basePtrReg)
3287       .addReg(basePtrReg);
3288     *RemainderPtr = remainder;
3289     return;
3290   }
3291
3292   // If we still have a pending add at this point, emit it now
3293   if (pendingAdd) {
3294     unsigned TmpReg = makeAnotherReg(Type::IntTy);
3295     BuildMI(*MBB, IP, PPC::ADD, 2, TmpReg).addReg(pendingAddReg)
3296       .addReg(basePtrReg);
3297     basePtrReg = TmpReg;
3298   }
3299   
3300   // After we have processed all the indices, the result is left in
3301   // basePtrReg.  Move it to the register where we were expected to
3302   // put the answer.
3303   if (remainder->isNullValue()) {
3304     BuildMI (*MBB, IP, PPC::OR, 2, TargetReg).addReg(basePtrReg)
3305       .addReg(basePtrReg);
3306   } else if (canUseAsImmediateForOpcode(remainder, 0)) {
3307     BuildMI(*MBB, IP, PPC::ADDI, 2, TargetReg).addReg(basePtrReg)
3308       .addSImm(remainder->getValue());
3309   } else {
3310     unsigned Op1r = getReg(remainder, MBB, IP);
3311     BuildMI(*MBB, IP, PPC::ADD, 2, TargetReg).addReg(basePtrReg).addReg(Op1r);
3312   }
3313 }
3314
3315 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
3316 /// frame manager, otherwise do it the hard way.
3317 ///
3318 void ISel::visitAllocaInst(AllocaInst &I) {
3319   // If this is a fixed size alloca in the entry block for the function, we
3320   // statically stack allocate the space, so we don't need to do anything here.
3321   //
3322   if (dyn_castFixedAlloca(&I)) return;
3323   
3324   // Find the data size of the alloca inst's getAllocatedType.
3325   const Type *Ty = I.getAllocatedType();
3326   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
3327
3328   // Create a register to hold the temporary result of multiplying the type size
3329   // constant by the variable amount.
3330   unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
3331   
3332   // TotalSizeReg = mul <numelements>, <TypeSize>
3333   MachineBasicBlock::iterator MBBI = BB->end();
3334   ConstantUInt *CUI = ConstantUInt::get(Type::UIntTy, TySize);
3335   doMultiplyConst(BB, MBBI, TotalSizeReg, I.getArraySize(), CUI);
3336
3337   // AddedSize = add <TotalSizeReg>, 15
3338   unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
3339   BuildMI(BB, PPC::ADDI, 2, AddedSizeReg).addReg(TotalSizeReg).addSImm(15);
3340
3341   // AlignedSize = and <AddedSize>, ~15
3342   unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
3343   BuildMI(BB, PPC::RLWINM, 4, AlignedSize).addReg(AddedSizeReg).addImm(0)
3344     .addImm(0).addImm(27);
3345   
3346   // Subtract size from stack pointer, thereby allocating some space.
3347   BuildMI(BB, PPC::SUB, 2, PPC::R1).addReg(PPC::R1).addReg(AlignedSize);
3348
3349   // Put a pointer to the space into the result register, by copying
3350   // the stack pointer.
3351   BuildMI(BB, PPC::OR, 2, getReg(I)).addReg(PPC::R1).addReg(PPC::R1);
3352
3353   // Inform the Frame Information that we have just allocated a variable-sized
3354   // object.
3355   F->getFrameInfo()->CreateVariableSizedObject();
3356 }
3357
3358 /// visitMallocInst - Malloc instructions are code generated into direct calls
3359 /// to the library malloc.
3360 ///
3361 void ISel::visitMallocInst(MallocInst &I) {
3362   unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
3363   unsigned Arg;
3364
3365   if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
3366     Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
3367   } else {
3368     Arg = makeAnotherReg(Type::UIntTy);
3369     MachineBasicBlock::iterator MBBI = BB->end();
3370     ConstantUInt *CUI = ConstantUInt::get(Type::UIntTy, AllocSize);
3371     doMultiplyConst(BB, MBBI, Arg, I.getOperand(0), CUI);
3372   }
3373
3374   std::vector<ValueRecord> Args;
3375   Args.push_back(ValueRecord(Arg, Type::UIntTy));
3376   MachineInstr *TheCall = 
3377     BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(mallocFn, true);
3378   doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args, false);
3379   TM.CalledFunctions.insert(mallocFn);
3380 }
3381
3382
3383 /// visitFreeInst - Free instructions are code gen'd to call the free libc
3384 /// function.
3385 ///
3386 void ISel::visitFreeInst(FreeInst &I) {
3387   std::vector<ValueRecord> Args;
3388   Args.push_back(ValueRecord(I.getOperand(0)));
3389   MachineInstr *TheCall = 
3390     BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(freeFn, true);
3391   doCall(ValueRecord(0, Type::VoidTy), TheCall, Args, false);
3392   TM.CalledFunctions.insert(freeFn);
3393 }
3394    
3395 /// createPPC32ISelSimple - This pass converts an LLVM function into a machine
3396 /// code representation is a very simple peep-hole fashion.
3397 ///
3398 FunctionPass *llvm::createPPC32ISelSimple(TargetMachine &TM) {
3399   return new ISel(TM);
3400 }