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