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