Add protoypes for 64-bit long/ulong div, mul, and rem functions
[oota-llvm.git] / lib / Target / SparcV8 / SparcV8ISelSimple.cpp
1 //===-- InstSelectSimple.cpp - A simple instruction selector for SparcV8 --===//
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 // This file defines a simple peephole instruction selector for the V8 target
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "SparcV8.h"
15 #include "SparcV8InstrInfo.h"
16 #include "llvm/Support/Debug.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CodeGen/IntrinsicLowering.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/GetElementPtrTypeIterator.h"
28 #include "llvm/Support/InstVisitor.h"
29 #include "llvm/Support/CFG.h"
30 using namespace llvm;
31
32 namespace {
33   struct V8ISel : public FunctionPass, public InstVisitor<V8ISel> {
34     TargetMachine &TM;
35     MachineFunction *F;                 // The function we are compiling into
36     MachineBasicBlock *BB;              // The current MBB we are compiling
37     int VarArgsOffset;                  // Offset from fp for start of varargs area
38
39     // External functions we may use in compiling the Module
40     Function *__div64Fn, *__mul64Fn, *__rem64Fn,
41       *__udiv64Fn, *__umul64Fn, *__urem64Fn;
42
43     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
44
45     // MBBMap - Mapping between LLVM BB -> Machine BB
46     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
47
48     V8ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
49
50     bool doInitialization(Module &M) {
51       // Add external functions that we may call
52       Type *l = Type::LongTy;
53       Type *ul = Type::ULongTy;
54       // long __div64(long, long);
55       __div64Fn = M.getOrInsertFunction("__div64", l, l, l, 0);
56       // long __div64(long, long);
57       __mul64Fn = M.getOrInsertFunction("__mul64", l, l, l, 0);
58       // long __div64(long, long);
59       __rem64Fn = M.getOrInsertFunction("__rem64", l, l, l, 0);
60       // unsigned long __udiv64(unsigned long, unsigned long);
61       __udiv64Fn = M.getOrInsertFunction("__udiv64", ul, ul, ul, 0);
62       // unsigned long __umul64(unsigned long, unsigned long);
63       __umul64Fn = M.getOrInsertFunction("__umul64", ul, ul, ul, 0);
64       // unsigned long __urem64(unsigned long, unsigned long);
65       __urem64Fn = M.getOrInsertFunction("__urem64", ul, ul, ul, 0);
66       return true;
67     }
68
69     /// runOnFunction - Top level implementation of instruction selection for
70     /// the entire function.
71     ///
72     bool runOnFunction(Function &Fn);
73
74     virtual const char *getPassName() const {
75       return "SparcV8 Simple Instruction Selection";
76     }
77
78     /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
79     /// constant expression GEP support.
80     ///
81     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
82                           Value *Src, User::op_iterator IdxBegin,
83                           User::op_iterator IdxEnd, unsigned TargetReg);
84
85     /// emitCastOperation - Common code shared between visitCastInst and
86     /// constant expression cast support.
87     ///
88     void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
89                            Value *Src, const Type *DestTy, unsigned TargetReg);
90
91     /// emitIntegerCast, emitFPToIntegerCast - Helper methods for
92     /// emitCastOperation.
93     ///
94     unsigned emitIntegerCast (MachineBasicBlock *BB,
95                               MachineBasicBlock::iterator IP,
96                               const Type *oldTy, unsigned SrcReg,
97                               const Type *newTy, unsigned DestReg);
98     void emitFPToIntegerCast (MachineBasicBlock *BB,
99                               MachineBasicBlock::iterator IP, const Type *oldTy,
100                               unsigned SrcReg, const Type *newTy,
101                               unsigned DestReg);
102
103     /// visitBasicBlock - This method is called when we are visiting a new basic
104     /// block.  This simply creates a new MachineBasicBlock to emit code into
105     /// and adds it to the current MachineFunction.  Subsequent visit* for
106     /// instructions will be invoked for all instructions in the basic block.
107     ///
108     void visitBasicBlock(BasicBlock &LLVM_BB) {
109       BB = MBBMap[&LLVM_BB];
110     }
111
112     void visitBinaryOperator(Instruction &I);
113     void visitShiftInst (ShiftInst &SI) { visitBinaryOperator (SI); }
114     void visitSetCondInst(SetCondInst &I);
115     void visitCallInst(CallInst &I);
116     void visitReturnInst(ReturnInst &I);
117     void visitBranchInst(BranchInst &I);
118     void visitUnreachableInst(UnreachableInst &I) {}
119     void visitCastInst(CastInst &I);
120     void visitVANextInst(VANextInst &I);
121     void visitVAArgInst(VAArgInst &I);
122     void visitLoadInst(LoadInst &I);
123     void visitStoreInst(StoreInst &I);
124     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
125     void visitGetElementPtrInst(GetElementPtrInst &I);
126     void visitAllocaInst(AllocaInst &I);
127
128     void visitInstruction(Instruction &I) {
129       std::cerr << "Unhandled instruction: " << I;
130       abort();
131     }
132
133     /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
134     /// function, lowering any calls to unknown intrinsic functions into the
135     /// equivalent LLVM code.
136     void LowerUnknownIntrinsicFunctionCalls(Function &F);
137     void visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI);
138
139     void LoadArgumentsToVirtualRegs(Function *F);
140
141     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
142     /// because we have to generate our sources into the source basic blocks,
143     /// not the current one.
144     ///
145     void SelectPHINodes();
146
147     /// copyConstantToRegister - Output the instructions required to put the
148     /// specified constant into the specified register.
149     ///
150     void copyConstantToRegister(MachineBasicBlock *MBB,
151                                 MachineBasicBlock::iterator IP,
152                                 Constant *C, unsigned R);
153
154     /// makeAnotherReg - This method returns the next register number we haven't
155     /// yet used.
156     ///
157     /// Long values are handled somewhat specially.  They are always allocated
158     /// as pairs of 32 bit integer values.  The register number returned is the
159     /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
160     /// of the long value.
161     ///
162     unsigned makeAnotherReg(const Type *Ty) {
163       assert(dynamic_cast<const SparcV8RegisterInfo*>(TM.getRegisterInfo()) &&
164              "Current target doesn't have SparcV8 reg info??");
165       const SparcV8RegisterInfo *MRI =
166         static_cast<const SparcV8RegisterInfo*>(TM.getRegisterInfo());
167       if (Ty == Type::LongTy || Ty == Type::ULongTy) {
168         const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
169         // Create the lower part
170         F->getSSARegMap()->createVirtualRegister(RC);
171         // Create the upper part.
172         return F->getSSARegMap()->createVirtualRegister(RC)-1;
173       }
174
175       // Add the mapping of regnumber => reg class to MachineFunction
176       const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
177       return F->getSSARegMap()->createVirtualRegister(RC);
178     }
179
180     unsigned getReg(Value &V) { return getReg (&V); } // allow refs.
181     unsigned getReg(Value *V) {
182       // Just append to the end of the current bb.
183       MachineBasicBlock::iterator It = BB->end();
184       return getReg(V, BB, It);
185     }
186     unsigned getReg(Value *V, MachineBasicBlock *MBB,
187                     MachineBasicBlock::iterator IPt) {
188       unsigned &Reg = RegMap[V];
189       if (Reg == 0) {
190         Reg = makeAnotherReg(V->getType());
191         RegMap[V] = Reg;
192       }
193       // If this operand is a constant, emit the code to copy the constant into
194       // the register here...
195       //
196       if (Constant *C = dyn_cast<Constant>(V)) {
197         copyConstantToRegister(MBB, IPt, C, Reg);
198         RegMap.erase(V);  // Assign a new name to this constant if ref'd again
199       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
200         // Move the address of the global into the register
201         unsigned TmpReg = makeAnotherReg(V->getType());
202         BuildMI (*MBB, IPt, V8::SETHIi, 1, TmpReg).addGlobalAddress (GV);
203         BuildMI (*MBB, IPt, V8::ORri, 2, Reg).addReg (TmpReg)
204           .addGlobalAddress (GV);
205         RegMap.erase(V);  // Assign a new name to this address if ref'd again
206       }
207
208       return Reg;
209     }
210
211   };
212 }
213
214 FunctionPass *llvm::createSparcV8SimpleInstructionSelector(TargetMachine &TM) {
215   return new V8ISel(TM);
216 }
217
218 enum TypeClass {
219   cByte, cShort, cInt, cLong, cFloat, cDouble
220 };
221
222 static TypeClass getClass (const Type *T) {
223   switch (T->getTypeID()) {
224     case Type::UByteTyID:  case Type::SByteTyID:  return cByte;
225     case Type::UShortTyID: case Type::ShortTyID:  return cShort;
226     case Type::PointerTyID:
227     case Type::UIntTyID:   case Type::IntTyID:    return cInt;
228     case Type::ULongTyID:  case Type::LongTyID:   return cLong;
229     case Type::FloatTyID:                         return cFloat;
230     case Type::DoubleTyID:                        return cDouble;
231     default:
232       assert (0 && "Type of unknown class passed to getClass?");
233       return cByte;
234   }
235 }
236
237 static TypeClass getClassB(const Type *T) {
238   if (T == Type::BoolTy) return cByte;
239   return getClass(T);
240 }
241
242 /// copyConstantToRegister - Output the instructions required to put the
243 /// specified constant into the specified register.
244 ///
245 void V8ISel::copyConstantToRegister(MachineBasicBlock *MBB,
246                                     MachineBasicBlock::iterator IP,
247                                     Constant *C, unsigned R) {
248   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
249     switch (CE->getOpcode()) {
250     case Instruction::GetElementPtr:
251       emitGEPOperation(MBB, IP, CE->getOperand(0),
252                        CE->op_begin()+1, CE->op_end(), R);
253       return;
254     case Instruction::Cast:
255       emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
256       return;
257     default:
258       std::cerr << "Copying this constant expr not yet handled: " << *CE;
259       abort();
260     }
261   } else if (isa<UndefValue>(C)) {
262     BuildMI(*MBB, IP, V8::IMPLICIT_DEF, 0, R);
263     if (getClassB (C->getType ()) == cLong)
264       BuildMI(*MBB, IP, V8::IMPLICIT_DEF, 0, R+1);
265     return;
266   }
267
268   if (C->getType()->isIntegral ()) {
269     uint64_t Val;
270     unsigned Class = getClassB (C->getType ());
271     if (Class == cLong) {
272       unsigned TmpReg = makeAnotherReg (Type::IntTy);
273       unsigned TmpReg2 = makeAnotherReg (Type::IntTy);
274       // Copy the value into the register pair.
275       // R = top(more-significant) half, R+1 = bottom(less-significant) half
276       uint64_t Val = cast<ConstantInt>(C)->getRawValue();
277       copyConstantToRegister(MBB, IP, ConstantUInt::get(Type::UIntTy,
278                              Val >> 32), R);
279       copyConstantToRegister(MBB, IP, ConstantUInt::get(Type::UIntTy,
280                              Val & 0xffffffffU), R+1);
281       return;
282     }
283
284     assert(Class <= cInt && "Type not handled yet!");
285
286     if (C->getType() == Type::BoolTy) {
287       Val = (C == ConstantBool::True);
288     } else {
289       ConstantInt *CI = cast<ConstantInt> (C);
290       Val = CI->getRawValue ();
291     }
292     switch (Class) {
293       case cByte:  Val =  (int8_t) Val; break;
294       case cShort: Val = (int16_t) Val; break;
295       case cInt:   Val = (int32_t) Val; break;
296       default:
297         std::cerr << "Offending constant: " << *C << "\n";
298         assert (0 && "Can't copy this kind of constant into register yet");
299         return;
300     }
301     if (Val == 0) {
302       BuildMI (*MBB, IP, V8::ORrr, 2, R).addReg (V8::G0).addReg(V8::G0);
303     } else if (((int64_t)Val >= -4096) && ((int64_t)Val <= 4095)) {
304       BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (V8::G0).addSImm(Val);
305     } else {
306       unsigned TmpReg = makeAnotherReg (C->getType ());
307       BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg)
308         .addSImm (((uint32_t) Val) >> 10);
309       BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (TmpReg)
310         .addSImm (((uint32_t) Val) & 0x03ff);
311       return;
312     }
313   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
314     // We need to spill the constant to memory...
315     MachineConstantPool *CP = F->getConstantPool();
316     unsigned CPI = CP->getConstantPoolIndex(CFP);
317     const Type *Ty = CFP->getType();
318     unsigned TmpReg = makeAnotherReg (Type::UIntTy);
319     unsigned AddrReg = makeAnotherReg (Type::UIntTy);
320
321     assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
322     unsigned LoadOpcode = Ty == Type::FloatTy ? V8::LDFri : V8::LDDFri;
323     BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg).addConstantPoolIndex (CPI);
324     BuildMI (*MBB, IP, V8::ORri, 2, AddrReg).addReg (TmpReg)
325       .addConstantPoolIndex (CPI);
326     BuildMI (*MBB, IP, LoadOpcode, 2, R).addReg (AddrReg).addSImm (0);
327   } else if (isa<ConstantPointerNull>(C)) {
328     // Copy zero (null pointer) to the register.
329     BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (V8::G0).addSImm (0);
330   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
331     // Copy it with a SETHI/OR pair; the JIT + asmwriter should recognize
332     // that SETHI %reg,global == SETHI %reg,%hi(global) and 
333     // OR %reg,global,%reg == OR %reg,%lo(global),%reg.
334     unsigned TmpReg = makeAnotherReg (C->getType ());
335     BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg).addGlobalAddress(GV);
336     BuildMI (*MBB, IP, V8::ORri, 2, R).addReg(TmpReg).addGlobalAddress(GV);
337   } else {
338     std::cerr << "Offending constant: " << *C << "\n";
339     assert (0 && "Can't copy this kind of constant into register yet");
340   }
341 }
342
343 void V8ISel::LoadArgumentsToVirtualRegs (Function *LF) {
344   static const unsigned IncomingArgRegs[] = { V8::I0, V8::I1, V8::I2,
345     V8::I3, V8::I4, V8::I5 };
346
347   // Add IMPLICIT_DEFs of input regs.
348   unsigned ArgNo = 0;
349   for (Function::aiterator I = LF->abegin(), E = LF->aend();
350        I != E && ArgNo < 6; ++I, ++ArgNo) {
351     switch (getClassB(I->getType())) {
352     case cByte:
353     case cShort:
354     case cInt:
355     case cFloat:
356       BuildMI(BB, V8::IMPLICIT_DEF, 0, IncomingArgRegs[ArgNo]);
357       break;
358     case cDouble:
359     case cLong:
360       // Double and Long use register pairs.
361       BuildMI(BB, V8::IMPLICIT_DEF, 0, IncomingArgRegs[ArgNo]);
362       ++ArgNo;
363       if (ArgNo < 6)
364         BuildMI(BB, V8::IMPLICIT_DEF, 0, IncomingArgRegs[ArgNo]);
365       break;
366     default:
367       assert (0 && "type not handled");
368       return;
369     }
370   }
371
372   const unsigned *IAREnd = &IncomingArgRegs[6];
373   const unsigned *IAR = &IncomingArgRegs[0];
374   unsigned ArgOffset = 68;
375
376   // Store registers onto stack if this is a varargs function. 
377   // FIXME: This doesn't really pertain to "loading arguments into
378   // virtual registers", so it's not clear that it really belongs here.
379   // FIXME: We could avoid storing any args onto the stack that don't 
380   // need to be in memory, because they come before the ellipsis in the
381   // parameter list (and thus could never be accessed through va_arg).
382   if (LF->getFunctionType ()->isVarArg ()) {
383     for (unsigned i = 0; i < 6; ++i) {
384       int FI = F->getFrameInfo()->CreateFixedObject(4, ArgOffset);
385       assert (IAR != IAREnd
386               && "About to dereference past end of IncomingArgRegs");
387       BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (0).addReg (*IAR++);
388       ArgOffset += 4;
389     }
390     // Reset the pointers now that we're done.
391     ArgOffset = 68;
392     IAR = &IncomingArgRegs[0];
393   }
394
395   // Copy args out of their incoming hard regs or stack slots into virtual regs.
396   for (Function::aiterator I = LF->abegin(), E = LF->aend(); I != E; ++I) {
397     Argument &A = *I;
398     unsigned ArgReg = getReg (A);
399     if (getClassB (A.getType ()) < cLong) {
400       // Get it out of the incoming arg register
401       if (ArgOffset < 92) {
402         assert (IAR != IAREnd
403                 && "About to dereference past end of IncomingArgRegs");
404         BuildMI (BB, V8::ORrr, 2, ArgReg).addReg (V8::G0).addReg (*IAR++);
405       } else {
406         int FI = F->getFrameInfo()->CreateFixedObject(4, ArgOffset);
407         BuildMI (BB, V8::LD, 3, ArgReg).addFrameIndex (FI).addSImm (0);
408       }
409       ArgOffset += 4;
410     } else if (getClassB (A.getType ()) == cFloat) {
411       if (ArgOffset < 92) {
412         // Single-fp args are passed in integer registers; go through
413         // memory to get them out of integer registers and back into fp. (Bleh!)
414         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
415         int FI = F->getFrameInfo()->CreateStackObject(4, FltAlign);
416         assert (IAR != IAREnd
417                 && "About to dereference past end of IncomingArgRegs");
418         BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (0).addReg (*IAR++);
419         BuildMI (BB, V8::LDFri, 2, ArgReg).addFrameIndex (FI).addSImm (0);
420       } else {
421         int FI = F->getFrameInfo()->CreateFixedObject(4, ArgOffset);
422         BuildMI (BB, V8::LDFri, 3, ArgReg).addFrameIndex (FI).addSImm (0);
423       }
424       ArgOffset += 4;
425     } else if (getClassB (A.getType ()) == cDouble) {
426       // Double-fp args are passed in pairs of integer registers; go through
427       // memory to get them out of integer registers and back into fp. (Bleh!)
428       // We'd like to 'ldd' these right out of the incoming-args area,
429       // but it might not be 8-byte aligned (e.g., call x(int x, double d)).
430       unsigned DblAlign = TM.getTargetData().getDoubleAlignment();
431       int FI = F->getFrameInfo()->CreateStackObject(8, DblAlign);
432       if (ArgOffset < 92 && IAR != IAREnd) {
433         BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (0).addReg (*IAR++);
434       } else {
435         unsigned TempReg = makeAnotherReg (Type::IntTy);
436         BuildMI (BB, V8::LD, 2, TempReg).addFrameIndex (FI).addSImm (0);
437         BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (0).addReg (TempReg);
438       }
439       ArgOffset += 4;
440       if (ArgOffset < 92 && IAR != IAREnd) {
441         BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (4).addReg (*IAR++);
442       } else {
443         unsigned TempReg = makeAnotherReg (Type::IntTy);
444         BuildMI (BB, V8::LD, 2, TempReg).addFrameIndex (FI).addSImm (4);
445         BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (4).addReg (TempReg);
446       }
447       ArgOffset += 4;
448       BuildMI (BB, V8::LDDFri, 2, ArgReg).addFrameIndex (FI).addSImm (0);
449     } else if (getClassB (A.getType ()) == cLong) {
450       // do the first half...
451       if (ArgOffset < 92) {
452         assert (IAR != IAREnd
453                 && "About to dereference past end of IncomingArgRegs");
454         BuildMI (BB, V8::ORrr, 2, ArgReg).addReg (V8::G0).addReg (*IAR++);
455       } else {
456         int FI = F->getFrameInfo()->CreateFixedObject(4, ArgOffset);
457         BuildMI (BB, V8::LD, 2, ArgReg).addFrameIndex (FI).addSImm (0);
458       }
459       ArgOffset += 4;
460       // ...then do the second half
461       if (ArgOffset < 92) {
462         assert (IAR != IAREnd
463                 && "About to dereference past end of IncomingArgRegs");
464         BuildMI (BB, V8::ORrr, 2, ArgReg+1).addReg (V8::G0).addReg (*IAR++);
465       } else {
466         int FI = F->getFrameInfo()->CreateFixedObject(4, ArgOffset);
467         BuildMI (BB, V8::LD, 2, ArgReg+1).addFrameIndex (FI).addSImm (0);
468       }
469       ArgOffset += 4;
470     } else {
471       assert (0 && "Unknown class?!");
472     }
473   }
474
475   // If the function takes variable number of arguments, remember the fp
476   // offset for the start of the first vararg value... this is used to expand
477   // llvm.va_start.
478   if (LF->getFunctionType ()->isVarArg ())
479     VarArgsOffset = ArgOffset;
480 }
481
482 void V8ISel::SelectPHINodes() {
483   const TargetInstrInfo &TII = *TM.getInstrInfo();
484   const Function &LF = *F->getFunction();  // The LLVM function...
485   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
486     const BasicBlock *BB = I;
487     MachineBasicBlock &MBB = *MBBMap[I];
488
489     // Loop over all of the PHI nodes in the LLVM basic block...
490     MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
491     for (BasicBlock::const_iterator I = BB->begin();
492          PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
493
494       // Create a new machine instr PHI node, and insert it.
495       unsigned PHIReg = getReg(*PN);
496       MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
497                                     V8::PHI, PN->getNumOperands(), PHIReg);
498
499       MachineInstr *LongPhiMI = 0;
500       if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
501         LongPhiMI = BuildMI(MBB, PHIInsertPoint,
502                             V8::PHI, PN->getNumOperands(), PHIReg+1);
503
504       // PHIValues - Map of blocks to incoming virtual registers.  We use this
505       // so that we only initialize one incoming value for a particular block,
506       // even if the block has multiple entries in the PHI node.
507       //
508       std::map<MachineBasicBlock*, unsigned> PHIValues;
509
510       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
511         MachineBasicBlock *PredMBB = 0;
512         for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
513              PE = MBB.pred_end (); PI != PE; ++PI)
514           if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
515             PredMBB = *PI;
516             break;
517           }
518         assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
519         
520         unsigned ValReg;
521         std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
522           PHIValues.lower_bound(PredMBB);
523
524         if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
525           // We already inserted an initialization of the register for this
526           // predecessor.  Recycle it.
527           ValReg = EntryIt->second;
528
529         } else {        
530           // Get the incoming value into a virtual register.
531           //
532           Value *Val = PN->getIncomingValue(i);
533
534           // If this is a constant or GlobalValue, we may have to insert code
535           // into the basic block to compute it into a virtual register.
536           if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
537               isa<GlobalValue>(Val)) {
538             // Simple constants get emitted at the end of the basic block,
539             // before any terminator instructions.  We "know" that the code to
540             // move a constant into a register will never clobber any flags.
541             ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
542           } else {
543             // Because we don't want to clobber any values which might be in
544             // physical registers with the computation of this constant (which
545             // might be arbitrarily complex if it is a constant expression),
546             // just insert the computation at the top of the basic block.
547             MachineBasicBlock::iterator PI = PredMBB->begin();
548             
549             // Skip over any PHI nodes though!
550             while (PI != PredMBB->end() && PI->getOpcode() == V8::PHI)
551               ++PI;
552             
553             ValReg = getReg(Val, PredMBB, PI);
554           }
555
556           // Remember that we inserted a value for this PHI for this predecessor
557           PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
558         }
559
560         PhiMI->addRegOperand(ValReg);
561         PhiMI->addMachineBasicBlockOperand(PredMBB);
562         if (LongPhiMI) {
563           LongPhiMI->addRegOperand(ValReg+1);
564           LongPhiMI->addMachineBasicBlockOperand(PredMBB);
565         }
566       }
567
568       // Now that we emitted all of the incoming values for the PHI node, make
569       // sure to reposition the InsertPoint after the PHI that we just added.
570       // This is needed because we might have inserted a constant into this
571       // block, right after the PHI's which is before the old insert point!
572       PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
573       ++PHIInsertPoint;
574     }
575   }
576 }
577
578 bool V8ISel::runOnFunction(Function &Fn) {
579   // First pass over the function, lower any unknown intrinsic functions
580   // with the IntrinsicLowering class.
581   LowerUnknownIntrinsicFunctionCalls(Fn);
582   
583   F = &MachineFunction::construct(&Fn, TM);
584   
585   // Create all of the machine basic blocks for the function...
586   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
587     F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
588   
589   BB = &F->front();
590   
591   // Set up a frame object for the return address.  This is used by the
592   // llvm.returnaddress & llvm.frameaddress intrinisics.
593   //ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
594   
595   // Copy incoming arguments off of the stack and out of fixed registers.
596   LoadArgumentsToVirtualRegs(&Fn);
597   
598   // Instruction select everything except PHI nodes
599   visit(Fn);
600   
601   // Select the PHI nodes
602   SelectPHINodes();
603   
604   RegMap.clear();
605   MBBMap.clear();
606   F = 0;
607   // We always build a machine code representation for the function
608   return true;
609 }
610
611 void V8ISel::visitCastInst(CastInst &I) {
612   Value *Op = I.getOperand(0);
613   unsigned DestReg = getReg(I);
614   MachineBasicBlock::iterator MI = BB->end();
615   emitCastOperation(BB, MI, Op, I.getType(), DestReg);
616 }
617
618 unsigned V8ISel::emitIntegerCast (MachineBasicBlock *BB,
619                               MachineBasicBlock::iterator IP, const Type *oldTy,
620                               unsigned SrcReg, const Type *newTy,
621                               unsigned DestReg) {
622   if (oldTy == newTy) {
623     // No-op cast - just emit a copy; assume the reg. allocator will zap it.
624     BuildMI (*BB, IP, V8::ORrr, 2, DestReg).addReg (V8::G0).addReg(SrcReg);
625     return SrcReg;
626   }
627   // Emit left-shift, then right-shift to sign- or zero-extend.
628   unsigned TmpReg = makeAnotherReg (newTy);
629   unsigned shiftWidth = 32 - (8 * TM.getTargetData ().getTypeSize (newTy));
630   BuildMI (*BB, IP, V8::SLLri, 2, TmpReg).addZImm (shiftWidth).addReg(SrcReg);
631   if (newTy->isSigned ()) { // sign-extend with SRA
632     BuildMI(*BB, IP, V8::SRAri, 2, DestReg).addZImm (shiftWidth).addReg(TmpReg);
633   } else { // zero-extend with SRL
634     BuildMI(*BB, IP, V8::SRLri, 2, DestReg).addZImm (shiftWidth).addReg(TmpReg);
635   }
636   // Return the temp reg. in case this is one half of a cast to long.
637   return TmpReg;
638 }
639
640 void V8ISel::emitFPToIntegerCast (MachineBasicBlock *BB,
641                                   MachineBasicBlock::iterator IP,
642                                   const Type *oldTy, unsigned SrcReg,
643                                   const Type *newTy, unsigned DestReg) {
644   unsigned FPCastOpcode, FPStoreOpcode, FPSize, FPAlign;
645   unsigned oldTyClass = getClassB(oldTy);
646   if (oldTyClass == cFloat) { 
647     FPCastOpcode = V8::FSTOI; FPStoreOpcode = V8::STFri; FPSize = 4; 
648     FPAlign = TM.getTargetData().getFloatAlignment();
649   } else { // it's a double
650     FPCastOpcode = V8::FDTOI; FPStoreOpcode = V8::STDFri; FPSize = 8; 
651     FPAlign = TM.getTargetData().getDoubleAlignment();
652   }
653   unsigned TempReg = makeAnotherReg (oldTy);
654   BuildMI (*BB, IP, FPCastOpcode, 1, TempReg).addReg (SrcReg);
655   int FI = F->getFrameInfo()->CreateStackObject(FPSize, FPAlign);
656   BuildMI (*BB, IP, FPStoreOpcode, 3).addFrameIndex (FI).addSImm (0)
657     .addReg (TempReg);
658   unsigned TempReg2 = makeAnotherReg (newTy);
659   BuildMI (*BB, IP, V8::LD, 3, TempReg2).addFrameIndex (FI).addSImm (0);
660   emitIntegerCast (BB, IP, Type::IntTy, TempReg2, newTy, DestReg);
661 }
662
663 /// emitCastOperation - Common code shared between visitCastInst and constant
664 /// expression cast support.
665 ///
666 void V8ISel::emitCastOperation(MachineBasicBlock *BB,
667                                MachineBasicBlock::iterator IP, Value *Src,
668                                const Type *DestTy, unsigned DestReg) {
669   const Type *SrcTy = Src->getType();
670   unsigned SrcClass = getClassB(SrcTy);
671   unsigned DestClass = getClassB(DestTy);
672   unsigned SrcReg = getReg(Src, BB, IP);
673
674   const Type *oldTy = SrcTy;
675   const Type *newTy = DestTy;
676   unsigned oldTyClass = SrcClass;
677   unsigned newTyClass = DestClass;
678
679   if (oldTyClass < cLong && newTyClass < cLong) {
680     emitIntegerCast (BB, IP, oldTy, SrcReg, newTy, DestReg);
681   } else switch (newTyClass) {
682     case cByte:
683     case cShort:
684     case cInt:
685       switch (oldTyClass) {
686       case cLong: 
687         // Treat it like a cast from the lower half of the value.
688         emitIntegerCast (BB, IP, Type::IntTy, SrcReg+1, newTy, DestReg);
689         break;
690       case cFloat: 
691       case cDouble:
692         emitFPToIntegerCast (BB, IP, oldTy, SrcReg, newTy, DestReg);
693         break;
694       default: goto not_yet;
695       }
696       return;
697
698     case cFloat:
699       switch (oldTyClass) {
700       case cLong: goto not_yet;
701       case cFloat:
702         BuildMI (*BB, IP, V8::FMOVS, 1, DestReg).addReg (SrcReg);
703         break;
704       case cDouble:
705         BuildMI (*BB, IP, V8::FDTOS, 1, DestReg).addReg (SrcReg);
706         break;
707       default: {
708         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
709         // cast integer type to float.  Store it to a stack slot and then load
710         // it using ldf into a floating point register. then do fitos.
711         unsigned TmpReg = makeAnotherReg (newTy);
712         int FI = F->getFrameInfo()->CreateStackObject(4, FltAlign);
713         BuildMI (*BB, IP, V8::ST, 3).addFrameIndex (FI).addSImm (0)
714           .addReg (SrcReg);
715         BuildMI (*BB, IP, V8::LDFri, 2, TmpReg).addFrameIndex (FI).addSImm (0);
716         BuildMI (*BB, IP, V8::FITOS, 1, DestReg).addReg(TmpReg);
717         break;
718       }
719       }
720       return;
721
722     case cDouble:
723       switch (oldTyClass) {
724       case cLong: goto not_yet;
725       case cFloat:
726         BuildMI (*BB, IP, V8::FSTOD, 1, DestReg).addReg (SrcReg);
727         break;
728       case cDouble: // use double move pseudo-instr
729         BuildMI (*BB, IP, V8::FpMOVD, 1, DestReg).addReg (SrcReg);
730         break;
731       default: {
732         unsigned DoubleAlignment = TM.getTargetData().getDoubleAlignment();
733         unsigned TmpReg = makeAnotherReg (newTy);
734         int FI = F->getFrameInfo()->CreateStackObject(8, DoubleAlignment);
735         BuildMI (*BB, IP, V8::ST, 3).addFrameIndex (FI).addSImm (0)
736           .addReg (SrcReg);
737         BuildMI (*BB, IP, V8::LDDFri, 2, TmpReg).addFrameIndex (FI).addSImm (0);
738         BuildMI (*BB, IP, V8::FITOD, 1, DestReg).addReg(TmpReg);
739         break;
740       }
741       }
742       return;
743
744     case cLong:
745       switch (oldTyClass) {
746       case cByte:
747       case cShort:
748       case cInt: {
749         // Cast to (u)int in the bottom half, and sign(zero) extend in the top
750         // half.
751         const Type *OldHalfTy = oldTy->isSigned() ? Type::IntTy : Type::UIntTy;
752         const Type *NewHalfTy = newTy->isSigned() ? Type::IntTy : Type::UIntTy;
753         unsigned TempReg = emitIntegerCast (BB, IP, OldHalfTy, SrcReg,
754                                             NewHalfTy, DestReg+1);
755         if (newTy->isSigned ()) {
756           BuildMI (*BB, IP, V8::SRAri, 2, DestReg).addReg (TempReg) 
757             .addZImm (31);
758         } else {
759           BuildMI (*BB, IP, V8::ORrr, 2, DestReg).addReg (V8::G0) 
760             .addReg (V8::G0);
761         }
762         break;
763       }
764       case cLong:
765         // Just copy both halves.
766         BuildMI (*BB, IP, V8::ORrr, 2, DestReg).addReg (V8::G0).addReg (SrcReg);
767         BuildMI (*BB, IP, V8::ORrr, 2, DestReg+1).addReg (V8::G0)
768           .addReg (SrcReg+1);
769         break;
770       default: goto not_yet;
771       }
772       return;
773
774     default: goto not_yet;
775   }
776   return;
777 not_yet:
778   std::cerr << "Sorry, cast still unsupported: SrcTy = " << *SrcTy
779             << ", DestTy = " << *DestTy << "\n";
780   abort ();
781 }
782
783 void V8ISel::visitLoadInst(LoadInst &I) {
784   unsigned DestReg = getReg (I);
785   unsigned PtrReg = getReg (I.getOperand (0));
786   switch (getClassB (I.getType ())) {
787    case cByte:
788     if (I.getType ()->isSigned ())
789       BuildMI (BB, V8::LDSB, 2, DestReg).addReg (PtrReg).addSImm(0);
790     else
791       BuildMI (BB, V8::LDUB, 2, DestReg).addReg (PtrReg).addSImm(0);
792     return;
793    case cShort:
794     if (I.getType ()->isSigned ())
795       BuildMI (BB, V8::LDSH, 2, DestReg).addReg (PtrReg).addSImm(0);
796     else
797       BuildMI (BB, V8::LDUH, 2, DestReg).addReg (PtrReg).addSImm(0);
798     return;
799    case cInt:
800     BuildMI (BB, V8::LD, 2, DestReg).addReg (PtrReg).addSImm(0);
801     return;
802    case cLong:
803     BuildMI (BB, V8::LD, 2, DestReg).addReg (PtrReg).addSImm(0);
804     BuildMI (BB, V8::LD, 2, DestReg+1).addReg (PtrReg).addSImm(4);
805     return;
806    case cFloat:
807     BuildMI (BB, V8::LDFri, 2, DestReg).addReg (PtrReg).addSImm(0);
808     return;
809    case cDouble:
810     BuildMI (BB, V8::LDDFri, 2, DestReg).addReg (PtrReg).addSImm(0);
811     return;
812    default:
813     std::cerr << "Load instruction not handled: " << I;
814     abort ();
815     return;
816   }
817 }
818
819 void V8ISel::visitStoreInst(StoreInst &I) {
820   Value *SrcVal = I.getOperand (0);
821   unsigned SrcReg = getReg (SrcVal);
822   unsigned PtrReg = getReg (I.getOperand (1));
823   switch (getClassB (SrcVal->getType ())) {
824    case cByte:
825     BuildMI (BB, V8::STB, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
826     return;
827    case cShort:
828     BuildMI (BB, V8::STH, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
829     return;
830    case cInt:
831     BuildMI (BB, V8::ST, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
832     return;
833    case cLong:
834     BuildMI (BB, V8::ST, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
835     BuildMI (BB, V8::ST, 3).addReg (PtrReg).addSImm (4).addReg (SrcReg+1);
836     return;
837    case cFloat:
838     BuildMI (BB, V8::STFri, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
839     return;
840    case cDouble:
841     BuildMI (BB, V8::STDFri, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
842     return;
843    default:
844     std::cerr << "Store instruction not handled: " << I;
845     abort ();
846     return;
847   }
848 }
849
850 void V8ISel::visitCallInst(CallInst &I) {
851   MachineInstr *TheCall;
852   // Is it an intrinsic function call?
853   if (Function *F = I.getCalledFunction()) {
854     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
855       visitIntrinsicCall(ID, I);   // Special intrinsics are not handled here
856       return;
857     }
858   }
859
860   unsigned extraStack = 0;
861   // How much extra call stack will we need?
862   for (unsigned i = 7; i < I.getNumOperands (); ++i) {
863     switch (getClassB (I.getOperand (i)->getType ())) {
864       case cLong: extraStack += 8; break;
865       case cFloat: extraStack += 4; break;
866       case cDouble: extraStack += 8; break;
867       default: extraStack += 4; break;
868     }
869   }
870   // Round up extra stack size to the nearest doubleword.
871   if (extraStack) { extraStack = (extraStack + 7) & ~7; }
872
873   // Deal with args
874   static const unsigned OutgoingArgRegs[] = { V8::O0, V8::O1, V8::O2, V8::O3,
875     V8::O4, V8::O5 };
876   const unsigned *OAREnd = &OutgoingArgRegs[6];
877   const unsigned *OAR = &OutgoingArgRegs[0];
878   unsigned ArgOffset = 68;
879   if (extraStack) BuildMI (BB, V8::ADJCALLSTACKDOWN, 1).addImm (extraStack);
880   for (unsigned i = 1; i < I.getNumOperands (); ++i) {
881     unsigned ArgReg = getReg (I.getOperand (i));
882     if (getClassB (I.getOperand (i)->getType ()) < cLong) {
883       // Schlep it over into the incoming arg register
884       if (ArgOffset < 92) {
885         assert (OAR != OAREnd && "About to dereference past end of OutgoingArgRegs");
886         BuildMI (BB, V8::ORrr, 2, *OAR++).addReg (V8::G0).addReg (ArgReg);
887       } else {
888         BuildMI (BB, V8::ST, 3).addReg (V8::SP).addSImm (ArgOffset).addReg (ArgReg);
889       }
890       ArgOffset += 4;
891     } else if (getClassB (I.getOperand (i)->getType ()) == cFloat) {
892       if (ArgOffset < 92) {
893         // Single-fp args are passed in integer registers; go through
894         // memory to get them out of FP registers. (Bleh!)
895         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
896         int FI = F->getFrameInfo()->CreateStackObject(4, FltAlign);
897         BuildMI (BB, V8::STFri, 3).addFrameIndex (FI).addSImm (0).addReg (ArgReg);
898         assert (OAR != OAREnd && "About to dereference past end of OutgoingArgRegs");
899         BuildMI (BB, V8::LD, 2, *OAR++).addFrameIndex (FI).addSImm (0);
900       } else {
901         BuildMI (BB, V8::STFri, 3).addReg (V8::SP).addSImm (ArgOffset).addReg (ArgReg);
902       }
903       ArgOffset += 4;
904     } else if (getClassB (I.getOperand (i)->getType ()) == cDouble) {
905       // Double-fp args are passed in pairs of integer registers; go through
906       // memory to get them out of FP registers. (Bleh!)
907       // We'd like to 'std' these right onto the outgoing-args area, but it might
908       // not be 8-byte aligned (e.g., call x(int x, double d)). sigh.
909       unsigned DblAlign = TM.getTargetData().getDoubleAlignment();
910       int FI = F->getFrameInfo()->CreateStackObject(8, DblAlign);
911       BuildMI (BB, V8::STDFri, 3).addFrameIndex (FI).addSImm (0).addReg (ArgReg);
912       if (ArgOffset < 92 && OAR != OAREnd) {
913         assert (OAR != OAREnd && "About to dereference past end of OutgoingArgRegs");
914         BuildMI (BB, V8::LD, 2, *OAR++).addFrameIndex (FI).addSImm (0);
915       } else {
916         unsigned TempReg = makeAnotherReg (Type::IntTy);
917         BuildMI (BB, V8::LD, 2, TempReg).addFrameIndex (FI).addSImm (0);
918         BuildMI (BB, V8::ST, 3).addReg (V8::SP).addSImm (ArgOffset).addReg (TempReg);
919       }
920       ArgOffset += 4;
921       if (ArgOffset < 92 && OAR != OAREnd) {
922         assert (OAR != OAREnd && "About to dereference past end of OutgoingArgRegs");
923         BuildMI (BB, V8::LD, 2, *OAR++).addFrameIndex (FI).addSImm (4);
924       } else {
925         unsigned TempReg = makeAnotherReg (Type::IntTy);
926         BuildMI (BB, V8::LD, 2, TempReg).addFrameIndex (FI).addSImm (4);
927         BuildMI (BB, V8::ST, 3).addReg (V8::SP).addSImm (ArgOffset).addReg (TempReg);
928       }
929       ArgOffset += 4;
930     } else if (getClassB (I.getOperand (i)->getType ()) == cLong) {
931       // do the first half...
932       if (ArgOffset < 92) {
933         assert (OAR != OAREnd && "About to dereference past end of OutgoingArgRegs");
934         BuildMI (BB, V8::ORrr, 2, *OAR++).addReg (V8::G0).addReg (ArgReg);
935       } else {
936         BuildMI (BB, V8::ST, 3).addReg (V8::SP).addSImm (ArgOffset).addReg (ArgReg);
937       }
938       ArgOffset += 4;
939       // ...then do the second half
940       if (ArgOffset < 92) {
941         assert (OAR != OAREnd && "About to dereference past end of OutgoingArgRegs");
942         BuildMI (BB, V8::ORrr, 2, *OAR++).addReg (V8::G0).addReg (ArgReg+1);
943       } else {
944         BuildMI (BB, V8::ST, 3).addReg (V8::SP).addSImm (ArgOffset).addReg (ArgReg+1);
945       }
946       ArgOffset += 4;
947     } else {
948       assert (0 && "Unknown class?!");
949     }
950   }
951
952   // Emit call instruction
953   if (Function *F = I.getCalledFunction ()) {
954     BuildMI (BB, V8::CALL, 1).addGlobalAddress (F, true);
955   } else {  // Emit an indirect call...
956     unsigned Reg = getReg (I.getCalledValue ());
957     BuildMI (BB, V8::JMPLrr, 3, V8::O7).addReg (Reg).addReg (V8::G0);
958   }
959
960   if (extraStack) BuildMI (BB, V8::ADJCALLSTACKUP, 1).addImm (extraStack);
961
962   // Deal w/ return value: schlep it over into the destination register
963   if (I.getType () == Type::VoidTy)
964     return;
965   unsigned DestReg = getReg (I);
966   switch (getClassB (I.getType ())) {
967     case cByte:
968     case cShort:
969     case cInt:
970       BuildMI (BB, V8::ORrr, 2, DestReg).addReg(V8::G0).addReg(V8::O0);
971       break;
972     case cFloat:
973       BuildMI (BB, V8::FMOVS, 2, DestReg).addReg(V8::F0);
974       break;
975     case cDouble:
976       BuildMI (BB, V8::FpMOVD, 2, DestReg).addReg(V8::D0);
977       break;
978     case cLong:
979       BuildMI (BB, V8::ORrr, 2, DestReg).addReg(V8::G0).addReg(V8::O0);
980       BuildMI (BB, V8::ORrr, 2, DestReg+1).addReg(V8::G0).addReg(V8::O1);
981       break;
982     default:
983       std::cerr << "Return type of call instruction not handled: " << I;
984       abort ();
985   }
986 }
987
988 void V8ISel::visitReturnInst(ReturnInst &I) {
989   if (I.getNumOperands () == 1) {
990     unsigned RetValReg = getReg (I.getOperand (0));
991     switch (getClassB (I.getOperand (0)->getType ())) {
992       case cByte:
993       case cShort:
994       case cInt:
995         // Schlep it over into i0 (where it will become o0 after restore).
996         BuildMI (BB, V8::ORrr, 2, V8::I0).addReg(V8::G0).addReg(RetValReg);
997         break;
998       case cFloat:
999         BuildMI (BB, V8::FMOVS, 1, V8::F0).addReg(RetValReg);
1000         break;
1001       case cDouble:
1002         BuildMI (BB, V8::FpMOVD, 1, V8::D0).addReg(RetValReg);
1003         break;
1004       case cLong:
1005         BuildMI (BB, V8::ORrr, 2, V8::I0).addReg(V8::G0).addReg(RetValReg);
1006         BuildMI (BB, V8::ORrr, 2, V8::I1).addReg(V8::G0).addReg(RetValReg+1);
1007         break;
1008       default:
1009         std::cerr << "Return instruction of this type not handled: " << I;
1010         abort ();
1011     }
1012   }
1013
1014   // Just emit a 'retl' instruction to return.
1015   BuildMI(BB, V8::RETL, 0);
1016   return;
1017 }
1018
1019 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1020   Function::iterator I = BB; ++I;  // Get iterator to next block
1021   return I != BB->getParent()->end() ? &*I : 0;
1022 }
1023
1024 /// visitBranchInst - Handles conditional and unconditional branches.
1025 ///
1026 void V8ISel::visitBranchInst(BranchInst &I) {
1027   BasicBlock *takenSucc = I.getSuccessor (0);
1028   MachineBasicBlock *takenSuccMBB = MBBMap[takenSucc];
1029   BB->addSuccessor (takenSuccMBB);
1030   if (I.isConditional()) {  // conditional branch
1031     BasicBlock *notTakenSucc = I.getSuccessor (1);
1032     MachineBasicBlock *notTakenSuccMBB = MBBMap[notTakenSucc];
1033     BB->addSuccessor (notTakenSuccMBB);
1034
1035     // CondReg=(<condition>);
1036     // If (CondReg==0) goto notTakenSuccMBB;
1037     unsigned CondReg = getReg (I.getCondition ());
1038     BuildMI (BB, V8::CMPri, 2).addSImm (0).addReg (CondReg);
1039     BuildMI (BB, V8::BE, 1).addMBB (notTakenSuccMBB);
1040   }
1041   // goto takenSuccMBB;
1042   BuildMI (BB, V8::BA, 1).addMBB (takenSuccMBB);
1043 }
1044
1045 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
1046 /// constant expression GEP support.
1047 ///
1048 void V8ISel::emitGEPOperation (MachineBasicBlock *MBB,
1049                                MachineBasicBlock::iterator IP,
1050                                Value *Src, User::op_iterator IdxBegin,
1051                                User::op_iterator IdxEnd, unsigned TargetReg) {
1052   const TargetData &TD = TM.getTargetData ();
1053   const Type *Ty = Src->getType ();
1054   unsigned basePtrReg = getReg (Src, MBB, IP);
1055
1056   // GEPs have zero or more indices; we must perform a struct access
1057   // or array access for each one.
1058   for (GetElementPtrInst::op_iterator oi = IdxBegin, oe = IdxEnd; oi != oe;
1059        ++oi) {
1060     Value *idx = *oi;
1061     unsigned nextBasePtrReg = makeAnotherReg (Type::UIntTy);
1062     if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
1063       // It's a struct access.  idx is the index into the structure,
1064       // which names the field. Use the TargetData structure to
1065       // pick out what the layout of the structure is in memory.
1066       // Use the (constant) structure index's value to find the
1067       // right byte offset from the StructLayout class's list of
1068       // structure member offsets.
1069       unsigned fieldIndex = cast<ConstantUInt> (idx)->getValue ();
1070       unsigned memberOffset =
1071         TD.getStructLayout (StTy)->MemberOffsets[fieldIndex];
1072       // Emit an ADD to add memberOffset to the basePtr.
1073       BuildMI (*MBB, IP, V8::ADDri, 2,
1074                nextBasePtrReg).addReg (basePtrReg).addZImm (memberOffset);
1075       // The next type is the member of the structure selected by the
1076       // index.
1077       Ty = StTy->getElementType (fieldIndex);
1078     } else if (const SequentialType *SqTy = dyn_cast<SequentialType> (Ty)) {
1079       // It's an array or pointer access: [ArraySize x ElementType].
1080       // We want to add basePtrReg to (idxReg * sizeof ElementType). First, we
1081       // must find the size of the pointed-to type (Not coincidentally, the next
1082       // type is the type of the elements in the array).
1083       Ty = SqTy->getElementType ();
1084       unsigned elementSize = TD.getTypeSize (Ty);
1085       unsigned idxReg = getReg (idx, MBB, IP);
1086       unsigned OffsetReg = makeAnotherReg (Type::IntTy);
1087       unsigned elementSizeReg = makeAnotherReg (Type::UIntTy);
1088       copyConstantToRegister (MBB, IP,
1089         ConstantUInt::get(Type::UIntTy, elementSize), elementSizeReg);
1090       // Emit a SMUL to multiply the register holding the index by
1091       // elementSize, putting the result in OffsetReg.
1092       BuildMI (*MBB, IP, V8::SMULrr, 2,
1093                OffsetReg).addReg (elementSizeReg).addReg (idxReg);
1094       // Emit an ADD to add OffsetReg to the basePtr.
1095       BuildMI (*MBB, IP, V8::ADDrr, 2,
1096                nextBasePtrReg).addReg (basePtrReg).addReg (OffsetReg);
1097     }
1098     basePtrReg = nextBasePtrReg;
1099   }
1100   // After we have processed all the indices, the result is left in
1101   // basePtrReg.  Move it to the register where we were expected to
1102   // put the answer.
1103   BuildMI (BB, V8::ORrr, 1, TargetReg).addReg (V8::G0).addReg (basePtrReg);
1104 }
1105
1106 void V8ISel::visitGetElementPtrInst (GetElementPtrInst &I) {
1107   unsigned outputReg = getReg (I);
1108   emitGEPOperation (BB, BB->end (), I.getOperand (0),
1109                     I.op_begin ()+1, I.op_end (), outputReg);
1110 }
1111
1112
1113 void V8ISel::visitBinaryOperator (Instruction &I) {
1114   unsigned DestReg = getReg (I);
1115   unsigned Op0Reg = getReg (I.getOperand (0));
1116   unsigned Op1Reg = getReg (I.getOperand (1));
1117
1118   unsigned Class = getClassB (I.getType());
1119   unsigned OpCase = ~0;
1120
1121   if (Class > cLong) {
1122     switch (I.getOpcode ()) {
1123     case Instruction::Add: OpCase = 0; break;
1124     case Instruction::Sub: OpCase = 1; break;
1125     case Instruction::Mul: OpCase = 2; break;
1126     case Instruction::Div: OpCase = 3; break;
1127     default: visitInstruction (I); return;
1128     }
1129     static unsigned Opcodes[] = { V8::FADDS, V8::FADDD,
1130                                   V8::FSUBS, V8::FSUBD,
1131                                   V8::FMULS, V8::FMULD,
1132                                   V8::FDIVS, V8::FDIVD };
1133     BuildMI (BB, Opcodes[2*OpCase + (Class - cFloat)], 2, DestReg)
1134       .addReg (Op0Reg).addReg (Op1Reg);
1135     return;
1136   }
1137
1138   unsigned ResultReg = DestReg;
1139   if (Class != cInt && Class != cLong)
1140     ResultReg = makeAnotherReg (I.getType ());
1141
1142   if (Class == cLong) {
1143     DEBUG (std::cerr << "Class = cLong\n");
1144     DEBUG (std::cerr << "Op0Reg = " << Op0Reg << ", " << Op0Reg+1 << "\n");
1145     DEBUG (std::cerr << "Op1Reg = " << Op1Reg << ", " << Op1Reg+1 << "\n");
1146     DEBUG (std::cerr << "ResultReg = " << ResultReg << ", " << ResultReg+1 << "\n");
1147     DEBUG (std::cerr << "DestReg = " << DestReg << ", " << DestReg+1 <<  "\n");
1148   }
1149
1150   // FIXME: support long, ulong.
1151   switch (I.getOpcode ()) {
1152   case Instruction::Add: OpCase = 0; break;
1153   case Instruction::Sub: OpCase = 1; break;
1154   case Instruction::Mul: OpCase = 2; break;
1155   case Instruction::And: OpCase = 3; break;
1156   case Instruction::Or:  OpCase = 4; break;
1157   case Instruction::Xor: OpCase = 5; break;
1158   case Instruction::Shl: OpCase = 6; break;
1159   case Instruction::Shr: OpCase = 7+I.getType()->isSigned(); break;
1160
1161   case Instruction::Div:
1162   case Instruction::Rem: {
1163     unsigned Dest = ResultReg;
1164     if (I.getOpcode() == Instruction::Rem)
1165       Dest = makeAnotherReg(I.getType());
1166
1167     // FIXME: this is probably only right for 32 bit operands.
1168     if (I.getType ()->isSigned()) {
1169       unsigned Tmp = makeAnotherReg (I.getType ());
1170       // Sign extend into the Y register
1171       BuildMI (BB, V8::SRAri, 2, Tmp).addReg (Op0Reg).addZImm (31);
1172       BuildMI (BB, V8::WRrr, 2, V8::Y).addReg (Tmp).addReg (V8::G0);
1173       BuildMI (BB, V8::SDIVrr, 2, Dest).addReg (Op0Reg).addReg (Op1Reg);
1174     } else {
1175       // Zero extend into the Y register, ie, just set it to zero
1176       BuildMI (BB, V8::WRrr, 2, V8::Y).addReg (V8::G0).addReg (V8::G0);
1177       BuildMI (BB, V8::UDIVrr, 2, Dest).addReg (Op0Reg).addReg (Op1Reg);
1178     }
1179
1180     if (I.getOpcode() == Instruction::Rem) {
1181       unsigned Tmp = makeAnotherReg (I.getType ());
1182       BuildMI (BB, V8::SMULrr, 2, Tmp).addReg(Dest).addReg(Op1Reg);
1183       BuildMI (BB, V8::SUBrr, 2, ResultReg).addReg(Op0Reg).addReg(Tmp);
1184     }
1185     break;
1186   }
1187   default:
1188     visitInstruction (I);
1189     return;
1190   }
1191
1192   static const unsigned Opcodes[] = {
1193     V8::ADDrr, V8::SUBrr, V8::SMULrr, V8::ANDrr, V8::ORrr, V8::XORrr,
1194     V8::SLLrr, V8::SRLrr, V8::SRArr
1195   };
1196   if (OpCase != ~0U) {
1197     BuildMI (BB, Opcodes[OpCase], 2, ResultReg).addReg (Op0Reg).addReg (Op1Reg);
1198   }
1199
1200   switch (getClassB (I.getType ())) {
1201     case cByte: 
1202       if (I.getType ()->isSigned ()) { // add byte
1203         BuildMI (BB, V8::ANDri, 2, DestReg).addReg (ResultReg).addZImm (0xff);
1204       } else { // add ubyte
1205         unsigned TmpReg = makeAnotherReg (I.getType ());
1206         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (24);
1207         BuildMI (BB, V8::SRAri, 2, DestReg).addReg (TmpReg).addZImm (24);
1208       }
1209       break;
1210     case cShort:
1211       if (I.getType ()->isSigned ()) { // add short
1212         unsigned TmpReg = makeAnotherReg (I.getType ());
1213         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (16);
1214         BuildMI (BB, V8::SRAri, 2, DestReg).addReg (TmpReg).addZImm (16);
1215       } else { // add ushort
1216         unsigned TmpReg = makeAnotherReg (I.getType ());
1217         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (16);
1218         BuildMI (BB, V8::SRLri, 2, DestReg).addReg (TmpReg).addZImm (16);
1219       }
1220       break;
1221     case cInt:
1222       // Nothing to do here.
1223       break;
1224     case cLong:
1225       // Only support and, or, xor.
1226       if (OpCase < 3 || OpCase > 5) {
1227         visitInstruction (I);
1228         return;
1229       }
1230       // Do the other half of the value:
1231       BuildMI (BB, Opcodes[OpCase], 2, ResultReg+1).addReg (Op0Reg+1)
1232         .addReg (Op1Reg+1);
1233       break;
1234     default:
1235       visitInstruction (I);
1236   }
1237 }
1238
1239 void V8ISel::visitSetCondInst(SetCondInst &I) {
1240   unsigned Op0Reg = getReg (I.getOperand (0));
1241   unsigned Op1Reg = getReg (I.getOperand (1));
1242   unsigned DestReg = getReg (I);
1243   const Type *Ty = I.getOperand (0)->getType ();
1244   
1245   // Compare the two values.
1246   assert (getClass (Ty) != cLong && "can't setcc on longs yet");
1247   if (getClass (Ty) < cLong) {
1248     BuildMI(BB, V8::SUBCCrr, 2, V8::G0).addReg(Op0Reg).addReg(Op1Reg);
1249   } else if (getClass (Ty) == cFloat) {
1250     BuildMI(BB, V8::FCMPS, 2).addReg(Op0Reg).addReg(Op1Reg);
1251   } else if (getClass (Ty) == cDouble) {
1252     BuildMI(BB, V8::FCMPD, 2).addReg(Op0Reg).addReg(Op1Reg);
1253   }
1254
1255   unsigned BranchIdx;
1256   switch (I.getOpcode()) {
1257   default: assert(0 && "Unknown setcc instruction!");
1258   case Instruction::SetEQ: BranchIdx = 0; break;
1259   case Instruction::SetNE: BranchIdx = 1; break;
1260   case Instruction::SetLT: BranchIdx = 2; break;
1261   case Instruction::SetGT: BranchIdx = 3; break;
1262   case Instruction::SetLE: BranchIdx = 4; break;
1263   case Instruction::SetGE: BranchIdx = 5; break;
1264   }
1265   unsigned Column = 0;
1266   if (Ty->isSigned() && !Ty->isFloatingPoint()) Column = 1;
1267   if (Ty->isFloatingPoint()) Column = 2;
1268   static unsigned OpcodeTab[3*6] = {
1269                                  // LLVM            SparcV8
1270                                  //        unsigned signed  fp
1271     V8::BE,   V8::BE,  V8::FBE,  // seteq = be      be      fbe
1272     V8::BNE,  V8::BNE, V8::FBNE, // setne = bne     bne     fbne
1273     V8::BCS,  V8::BL,  V8::FBL,  // setlt = bcs     bl      fbl
1274     V8::BGU,  V8::BG,  V8::FBG,  // setgt = bgu     bg      fbg
1275     V8::BLEU, V8::BLE, V8::FBLE, // setle = bleu    ble     fble
1276     V8::BCC,  V8::BGE, V8::FBGE  // setge = bcc     bge     fbge
1277   };
1278   unsigned Opcode = OpcodeTab[3*BranchIdx + Column];
1279
1280   MachineBasicBlock *thisMBB = BB;
1281   const BasicBlock *LLVM_BB = BB->getBasicBlock ();
1282   //  thisMBB:
1283   //  ...
1284   //   subcc %reg0, %reg1, %g0
1285   //   bCC copy1MBB
1286   //   ba copy0MBB
1287
1288   // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1289   // if we could insert other, non-terminator instructions after the
1290   // bCC. But MBB->getFirstTerminator() can't understand this.
1291   MachineBasicBlock *copy1MBB = new MachineBasicBlock (LLVM_BB);
1292   F->getBasicBlockList ().push_back (copy1MBB);
1293   BuildMI (BB, Opcode, 1).addMBB (copy1MBB);
1294   MachineBasicBlock *copy0MBB = new MachineBasicBlock (LLVM_BB);
1295   F->getBasicBlockList ().push_back (copy0MBB);
1296   BuildMI (BB, V8::BA, 1).addMBB (copy0MBB);
1297   // Update machine-CFG edges
1298   BB->addSuccessor (copy1MBB);
1299   BB->addSuccessor (copy0MBB);
1300
1301   //  copy0MBB:
1302   //   %FalseValue = or %G0, 0
1303   //   ba sinkMBB
1304   BB = copy0MBB;
1305   unsigned FalseValue = makeAnotherReg (I.getType ());
1306   BuildMI (BB, V8::ORri, 2, FalseValue).addReg (V8::G0).addZImm (0);
1307   MachineBasicBlock *sinkMBB = new MachineBasicBlock (LLVM_BB);
1308   F->getBasicBlockList ().push_back (sinkMBB);
1309   BuildMI (BB, V8::BA, 1).addMBB (sinkMBB);
1310   // Update machine-CFG edges
1311   BB->addSuccessor (sinkMBB);
1312
1313   DEBUG (std::cerr << "thisMBB is at " << (void*)thisMBB << "\n");
1314   DEBUG (std::cerr << "copy1MBB is at " << (void*)copy1MBB << "\n");
1315   DEBUG (std::cerr << "copy0MBB is at " << (void*)copy0MBB << "\n");
1316   DEBUG (std::cerr << "sinkMBB is at " << (void*)sinkMBB << "\n");
1317
1318   //  copy1MBB:
1319   //   %TrueValue = or %G0, 1
1320   //   ba sinkMBB
1321   BB = copy1MBB;
1322   unsigned TrueValue = makeAnotherReg (I.getType ());
1323   BuildMI (BB, V8::ORri, 2, TrueValue).addReg (V8::G0).addZImm (1);
1324   BuildMI (BB, V8::BA, 1).addMBB (sinkMBB);
1325   // Update machine-CFG edges
1326   BB->addSuccessor (sinkMBB);
1327
1328   //  sinkMBB:
1329   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1330   //  ...
1331   BB = sinkMBB;
1332   BuildMI (BB, V8::PHI, 4, DestReg).addReg (FalseValue)
1333     .addMBB (copy0MBB).addReg (TrueValue).addMBB (copy1MBB);
1334 }
1335
1336 void V8ISel::visitAllocaInst(AllocaInst &I) {
1337   // Find the data size of the alloca inst's getAllocatedType.
1338   const Type *Ty = I.getAllocatedType();
1339   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
1340
1341   unsigned ArraySizeReg = getReg (I.getArraySize ());
1342   unsigned TySizeReg = getReg (ConstantUInt::get (Type::UIntTy, TySize));
1343   unsigned TmpReg1 = makeAnotherReg (Type::UIntTy);
1344   unsigned TmpReg2 = makeAnotherReg (Type::UIntTy);
1345   unsigned StackAdjReg = makeAnotherReg (Type::UIntTy);
1346
1347   // StackAdjReg = (ArraySize * TySize) rounded up to nearest doubleword boundary
1348   BuildMI (BB, V8::UMULrr, 2, TmpReg1).addReg (ArraySizeReg).addReg (TySizeReg);
1349
1350   // Round up TmpReg1 to nearest doubleword boundary:
1351   BuildMI (BB, V8::ADDri, 2, TmpReg2).addReg (TmpReg1).addSImm (7);
1352   BuildMI (BB, V8::ANDri, 2, StackAdjReg).addReg (TmpReg2).addSImm (-8);
1353
1354   // Subtract size from stack pointer, thereby allocating some space.
1355   BuildMI (BB, V8::SUBrr, 2, V8::SP).addReg (V8::SP).addReg (StackAdjReg);
1356
1357   // Put a pointer to the space into the result register, by copying
1358   // the stack pointer.
1359   BuildMI (BB, V8::ADDri, 2, getReg(I)).addReg (V8::SP).addSImm (96);
1360
1361   // Inform the Frame Information that we have just allocated a variable-sized
1362   // object.
1363   F->getFrameInfo()->CreateVariableSizedObject();
1364 }
1365
1366 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1367 /// function, lowering any calls to unknown intrinsic functions into the
1368 /// equivalent LLVM code.
1369 void V8ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1370   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1371     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1372       if (CallInst *CI = dyn_cast<CallInst>(I++))
1373         if (Function *F = CI->getCalledFunction())
1374           switch (F->getIntrinsicID()) {
1375           case Intrinsic::vastart:
1376           case Intrinsic::vacopy:
1377           case Intrinsic::vaend:
1378             // We directly implement these intrinsics
1379           case Intrinsic::not_intrinsic: break;
1380           default:
1381             // All other intrinsic calls we must lower.
1382             Instruction *Before = CI->getPrev();
1383             TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1384             if (Before) {        // Move iterator to instruction after call
1385               I = Before;  ++I;
1386             } else {
1387               I = BB->begin();
1388             }
1389           }
1390 }
1391
1392
1393 void V8ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1394   switch (ID) {
1395   default:
1396     std::cerr << "Sorry, unknown intrinsic function call:\n" << CI; abort ();
1397
1398   case Intrinsic::vastart: {
1399     unsigned DestReg = getReg (CI);
1400     BuildMI (BB, V8::ADDri, 2, DestReg).addReg (V8::FP).addSImm (VarArgsOffset);
1401     return;
1402   }
1403
1404   case Intrinsic::vaend:
1405     // va_end is a no-op on SparcV8.
1406     return;
1407
1408   case Intrinsic::vacopy:
1409     std::cerr << "Sorry, va_copy intrinsic still unsupported:\n" << CI; abort ();
1410   }
1411 }
1412
1413 void V8ISel::visitVANextInst (VANextInst &I) {
1414   std::cerr << "Sorry, vanext instruction still unsupported:\n" << I; abort ();
1415 }
1416
1417 void V8ISel::visitVAArgInst (VAArgInst &I) {
1418   std::cerr << "Sorry, vaarg instruction still unsupported:\n" << I; abort ();
1419 }