df668825a6f26e2acadadceb28ea6c712e6abeed
[oota-llvm.git] / lib / Target / Sparc / 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/DerivedTypes.h"
21 #include "llvm/CodeGen/IntrinsicLowering.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/SSARegMap.h"
27 #include "llvm/Target/TargetMachine.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     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
40
41     // MBBMap - Mapping between LLVM BB -> Machine BB
42     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
43
44     V8ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
45
46     /// runOnFunction - Top level implementation of instruction selection for
47     /// the entire function.
48     ///
49     bool runOnFunction(Function &Fn);
50
51     virtual const char *getPassName() const {
52       return "SparcV8 Simple Instruction Selection";
53     }
54
55     /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
56     /// constant expression GEP support.
57     ///
58     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
59                           Value *Src, User::op_iterator IdxBegin,
60                           User::op_iterator IdxEnd, unsigned TargetReg);
61
62     /// emitCastOperation - Common code shared between visitCastInst and
63     /// constant expression cast support.
64     ///
65     void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
66                            Value *Src, const Type *DestTy, unsigned TargetReg);
67
68     /// emitIntegerCast, emitFPToIntegerCast - Helper methods for
69     /// emitCastOperation.
70     ///
71     unsigned emitIntegerCast (MachineBasicBlock *BB,
72                               MachineBasicBlock::iterator IP,
73                               const Type *oldTy, unsigned SrcReg,
74                               const Type *newTy, unsigned DestReg,
75                               bool castToLong = false);
76     void emitFPToIntegerCast (MachineBasicBlock *BB,
77                               MachineBasicBlock::iterator IP, const Type *oldTy,
78                               unsigned SrcReg, const Type *newTy,
79                               unsigned DestReg);
80
81     /// visitBasicBlock - This method is called when we are visiting a new basic
82     /// block.  This simply creates a new MachineBasicBlock to emit code into
83     /// and adds it to the current MachineFunction.  Subsequent visit* for
84     /// instructions will be invoked for all instructions in the basic block.
85     ///
86     void visitBasicBlock(BasicBlock &LLVM_BB) {
87       BB = MBBMap[&LLVM_BB];
88     }
89
90     void emitOp64LibraryCall (MachineBasicBlock *MBB,
91                               MachineBasicBlock::iterator IP,
92                               unsigned DestReg, const char *FuncName,
93                               unsigned Op0Reg, unsigned Op1Reg);
94     void emitShift64 (MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
95                       Instruction &I, unsigned DestReg, unsigned Op0Reg,
96                       unsigned Op1Reg);
97     void visitBinaryOperator(Instruction &I);
98     void visitShiftInst (ShiftInst &SI) { visitBinaryOperator (SI); }
99     void visitSetCondInst(SetCondInst &I);
100     void visitCallInst(CallInst &I);
101     void visitReturnInst(ReturnInst &I);
102     void visitBranchInst(BranchInst &I);
103     void visitUnreachableInst(UnreachableInst &I) {}
104     void visitCastInst(CastInst &I);
105     void visitVAArgInst(VAArgInst &I);
106     void visitLoadInst(LoadInst &I);
107     void visitStoreInst(StoreInst &I);
108     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
109     void visitGetElementPtrInst(GetElementPtrInst &I);
110     void visitAllocaInst(AllocaInst &I);
111
112     void visitInstruction(Instruction &I) {
113       std::cerr << "Unhandled instruction: " << I;
114       abort();
115     }
116
117     /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
118     /// function, lowering any calls to unknown intrinsic functions into the
119     /// equivalent LLVM code.
120     void LowerUnknownIntrinsicFunctionCalls(Function &F);
121     void visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI);
122
123     void LoadArgumentsToVirtualRegs(Function *F);
124
125     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
126     /// because we have to generate our sources into the source basic blocks,
127     /// not the current one.
128     ///
129     void SelectPHINodes();
130
131     /// copyConstantToRegister - Output the instructions required to put the
132     /// specified constant into the specified register.
133     ///
134     void copyConstantToRegister(MachineBasicBlock *MBB,
135                                 MachineBasicBlock::iterator IP,
136                                 Constant *C, unsigned R);
137
138     /// makeAnotherReg - This method returns the next register number we haven't
139     /// yet used.
140     ///
141     /// Long values are handled somewhat specially.  They are always allocated
142     /// as pairs of 32 bit integer values.  The register number returned is the
143     /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
144     /// of the long value.
145     ///
146     unsigned makeAnotherReg(const Type *Ty) {
147       assert(dynamic_cast<const SparcV8RegisterInfo*>(TM.getRegisterInfo()) &&
148              "Current target doesn't have SparcV8 reg info??");
149       const SparcV8RegisterInfo *MRI =
150         static_cast<const SparcV8RegisterInfo*>(TM.getRegisterInfo());
151       if (Ty == Type::LongTy || Ty == Type::ULongTy) {
152         const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
153         // Create the lower part
154         F->getSSARegMap()->createVirtualRegister(RC);
155         // Create the upper part.
156         return F->getSSARegMap()->createVirtualRegister(RC)-1;
157       }
158
159       // Add the mapping of regnumber => reg class to MachineFunction
160       const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
161       return F->getSSARegMap()->createVirtualRegister(RC);
162     }
163
164     unsigned getReg(Value &V) { return getReg (&V); } // allow refs.
165     unsigned getReg(Value *V) {
166       // Just append to the end of the current bb.
167       MachineBasicBlock::iterator It = BB->end();
168       return getReg(V, BB, It);
169     }
170     unsigned getReg(Value *V, MachineBasicBlock *MBB,
171                     MachineBasicBlock::iterator IPt) {
172       unsigned &Reg = RegMap[V];
173       if (Reg == 0) {
174         Reg = makeAnotherReg(V->getType());
175         RegMap[V] = Reg;
176       }
177       // If this operand is a constant, emit the code to copy the constant into
178       // the register here...
179       //
180       if (Constant *C = dyn_cast<Constant>(V)) {
181         copyConstantToRegister(MBB, IPt, C, Reg);
182         RegMap.erase(V);  // Assign a new name to this constant if ref'd again
183       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
184         // Move the address of the global into the register
185         unsigned TmpReg = makeAnotherReg(V->getType());
186         BuildMI (*MBB, IPt, V8::SETHIi, 1, TmpReg).addGlobalAddress (GV);
187         BuildMI (*MBB, IPt, V8::ORri, 2, Reg).addReg (TmpReg)
188           .addGlobalAddress (GV);
189         RegMap.erase(V);  // Assign a new name to this address if ref'd again
190       }
191
192       return Reg;
193     }
194
195   };
196 }
197
198 FunctionPass *llvm::createSparcV8SimpleInstructionSelector(TargetMachine &TM) {
199   return new V8ISel(TM);
200 }
201
202 enum TypeClass {
203   cByte, cShort, cInt, cLong, cFloat, cDouble
204 };
205
206 static TypeClass getClass (const Type *T) {
207   switch (T->getTypeID()) {
208     case Type::UByteTyID:  case Type::SByteTyID:  return cByte;
209     case Type::UShortTyID: case Type::ShortTyID:  return cShort;
210     case Type::PointerTyID:
211     case Type::UIntTyID:   case Type::IntTyID:    return cInt;
212     case Type::ULongTyID:  case Type::LongTyID:   return cLong;
213     case Type::FloatTyID:                         return cFloat;
214     case Type::DoubleTyID:                        return cDouble;
215     default:
216       assert (0 && "Type of unknown class passed to getClass?");
217       return cByte;
218   }
219 }
220
221 static TypeClass getClassB(const Type *T) {
222   if (T == Type::BoolTy) return cByte;
223   return getClass(T);
224 }
225
226 /// copyConstantToRegister - Output the instructions required to put the
227 /// specified constant into the specified register.
228 ///
229 void V8ISel::copyConstantToRegister(MachineBasicBlock *MBB,
230                                     MachineBasicBlock::iterator IP,
231                                     Constant *C, unsigned R) {
232   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
233     switch (CE->getOpcode()) {
234     case Instruction::GetElementPtr:
235       emitGEPOperation(MBB, IP, CE->getOperand(0),
236                        CE->op_begin()+1, CE->op_end(), R);
237       return;
238     case Instruction::Cast:
239       emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
240       return;
241     default:
242       std::cerr << "Copying this constant expr not yet handled: " << *CE;
243       abort();
244     }
245   } else if (isa<UndefValue>(C)) {
246     BuildMI(*MBB, IP, V8::IMPLICIT_DEF_Int, 0, R);
247     if (getClassB (C->getType ()) == cLong)
248       BuildMI(*MBB, IP, V8::IMPLICIT_DEF_Int, 0, R+1);
249     return;
250   }
251
252   if (C->getType()->isIntegral ()) {
253     unsigned Class = getClassB (C->getType ());
254     if (Class == cLong) {
255       unsigned TmpReg = makeAnotherReg (Type::IntTy);
256       unsigned TmpReg2 = makeAnotherReg (Type::IntTy);
257       // Copy the value into the register pair.
258       // R = top(more-significant) half, R+1 = bottom(less-significant) half
259       uint64_t Val = cast<ConstantInt>(C)->getRawValue();
260       copyConstantToRegister(MBB, IP, ConstantUInt::get(Type::UIntTy,
261                              Val >> 32), R);
262       copyConstantToRegister(MBB, IP, ConstantUInt::get(Type::UIntTy,
263                              Val & 0xffffffffU), R+1);
264       return;
265     }
266
267     assert(Class <= cInt && "Type not handled yet!");
268     unsigned Val;
269
270     if (C->getType() == Type::BoolTy) {
271       Val = (C == ConstantBool::True);
272     } else {
273       ConstantIntegral *CI = cast<ConstantIntegral> (C);
274       Val = CI->getRawValue();
275     }
276     if (C->getType()->isSigned()) {
277       switch (Class) {
278         case cByte:  Val =  (int8_t) Val; break;
279         case cShort: Val = (int16_t) Val; break;
280         case cInt:   Val = (int32_t) Val; break;
281       }
282     } else {
283       switch (Class) {
284         case cByte:  Val =  (uint8_t) Val; break;
285         case cShort: Val = (uint16_t) Val; break;
286         case cInt:   Val = (uint32_t) Val; break;
287       }
288     }
289     if (Val == 0) {
290       BuildMI (*MBB, IP, V8::ORrr, 2, R).addReg (V8::G0).addReg(V8::G0);
291     } else if ((int)Val >= -4096 && (int)Val <= 4095) {
292       BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (V8::G0).addSImm(Val);
293     } else {
294       unsigned TmpReg = makeAnotherReg (C->getType ());
295       BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg)
296         .addSImm (((uint32_t) Val) >> 10);
297       BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (TmpReg)
298         .addSImm (((uint32_t) Val) & 0x03ff);
299       return;
300     }
301   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
302     // We need to spill the constant to memory...
303     MachineConstantPool *CP = F->getConstantPool();
304     unsigned CPI = CP->getConstantPoolIndex(CFP);
305     const Type *Ty = CFP->getType();
306     unsigned TmpReg = makeAnotherReg (Type::UIntTy);
307     unsigned AddrReg = makeAnotherReg (Type::UIntTy);
308
309     assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
310     unsigned LoadOpcode = Ty == Type::FloatTy ? V8::LDFri : V8::LDDFri;
311     BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg).addConstantPoolIndex (CPI);
312     BuildMI (*MBB, IP, V8::ORri, 2, AddrReg).addReg (TmpReg)
313       .addConstantPoolIndex (CPI);
314     BuildMI (*MBB, IP, LoadOpcode, 2, R).addReg (AddrReg).addSImm (0);
315   } else if (isa<ConstantPointerNull>(C)) {
316     // Copy zero (null pointer) to the register.
317     BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (V8::G0).addSImm (0);
318   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
319     // Copy it with a SETHI/OR pair; the JIT + asmwriter should recognize
320     // that SETHI %reg,global == SETHI %reg,%hi(global) and
321     // OR %reg,global,%reg == OR %reg,%lo(global),%reg.
322     unsigned TmpReg = makeAnotherReg (C->getType ());
323     BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg).addGlobalAddress(GV);
324     BuildMI (*MBB, IP, V8::ORri, 2, R).addReg(TmpReg).addGlobalAddress(GV);
325   } else {
326     std::cerr << "Offending constant: " << *C << "\n";
327     assert (0 && "Can't copy this kind of constant into register yet");
328   }
329 }
330
331 void V8ISel::LoadArgumentsToVirtualRegs (Function *LF) {
332   static const unsigned IncomingArgRegs[] = { V8::I0, V8::I1, V8::I2,
333     V8::I3, V8::I4, V8::I5 };
334
335   // Add IMPLICIT_DEFs of input regs.
336   unsigned ArgNo = 0;
337   for (Function::arg_iterator I = LF->arg_begin(), E = LF->arg_end();
338        I != E && ArgNo < 6; ++I, ++ArgNo) {
339     switch (getClassB(I->getType())) {
340     case cByte:
341     case cShort:
342     case cInt:
343     case cFloat:
344       BuildMI(BB, V8::IMPLICIT_DEF_Int, 0, IncomingArgRegs[ArgNo]);
345       break;
346     case cDouble:
347     case cLong:
348       // Double and Long use register pairs.
349       BuildMI(BB, V8::IMPLICIT_DEF_Int, 0, IncomingArgRegs[ArgNo]);
350       ++ArgNo;
351       if (ArgNo < 6)
352         BuildMI(BB, V8::IMPLICIT_DEF_Int, 0, IncomingArgRegs[ArgNo]);
353       break;
354     default:
355       assert (0 && "type not handled");
356       return;
357     }
358   }
359
360   const unsigned *IAREnd = &IncomingArgRegs[6];
361   const unsigned *IAR = &IncomingArgRegs[0];
362   unsigned ArgOffset = 68;
363
364   // Store registers onto stack if this is a varargs function.
365   // FIXME: This doesn't really pertain to "loading arguments into
366   // virtual registers", so it's not clear that it really belongs here.
367   // FIXME: We could avoid storing any args onto the stack that don't
368   // need to be in memory, because they come before the ellipsis in the
369   // parameter list (and thus could never be accessed through va_arg).
370   if (LF->getFunctionType()->isVarArg()) {
371     for (unsigned i = 0; i < 6; ++i) {
372       int FI = F->getFrameInfo()->CreateFixedObject(4, ArgOffset);
373       assert (IAR != IAREnd
374               && "About to dereference past end of IncomingArgRegs");
375       BuildMI (BB, V8::STri, 3).addFrameIndex (FI).addSImm (0).addReg (*IAR++);
376       ArgOffset += 4;
377     }
378     // Reset the pointers now that we're done.
379     ArgOffset = 68;
380     IAR = &IncomingArgRegs[0];
381   }
382
383   // Copy args out of their incoming hard regs or stack slots into virtual regs.
384   for (Function::arg_iterator I = LF->arg_begin(), E = LF->arg_end(); I != E; ++I) {
385     Argument &A = *I;
386     unsigned ArgReg = getReg (A);
387     if (getClassB (A.getType ()) < cLong) {
388       // Get it out of the incoming arg register
389       if (ArgOffset < 92) {
390         assert (IAR != IAREnd
391                 && "About to dereference past end of IncomingArgRegs");
392         BuildMI (BB, V8::ORrr, 2, ArgReg).addReg (V8::G0).addReg (*IAR++);
393       } else {
394         int FI = F->getFrameInfo()->CreateFixedObject(4, ArgOffset);
395         BuildMI (BB, V8::LDri, 3, ArgReg).addFrameIndex (FI).addSImm (0);
396       }
397       ArgOffset += 4;
398     } else if (getClassB (A.getType ()) == cFloat) {
399       if (ArgOffset < 92) {
400         // Single-fp args are passed in integer registers; go through
401         // memory to get them out of integer registers and back into fp. (Bleh!)
402         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
403         int FI = F->getFrameInfo()->CreateStackObject(4, FltAlign);
404         assert (IAR != IAREnd
405                 && "About to dereference past end of IncomingArgRegs");
406         BuildMI (BB, V8::STri, 3).addFrameIndex (FI).addSImm (0).addReg (*IAR++);
407         BuildMI (BB, V8::LDFri, 2, ArgReg).addFrameIndex (FI).addSImm (0);
408       } else {
409         int FI = F->getFrameInfo()->CreateFixedObject(4, ArgOffset);
410         BuildMI (BB, V8::LDFri, 3, ArgReg).addFrameIndex (FI).addSImm (0);
411       }
412       ArgOffset += 4;
413     } else if (getClassB (A.getType ()) == cDouble) {
414       // Double-fp args are passed in pairs of integer registers; go through
415       // memory to get them out of integer registers and back into fp. (Bleh!)
416       // We'd like to 'ldd' these right out of the incoming-args area,
417       // but it might not be 8-byte aligned (e.g., call x(int x, double d)).
418       unsigned DblAlign = TM.getTargetData().getDoubleAlignment();
419       int FI = F->getFrameInfo()->CreateStackObject(8, DblAlign);
420       if (ArgOffset < 92 && IAR != IAREnd) {
421         BuildMI (BB, V8::STri, 3).addFrameIndex (FI).addSImm (0).addReg (*IAR++);
422       } else {
423         unsigned TempReg = makeAnotherReg (Type::IntTy);
424         BuildMI (BB, V8::LDri, 2, TempReg).addFrameIndex (FI).addSImm (0);
425         BuildMI (BB, V8::STri, 3).addFrameIndex (FI).addSImm (0).addReg (TempReg);
426       }
427       ArgOffset += 4;
428       if (ArgOffset < 92 && IAR != IAREnd) {
429         BuildMI (BB, V8::STri, 3).addFrameIndex (FI).addSImm (4).addReg (*IAR++);
430       } else {
431         unsigned TempReg = makeAnotherReg (Type::IntTy);
432         BuildMI (BB, V8::LDri, 2, TempReg).addFrameIndex (FI).addSImm (4);
433         BuildMI (BB, V8::STri, 3).addFrameIndex (FI).addSImm (4).addReg (TempReg);
434       }
435       ArgOffset += 4;
436       BuildMI (BB, V8::LDDFri, 2, ArgReg).addFrameIndex (FI).addSImm (0);
437     } else if (getClassB (A.getType ()) == cLong) {
438       // do the first half...
439       if (ArgOffset < 92) {
440         assert (IAR != IAREnd
441                 && "About to dereference past end of IncomingArgRegs");
442         BuildMI (BB, V8::ORrr, 2, ArgReg).addReg (V8::G0).addReg (*IAR++);
443       } else {
444         int FI = F->getFrameInfo()->CreateFixedObject(4, ArgOffset);
445         BuildMI (BB, V8::LDri, 2, ArgReg).addFrameIndex (FI).addSImm (0);
446       }
447       ArgOffset += 4;
448       // ...then do the second half
449       if (ArgOffset < 92) {
450         assert (IAR != IAREnd
451                 && "About to dereference past end of IncomingArgRegs");
452         BuildMI (BB, V8::ORrr, 2, ArgReg+1).addReg (V8::G0).addReg (*IAR++);
453       } else {
454         int FI = F->getFrameInfo()->CreateFixedObject(4, ArgOffset);
455         BuildMI (BB, V8::LDri, 2, ArgReg+1).addFrameIndex (FI).addSImm (0);
456       }
457       ArgOffset += 4;
458     } else {
459       assert (0 && "Unknown class?!");
460     }
461   }
462
463   // If the function takes variable number of arguments, remember the fp
464   // offset for the start of the first vararg value... this is used to expand
465   // llvm.va_start.
466   if (LF->getFunctionType ()->isVarArg ())
467     VarArgsOffset = ArgOffset;
468 }
469
470 void V8ISel::SelectPHINodes() {
471   const TargetInstrInfo &TII = *TM.getInstrInfo();
472   const Function &LF = *F->getFunction();  // The LLVM function...
473   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
474     const BasicBlock *BB = I;
475     MachineBasicBlock &MBB = *MBBMap[I];
476
477     // Loop over all of the PHI nodes in the LLVM basic block...
478     MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
479     for (BasicBlock::const_iterator I = BB->begin();
480          PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
481
482       // Create a new machine instr PHI node, and insert it.
483       unsigned PHIReg = getReg(*PN);
484       MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
485                                     V8::PHI, PN->getNumOperands(), PHIReg);
486
487       MachineInstr *LongPhiMI = 0;
488       if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
489         LongPhiMI = BuildMI(MBB, PHIInsertPoint,
490                             V8::PHI, PN->getNumOperands(), PHIReg+1);
491
492       // PHIValues - Map of blocks to incoming virtual registers.  We use this
493       // so that we only initialize one incoming value for a particular block,
494       // even if the block has multiple entries in the PHI node.
495       //
496       std::map<MachineBasicBlock*, unsigned> PHIValues;
497
498       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
499         MachineBasicBlock *PredMBB = 0;
500         for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
501              PE = MBB.pred_end (); PI != PE; ++PI)
502           if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
503             PredMBB = *PI;
504             break;
505           }
506         assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
507
508         unsigned ValReg;
509         std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
510           PHIValues.lower_bound(PredMBB);
511
512         if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
513           // We already inserted an initialization of the register for this
514           // predecessor.  Recycle it.
515           ValReg = EntryIt->second;
516
517         } else {
518           // Get the incoming value into a virtual register.
519           //
520           Value *Val = PN->getIncomingValue(i);
521
522           // If this is a constant or GlobalValue, we may have to insert code
523           // into the basic block to compute it into a virtual register.
524           if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
525               isa<GlobalValue>(Val)) {
526             // Simple constants get emitted at the end of the basic block,
527             // before any terminator instructions.  We "know" that the code to
528             // move a constant into a register will never clobber any flags.
529             ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
530           } else {
531             // Because we don't want to clobber any values which might be in
532             // physical registers with the computation of this constant (which
533             // might be arbitrarily complex if it is a constant expression),
534             // just insert the computation at the top of the basic block.
535             MachineBasicBlock::iterator PI = PredMBB->begin();
536
537             // Skip over any PHI nodes though!
538             while (PI != PredMBB->end() && PI->getOpcode() == V8::PHI)
539               ++PI;
540
541             ValReg = getReg(Val, PredMBB, PI);
542           }
543
544           // Remember that we inserted a value for this PHI for this predecessor
545           PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
546         }
547
548         PhiMI->addRegOperand(ValReg);
549         PhiMI->addMachineBasicBlockOperand(PredMBB);
550         if (LongPhiMI) {
551           LongPhiMI->addRegOperand(ValReg+1);
552           LongPhiMI->addMachineBasicBlockOperand(PredMBB);
553         }
554       }
555
556       // Now that we emitted all of the incoming values for the PHI node, make
557       // sure to reposition the InsertPoint after the PHI that we just added.
558       // This is needed because we might have inserted a constant into this
559       // block, right after the PHI's which is before the old insert point!
560       PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
561       ++PHIInsertPoint;
562     }
563   }
564 }
565
566 bool V8ISel::runOnFunction(Function &Fn) {
567   // First pass over the function, lower any unknown intrinsic functions
568   // with the IntrinsicLowering class.
569   LowerUnknownIntrinsicFunctionCalls(Fn);
570
571   F = &MachineFunction::construct(&Fn, TM);
572
573   // Create all of the machine basic blocks for the function...
574   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
575     F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
576
577   BB = &F->front();
578
579   // Set up a frame object for the return address.  This is used by the
580   // llvm.returnaddress & llvm.frameaddress intrinisics.
581   //ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
582
583   // Copy incoming arguments off of the stack and out of fixed registers.
584   LoadArgumentsToVirtualRegs(&Fn);
585
586   // Instruction select everything except PHI nodes
587   visit(Fn);
588
589   // Select the PHI nodes
590   SelectPHINodes();
591
592   RegMap.clear();
593   MBBMap.clear();
594   F = 0;
595   // We always build a machine code representation for the function
596   return true;
597 }
598
599 void V8ISel::visitCastInst(CastInst &I) {
600   Value *Op = I.getOperand(0);
601   unsigned DestReg = getReg(I);
602   MachineBasicBlock::iterator MI = BB->end();
603   emitCastOperation(BB, MI, Op, I.getType(), DestReg);
604 }
605
606 unsigned V8ISel::emitIntegerCast (MachineBasicBlock *BB,
607                               MachineBasicBlock::iterator IP, const Type *oldTy,
608                               unsigned SrcReg, const Type *newTy,
609                               unsigned DestReg, bool castToLong) {
610   unsigned shiftWidth = 32 - (8 * TM.getTargetData ().getTypeSize (newTy));
611   if (oldTy == newTy || (!castToLong && shiftWidth == 0)) {
612     // No-op cast - just emit a copy; assume the reg. allocator will zap it.
613     BuildMI (*BB, IP, V8::ORrr, 2, DestReg).addReg (V8::G0).addReg(SrcReg);
614     return SrcReg;
615   }
616   // Emit left-shift, then right-shift to sign- or zero-extend.
617   unsigned TmpReg = makeAnotherReg (newTy);
618   BuildMI (*BB, IP, V8::SLLri, 2, TmpReg).addZImm (shiftWidth).addReg(SrcReg);
619   if (newTy->isSigned ()) { // sign-extend with SRA
620     BuildMI(*BB, IP, V8::SRAri, 2, DestReg).addZImm (shiftWidth).addReg(TmpReg);
621   } else { // zero-extend with SRL
622     BuildMI(*BB, IP, V8::SRLri, 2, DestReg).addZImm (shiftWidth).addReg(TmpReg);
623   }
624   // Return the temp reg. in case this is one half of a cast to long.
625   return TmpReg;
626 }
627
628 void V8ISel::emitFPToIntegerCast (MachineBasicBlock *BB,
629                                   MachineBasicBlock::iterator IP,
630                                   const Type *oldTy, unsigned SrcReg,
631                                   const Type *newTy, unsigned DestReg) {
632   unsigned FPCastOpcode, FPStoreOpcode, FPSize, FPAlign;
633   unsigned oldTyClass = getClassB(oldTy);
634   if (oldTyClass == cFloat) {
635     FPCastOpcode = V8::FSTOI; FPStoreOpcode = V8::STFri; FPSize = 4;
636     FPAlign = TM.getTargetData().getFloatAlignment();
637   } else { // it's a double
638     FPCastOpcode = V8::FDTOI; FPStoreOpcode = V8::STDFri; FPSize = 8;
639     FPAlign = TM.getTargetData().getDoubleAlignment();
640   }
641   unsigned TempReg = makeAnotherReg (oldTy);
642   BuildMI (*BB, IP, FPCastOpcode, 1, TempReg).addReg (SrcReg);
643   int FI = F->getFrameInfo()->CreateStackObject(FPSize, FPAlign);
644   BuildMI (*BB, IP, FPStoreOpcode, 3).addFrameIndex (FI).addSImm (0)
645     .addReg (TempReg);
646   unsigned TempReg2 = makeAnotherReg (newTy);
647   BuildMI (*BB, IP, V8::LDri, 3, TempReg2).addFrameIndex (FI).addSImm (0);
648   emitIntegerCast (BB, IP, Type::IntTy, TempReg2, newTy, DestReg);
649 }
650
651 /// emitCastOperation - Common code shared between visitCastInst and constant
652 /// expression cast support.
653 ///
654 void V8ISel::emitCastOperation(MachineBasicBlock *BB,
655                                MachineBasicBlock::iterator IP, Value *Src,
656                                const Type *DestTy, unsigned DestReg) {
657   const Type *SrcTy = Src->getType();
658   unsigned SrcClass = getClassB(SrcTy);
659   unsigned DestClass = getClassB(DestTy);
660   unsigned SrcReg = getReg(Src, BB, IP);
661
662   const Type *oldTy = SrcTy;
663   const Type *newTy = DestTy;
664   unsigned oldTyClass = SrcClass;
665   unsigned newTyClass = DestClass;
666
667   if (oldTyClass < cLong && newTyClass < cLong) {
668     emitIntegerCast (BB, IP, oldTy, SrcReg, newTy, DestReg);
669   } else switch (newTyClass) {
670     case cByte:
671     case cShort:
672     case cInt:
673       switch (oldTyClass) {
674       case cLong:
675         // Treat it like a cast from the lower half of the value.
676         emitIntegerCast (BB, IP, Type::IntTy, SrcReg+1, newTy, DestReg);
677         break;
678       case cFloat:
679       case cDouble:
680         emitFPToIntegerCast (BB, IP, oldTy, SrcReg, newTy, DestReg);
681         break;
682       default: goto not_yet;
683       }
684       return;
685
686     case cFloat:
687       switch (oldTyClass) {
688       case cLong: goto not_yet;
689       case cFloat:
690         BuildMI (*BB, IP, V8::FMOVS, 1, DestReg).addReg (SrcReg);
691         break;
692       case cDouble:
693         BuildMI (*BB, IP, V8::FDTOS, 1, DestReg).addReg (SrcReg);
694         break;
695       default: {
696         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
697         // cast integer type to float.  Store it to a stack slot and then load
698         // it using ldf into a floating point register. then do fitos.
699         unsigned TmpReg = makeAnotherReg (newTy);
700         int FI = F->getFrameInfo()->CreateStackObject(4, FltAlign);
701         BuildMI (*BB, IP, V8::STri, 3).addFrameIndex (FI).addSImm (0)
702           .addReg (SrcReg);
703         BuildMI (*BB, IP, V8::LDFri, 2, TmpReg).addFrameIndex (FI).addSImm (0);
704         BuildMI (*BB, IP, V8::FITOS, 1, DestReg).addReg(TmpReg);
705         break;
706       }
707       }
708       return;
709
710     case cDouble:
711       switch (oldTyClass) {
712       case cLong: goto not_yet;
713       case cFloat:
714         BuildMI (*BB, IP, V8::FSTOD, 1, DestReg).addReg (SrcReg);
715         break;
716       case cDouble: // use double move pseudo-instr
717         BuildMI (*BB, IP, V8::FpMOVD, 1, DestReg).addReg (SrcReg);
718         break;
719       default: {
720         unsigned DoubleAlignment = TM.getTargetData().getDoubleAlignment();
721         unsigned TmpReg = makeAnotherReg (newTy);
722         int FI = F->getFrameInfo()->CreateStackObject(8, DoubleAlignment);
723         BuildMI (*BB, IP, V8::STri, 3).addFrameIndex (FI).addSImm (0)
724           .addReg (SrcReg);
725         BuildMI (*BB, IP, V8::LDDFri, 2, TmpReg).addFrameIndex (FI).addSImm (0);
726         BuildMI (*BB, IP, V8::FITOD, 1, DestReg).addReg(TmpReg);
727         break;
728       }
729       }
730       return;
731
732     case cLong:
733       switch (oldTyClass) {
734       case cByte:
735       case cShort:
736       case cInt: {
737         // Cast to (u)int in the bottom half, and sign(zero) extend in the top
738         // half.
739         const Type *OldHalfTy = oldTy->isSigned() ? Type::IntTy : Type::UIntTy;
740         const Type *NewHalfTy = newTy->isSigned() ? Type::IntTy : Type::UIntTy;
741         unsigned TempReg = emitIntegerCast (BB, IP, OldHalfTy, SrcReg,
742                                             NewHalfTy, DestReg+1, true);
743         if (newTy->isSigned ()) {
744           BuildMI (*BB, IP, V8::SRAri, 2, DestReg).addReg (TempReg)
745             .addZImm (31);
746         } else {
747           BuildMI (*BB, IP, V8::ORrr, 2, DestReg).addReg (V8::G0)
748             .addReg (V8::G0);
749         }
750         break;
751       }
752       case cLong:
753         // Just copy both halves.
754         BuildMI (*BB, IP, V8::ORrr, 2, DestReg).addReg (V8::G0).addReg (SrcReg);
755         BuildMI (*BB, IP, V8::ORrr, 2, DestReg+1).addReg (V8::G0)
756           .addReg (SrcReg+1);
757         break;
758       default: goto not_yet;
759       }
760       return;
761
762     default: goto not_yet;
763   }
764   return;
765 not_yet:
766   std::cerr << "Sorry, cast still unsupported: SrcTy = " << *SrcTy
767             << ", DestTy = " << *DestTy << "\n";
768   abort ();
769 }
770
771 void V8ISel::visitLoadInst(LoadInst &I) {
772   unsigned DestReg = getReg (I);
773   unsigned PtrReg = getReg (I.getOperand (0));
774   switch (getClassB (I.getType ())) {
775    case cByte:
776     if (I.getType ()->isSigned ())
777       BuildMI (BB, V8::LDSBri, 2, DestReg).addReg (PtrReg).addSImm(0);
778     else
779       BuildMI (BB, V8::LDUBri, 2, DestReg).addReg (PtrReg).addSImm(0);
780     return;
781    case cShort:
782     if (I.getType ()->isSigned ())
783       BuildMI (BB, V8::LDSHri, 2, DestReg).addReg (PtrReg).addSImm(0);
784     else
785       BuildMI (BB, V8::LDUHri, 2, DestReg).addReg (PtrReg).addSImm(0);
786     return;
787    case cInt:
788     BuildMI (BB, V8::LDri, 2, DestReg).addReg (PtrReg).addSImm(0);
789     return;
790    case cLong:
791     BuildMI (BB, V8::LDri, 2, DestReg).addReg (PtrReg).addSImm(0);
792     BuildMI (BB, V8::LDri, 2, DestReg+1).addReg (PtrReg).addSImm(4);
793     return;
794    case cFloat:
795     BuildMI (BB, V8::LDFri, 2, DestReg).addReg (PtrReg).addSImm(0);
796     return;
797    case cDouble:
798     BuildMI (BB, V8::LDDFri, 2, DestReg).addReg (PtrReg).addSImm(0);
799     return;
800    default:
801     std::cerr << "Load instruction not handled: " << I;
802     abort ();
803     return;
804   }
805 }
806
807 void V8ISel::visitStoreInst(StoreInst &I) {
808   Value *SrcVal = I.getOperand (0);
809   unsigned SrcReg = getReg (SrcVal);
810   unsigned PtrReg = getReg (I.getOperand (1));
811   switch (getClassB (SrcVal->getType ())) {
812    case cByte:
813     BuildMI (BB, V8::STBri, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
814     return;
815    case cShort:
816     BuildMI (BB, V8::STHri, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
817     return;
818    case cInt:
819     BuildMI (BB, V8::STri, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
820     return;
821    case cLong:
822     BuildMI (BB, V8::STri, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
823     BuildMI (BB, V8::STri, 3).addReg (PtrReg).addSImm (4).addReg (SrcReg+1);
824     return;
825    case cFloat:
826     BuildMI (BB, V8::STFri, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
827     return;
828    case cDouble:
829     BuildMI (BB, V8::STDFri, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
830     return;
831    default:
832     std::cerr << "Store instruction not handled: " << I;
833     abort ();
834     return;
835   }
836 }
837
838 void V8ISel::visitCallInst(CallInst &I) {
839   MachineInstr *TheCall;
840   // Is it an intrinsic function call?
841   if (Function *F = I.getCalledFunction()) {
842     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
843       visitIntrinsicCall(ID, I);   // Special intrinsics are not handled here
844       return;
845     }
846   }
847
848   // How much extra call stack will we need?
849   int extraStack = 0;
850   for (unsigned i = 0; i < I.getNumOperands (); ++i) {
851     switch (getClassB (I.getOperand (i)->getType ())) {
852       case cLong: extraStack += 8; break;
853       case cFloat: extraStack += 4; break;
854       case cDouble: extraStack += 8; break;
855       default: extraStack += 4; break;
856     }
857   }
858   extraStack -= 24;
859   if (extraStack < 0) {
860     extraStack = 0;
861   } else {
862     // Round up extra stack size to the nearest doubleword.
863     extraStack = (extraStack + 7) & ~7;
864   }
865
866   // Deal with args
867   static const unsigned OutgoingArgRegs[] = { V8::O0, V8::O1, V8::O2, V8::O3,
868     V8::O4, V8::O5 };
869   const unsigned *OAREnd = &OutgoingArgRegs[6];
870   const unsigned *OAR = &OutgoingArgRegs[0];
871   unsigned ArgOffset = 68;
872   if (extraStack) BuildMI (BB, V8::ADJCALLSTACKDOWN, 1).addImm (extraStack);
873   for (unsigned i = 1; i < I.getNumOperands (); ++i) {
874     unsigned ArgReg = getReg (I.getOperand (i));
875     if (getClassB (I.getOperand (i)->getType ()) < cLong) {
876       // Schlep it over into the incoming arg register
877       if (ArgOffset < 92) {
878         assert (OAR != OAREnd &&
879                 "About to dereference past end of OutgoingArgRegs");
880         BuildMI (BB, V8::ORrr, 2, *OAR++).addReg (V8::G0).addReg (ArgReg);
881       } else {
882         BuildMI (BB, V8::STri, 3).addReg (V8::O6).addSImm (ArgOffset)
883           .addReg (ArgReg);
884       }
885       ArgOffset += 4;
886     } else if (getClassB (I.getOperand (i)->getType ()) == cFloat) {
887       if (ArgOffset < 92) {
888         // Single-fp args are passed in integer registers; go through
889         // memory to get them out of FP registers. (Bleh!)
890         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
891         int FI = F->getFrameInfo()->CreateStackObject(4, FltAlign);
892         BuildMI (BB, V8::STFri, 3).addFrameIndex(FI).addSImm(0).addReg(ArgReg);
893         assert (OAR != OAREnd &&
894                 "About to dereference past end of OutgoingArgRegs");
895         BuildMI (BB, V8::LDri, 2, *OAR++).addFrameIndex (FI).addSImm (0);
896       } else {
897         BuildMI (BB, V8::STFri, 3).addReg (V8::O6).addSImm (ArgOffset)
898           .addReg (ArgReg);
899       }
900       ArgOffset += 4;
901     } else if (getClassB (I.getOperand (i)->getType ()) == cDouble) {
902       // Double-fp args are passed in pairs of integer registers; go through
903       // memory to get them out of FP registers. (Bleh!)
904       // We'd like to 'std' these right onto the outgoing-args area, but it might
905       // not be 8-byte aligned (e.g., call x(int x, double d)). sigh.
906       unsigned DblAlign = TM.getTargetData().getDoubleAlignment();
907       int FI = F->getFrameInfo()->CreateStackObject(8, DblAlign);
908       BuildMI (BB, V8::STDFri, 3).addFrameIndex (FI).addSImm (0).addReg (ArgReg);
909       if (ArgOffset < 92 && OAR != OAREnd) {
910         assert (OAR != OAREnd &&
911                 "About to dereference past end of OutgoingArgRegs");
912         BuildMI (BB, V8::LDri, 2, *OAR++).addFrameIndex (FI).addSImm (0);
913       } else {
914         unsigned TempReg = makeAnotherReg (Type::IntTy);
915         BuildMI (BB, V8::LDri, 2, TempReg).addFrameIndex (FI).addSImm (0);
916         BuildMI (BB, V8::STri, 3).addReg (V8::O6).addSImm (ArgOffset)
917           .addReg (TempReg);
918       }
919       ArgOffset += 4;
920       if (ArgOffset < 92 && OAR != OAREnd) {
921         assert (OAR != OAREnd &&
922                 "About to dereference past end of OutgoingArgRegs");
923         BuildMI (BB, V8::LDri, 2, *OAR++).addFrameIndex (FI).addSImm (4);
924       } else {
925         unsigned TempReg = makeAnotherReg (Type::IntTy);
926         BuildMI (BB, V8::LDri, 2, TempReg).addFrameIndex (FI).addSImm (4);
927         BuildMI (BB, V8::STri, 3).addReg (V8::O6).addSImm (ArgOffset)
928           .addReg (TempReg);
929       }
930       ArgOffset += 4;
931     } else if (getClassB (I.getOperand (i)->getType ()) == cLong) {
932       // do the first half...
933       if (ArgOffset < 92) {
934         assert (OAR != OAREnd &&
935                 "About to dereference past end of OutgoingArgRegs");
936         BuildMI (BB, V8::ORrr, 2, *OAR++).addReg (V8::G0).addReg (ArgReg);
937       } else {
938         BuildMI (BB, V8::STri, 3).addReg (V8::O6).addSImm (ArgOffset)
939           .addReg (ArgReg);
940       }
941       ArgOffset += 4;
942       // ...then do the second half
943       if (ArgOffset < 92) {
944         assert (OAR != OAREnd &&
945                 "About to dereference past end of OutgoingArgRegs");
946         BuildMI (BB, V8::ORrr, 2, *OAR++).addReg (V8::G0).addReg (ArgReg+1);
947       } else {
948         BuildMI (BB, V8::STri, 3).addReg (V8::O6).addSImm (ArgOffset)
949           .addReg (ArgReg+1);
950       }
951       ArgOffset += 4;
952     } else {
953       assert (0 && "Unknown class?!");
954     }
955   }
956
957   // Emit call instruction
958   if (Function *F = I.getCalledFunction ()) {
959     BuildMI (BB, V8::CALL, 1).addGlobalAddress (F, true);
960   } else {  // Emit an indirect call...
961     unsigned Reg = getReg (I.getCalledValue ());
962     BuildMI (BB, V8::JMPLrr, 3, V8::O7).addReg (Reg).addReg (V8::G0);
963   }
964
965   if (extraStack) BuildMI (BB, V8::ADJCALLSTACKUP, 1).addImm (extraStack);
966
967   // Deal w/ return value: schlep it over into the destination register
968   if (I.getType () == Type::VoidTy)
969     return;
970   unsigned DestReg = getReg (I);
971   switch (getClassB (I.getType ())) {
972     case cByte:
973     case cShort:
974     case cInt:
975       BuildMI (BB, V8::ORrr, 2, DestReg).addReg(V8::G0).addReg(V8::O0);
976       break;
977     case cFloat:
978       BuildMI (BB, V8::FMOVS, 2, DestReg).addReg(V8::F0);
979       break;
980     case cDouble:
981       BuildMI (BB, V8::FpMOVD, 2, DestReg).addReg(V8::D0);
982       break;
983     case cLong:
984       BuildMI (BB, V8::ORrr, 2, DestReg).addReg(V8::G0).addReg(V8::O0);
985       BuildMI (BB, V8::ORrr, 2, DestReg+1).addReg(V8::G0).addReg(V8::O1);
986       break;
987     default:
988       std::cerr << "Return type of call instruction not handled: " << I;
989       abort ();
990   }
991 }
992
993 void V8ISel::visitReturnInst(ReturnInst &I) {
994   if (I.getNumOperands () == 1) {
995     unsigned RetValReg = getReg (I.getOperand (0));
996     switch (getClassB (I.getOperand (0)->getType ())) {
997       case cByte:
998       case cShort:
999       case cInt:
1000         // Schlep it over into i0 (where it will become o0 after restore).
1001         BuildMI (BB, V8::ORrr, 2, V8::I0).addReg(V8::G0).addReg(RetValReg);
1002         break;
1003       case cFloat:
1004         BuildMI (BB, V8::FMOVS, 1, V8::F0).addReg(RetValReg);
1005         break;
1006       case cDouble:
1007         BuildMI (BB, V8::FpMOVD, 1, V8::D0).addReg(RetValReg);
1008         break;
1009       case cLong:
1010         BuildMI (BB, V8::ORrr, 2, V8::I0).addReg(V8::G0).addReg(RetValReg);
1011         BuildMI (BB, V8::ORrr, 2, V8::I1).addReg(V8::G0).addReg(RetValReg+1);
1012         break;
1013       default:
1014         std::cerr << "Return instruction of this type not handled: " << I;
1015         abort ();
1016     }
1017   }
1018
1019   // Just emit a 'retl' instruction to return.
1020   BuildMI(BB, V8::RETL, 0);
1021   return;
1022 }
1023
1024 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1025   Function::iterator I = BB; ++I;  // Get iterator to next block
1026   return I != BB->getParent()->end() ? &*I : 0;
1027 }
1028
1029 /// canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it
1030 /// into the conditional branch which is the only user of the cc instruction.
1031 /// This is the case if the conditional branch is the only user of the setcc.
1032 ///
1033 static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
1034   //return 0; // disable.
1035   if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1036     if (SCI->hasOneUse()) {
1037       BranchInst *User = dyn_cast<BranchInst>(SCI->use_back());
1038       if (User
1039           && (SCI->getNext() == User)
1040           && (getClassB(SCI->getOperand(0)->getType()) != cLong)
1041           && User->isConditional() && (User->getCondition() == V))
1042         return SCI;
1043     }
1044   return 0;
1045 }
1046
1047 /// visitBranchInst - Handles conditional and unconditional branches.
1048 ///
1049 void V8ISel::visitBranchInst(BranchInst &I) {
1050   BasicBlock *takenSucc = I.getSuccessor (0);
1051   MachineBasicBlock *takenSuccMBB = MBBMap[takenSucc];
1052   BB->addSuccessor (takenSuccMBB);
1053   if (I.isConditional()) {  // conditional branch
1054     BasicBlock *notTakenSucc = I.getSuccessor (1);
1055     MachineBasicBlock *notTakenSuccMBB = MBBMap[notTakenSucc];
1056     BB->addSuccessor (notTakenSuccMBB);
1057
1058     // See if we can fold a previous setcc instr into this branch.
1059     SetCondInst *SCI = canFoldSetCCIntoBranch(I.getCondition());
1060     if (SCI == 0) {
1061       // The condition did not come from a setcc which we could fold.
1062       // CondReg=(<condition>);
1063       // If (CondReg==0) goto notTakenSuccMBB;
1064       unsigned CondReg = getReg (I.getCondition ());
1065       BuildMI (BB, V8::SUBCCri, 2, V8::G0).addReg(CondReg).addSImm(0);
1066       BuildMI (BB, V8::BE, 1).addMBB (notTakenSuccMBB);
1067       BuildMI (BB, V8::BA, 1).addMBB (takenSuccMBB);
1068       return;
1069     }
1070
1071     // Fold the setCC instr into the branch.
1072     unsigned Op0Reg = getReg (SCI->getOperand (0));
1073     unsigned Op1Reg = getReg (SCI->getOperand (1));
1074     const Type *Ty = SCI->getOperand (0)->getType ();
1075
1076     // Compare the two values.
1077     if (getClass (Ty) < cLong) {
1078       BuildMI(BB, V8::SUBCCrr, 2, V8::G0).addReg(Op0Reg).addReg(Op1Reg);
1079     } else if (getClass (Ty) == cLong) {
1080       assert (0 && "Can't fold setcc long/ulong into branch");
1081     } else if (getClass (Ty) == cFloat) {
1082       BuildMI(BB, V8::FCMPS, 2).addReg(Op0Reg).addReg(Op1Reg);
1083     } else if (getClass (Ty) == cDouble) {
1084       BuildMI(BB, V8::FCMPD, 2).addReg(Op0Reg).addReg(Op1Reg);
1085     }
1086
1087     unsigned BranchIdx;
1088     switch (SCI->getOpcode()) {
1089     default: assert(0 && "Unknown setcc instruction!");
1090     case Instruction::SetEQ: BranchIdx = 0; break;
1091     case Instruction::SetNE: BranchIdx = 1; break;
1092     case Instruction::SetLT: BranchIdx = 2; break;
1093     case Instruction::SetGT: BranchIdx = 3; break;
1094     case Instruction::SetLE: BranchIdx = 4; break;
1095     case Instruction::SetGE: BranchIdx = 5; break;
1096     }
1097
1098     unsigned Column = 0;
1099     if (Ty->isSigned() && !Ty->isFloatingPoint()) Column = 1;
1100     if (Ty->isFloatingPoint()) Column = 2;
1101     static unsigned OpcodeTab[3*6] = {
1102                                    // LLVM            SparcV8
1103                                    //        unsigned signed  fp
1104       V8::BE,   V8::BE,  V8::FBE,  // seteq = be      be      fbe
1105       V8::BNE,  V8::BNE, V8::FBNE, // setne = bne     bne     fbne
1106       V8::BCS,  V8::BL,  V8::FBL,  // setlt = bcs     bl      fbl
1107       V8::BGU,  V8::BG,  V8::FBG,  // setgt = bgu     bg      fbg
1108       V8::BLEU, V8::BLE, V8::FBLE, // setle = bleu    ble     fble
1109       V8::BCC,  V8::BGE, V8::FBGE  // setge = bcc     bge     fbge
1110     };
1111     unsigned Opcode = OpcodeTab[3*BranchIdx + Column];
1112     BuildMI (BB, Opcode, 1).addMBB (takenSuccMBB);
1113     BuildMI (BB, V8::BA, 1).addMBB (notTakenSuccMBB);
1114   } else {
1115     // goto takenSuccMBB;
1116     BuildMI (BB, V8::BA, 1).addMBB (takenSuccMBB);
1117   }
1118 }
1119
1120 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
1121 /// constant expression GEP support.
1122 ///
1123 void V8ISel::emitGEPOperation (MachineBasicBlock *MBB,
1124                                MachineBasicBlock::iterator IP,
1125                                Value *Src, User::op_iterator IdxBegin,
1126                                User::op_iterator IdxEnd, unsigned TargetReg) {
1127   const TargetData &TD = TM.getTargetData ();
1128   const Type *Ty = Src->getType ();
1129   unsigned basePtrReg = getReg (Src, MBB, IP);
1130
1131   // GEPs have zero or more indices; we must perform a struct access
1132   // or array access for each one.
1133   for (GetElementPtrInst::op_iterator oi = IdxBegin, oe = IdxEnd; oi != oe;
1134        ++oi) {
1135     Value *idx = *oi;
1136     unsigned nextBasePtrReg = makeAnotherReg (Type::UIntTy);
1137     if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
1138       // It's a struct access.  idx is the index into the structure,
1139       // which names the field. Use the TargetData structure to
1140       // pick out what the layout of the structure is in memory.
1141       // Use the (constant) structure index's value to find the
1142       // right byte offset from the StructLayout class's list of
1143       // structure member offsets.
1144       unsigned fieldIndex = cast<ConstantUInt> (idx)->getValue ();
1145       unsigned memberOffset =
1146         TD.getStructLayout (StTy)->MemberOffsets[fieldIndex];
1147       // Emit an ADD to add memberOffset to the basePtr.
1148       // We might have to copy memberOffset into a register first, if
1149       // it's big.
1150       if (memberOffset + 4096 < 8191) {
1151         BuildMI (*MBB, IP, V8::ADDri, 2,
1152                  nextBasePtrReg).addReg (basePtrReg).addSImm (memberOffset);
1153       } else {
1154         unsigned offsetReg = makeAnotherReg (Type::IntTy);
1155         copyConstantToRegister (MBB, IP,
1156           ConstantSInt::get(Type::IntTy, memberOffset), offsetReg);
1157         BuildMI (*MBB, IP, V8::ADDrr, 2,
1158                  nextBasePtrReg).addReg (basePtrReg).addReg (offsetReg);
1159       }
1160       // The next type is the member of the structure selected by the
1161       // index.
1162       Ty = StTy->getElementType (fieldIndex);
1163     } else if (const SequentialType *SqTy = dyn_cast<SequentialType> (Ty)) {
1164       // It's an array or pointer access: [ArraySize x ElementType].
1165       // We want to add basePtrReg to (idxReg * sizeof ElementType). First, we
1166       // must find the size of the pointed-to type (Not coincidentally, the next
1167       // type is the type of the elements in the array).
1168       Ty = SqTy->getElementType ();
1169       unsigned elementSize = TD.getTypeSize (Ty);
1170       unsigned OffsetReg = ~0U;
1171       int64_t Offset = -1;
1172       bool addImmed = false;
1173       if (isa<ConstantIntegral> (idx)) {
1174         // If idx is a constant, we don't have to emit the multiply.
1175         int64_t Val = cast<ConstantIntegral> (idx)->getRawValue ();
1176         if ((Val * elementSize) + 4096 < 8191) {
1177           // (Val * elementSize) is constant and fits in an immediate field.
1178           // emit: nextBasePtrReg = ADDri basePtrReg, (Val * elementSize)
1179           addImmed = true;
1180           Offset = Val * elementSize;
1181         } else {
1182           // (Val * elementSize) is constant, but doesn't fit in an immediate
1183           // field.  emit: OffsetReg = (Val * elementSize)
1184           //               nextBasePtrReg = ADDrr OffsetReg, basePtrReg
1185           OffsetReg = makeAnotherReg (Type::IntTy);
1186           copyConstantToRegister (MBB, IP,
1187             ConstantSInt::get(Type::IntTy, Val * elementSize), OffsetReg);
1188         }
1189       } else {
1190         // idx is not constant, we have to shift or multiply.
1191         OffsetReg = makeAnotherReg (Type::IntTy);
1192         unsigned idxReg = getReg (idx, MBB, IP);
1193         switch (elementSize) {
1194           case 1:
1195             BuildMI (*MBB, IP, V8::ORrr, 2, OffsetReg).addReg (V8::G0).addReg (idxReg);
1196             break;
1197           case 2:
1198             BuildMI (*MBB, IP, V8::SLLri, 2, OffsetReg).addReg (idxReg).addZImm (1);
1199             break;
1200           case 4:
1201             BuildMI (*MBB, IP, V8::SLLri, 2, OffsetReg).addReg (idxReg).addZImm (2);
1202             break;
1203           case 8:
1204             BuildMI (*MBB, IP, V8::SLLri, 2, OffsetReg).addReg (idxReg).addZImm (3);
1205             break;
1206           default: {
1207             if (elementSize + 4096 < 8191) {
1208               // Emit a SMUL to multiply the register holding the index by
1209               // elementSize, putting the result in OffsetReg.
1210               BuildMI (*MBB, IP, V8::SMULri, 2,
1211                        OffsetReg).addReg (idxReg).addSImm (elementSize);
1212             } else {
1213               unsigned elementSizeReg = makeAnotherReg (Type::UIntTy);
1214               copyConstantToRegister (MBB, IP,
1215                 ConstantUInt::get(Type::UIntTy, elementSize), elementSizeReg);
1216               // Emit a SMUL to multiply the register holding the index by
1217               // the register w/ elementSize, putting the result in OffsetReg.
1218               BuildMI (*MBB, IP, V8::SMULrr, 2,
1219                        OffsetReg).addReg (idxReg).addReg (elementSizeReg);
1220             }
1221             break;
1222           }
1223         }
1224       }
1225       if (addImmed) {
1226         // Emit an ADD to add the constant immediate Offset to the basePtr.
1227         BuildMI (*MBB, IP, V8::ADDri, 2,
1228                  nextBasePtrReg).addReg (basePtrReg).addSImm (Offset);
1229       } else {
1230         // Emit an ADD to add OffsetReg to the basePtr.
1231         BuildMI (*MBB, IP, V8::ADDrr, 2,
1232                  nextBasePtrReg).addReg (basePtrReg).addReg (OffsetReg);
1233       }
1234     }
1235     basePtrReg = nextBasePtrReg;
1236   }
1237   // After we have processed all the indices, the result is left in
1238   // basePtrReg.  Move it to the register where we were expected to
1239   // put the answer.
1240   BuildMI (BB, V8::ORrr, 1, TargetReg).addReg (V8::G0).addReg (basePtrReg);
1241 }
1242
1243 void V8ISel::visitGetElementPtrInst (GetElementPtrInst &I) {
1244   unsigned outputReg = getReg (I);
1245   emitGEPOperation (BB, BB->end (), I.getOperand (0),
1246                     I.op_begin ()+1, I.op_end (), outputReg);
1247 }
1248
1249 void V8ISel::emitOp64LibraryCall (MachineBasicBlock *MBB,
1250                                   MachineBasicBlock::iterator IP,
1251                                   unsigned DestReg,
1252                                   const char *FuncName,
1253                                   unsigned Op0Reg, unsigned Op1Reg) {
1254   BuildMI (*MBB, IP, V8::ORrr, 2, V8::O0).addReg (V8::G0).addReg (Op0Reg);
1255   BuildMI (*MBB, IP, V8::ORrr, 2, V8::O1).addReg (V8::G0).addReg (Op0Reg+1);
1256   BuildMI (*MBB, IP, V8::ORrr, 2, V8::O2).addReg (V8::G0).addReg (Op1Reg);
1257   BuildMI (*MBB, IP, V8::ORrr, 2, V8::O3).addReg (V8::G0).addReg (Op1Reg+1);
1258   BuildMI (*MBB, IP, V8::CALL, 1).addExternalSymbol (FuncName, true);
1259   BuildMI (*MBB, IP, V8::ORrr, 2, DestReg).addReg (V8::G0).addReg (V8::O0);
1260   BuildMI (*MBB, IP, V8::ORrr, 2, DestReg+1).addReg (V8::G0).addReg (V8::O1);
1261 }
1262
1263 void V8ISel::emitShift64 (MachineBasicBlock *MBB,
1264                           MachineBasicBlock::iterator IP, Instruction &I,
1265                           unsigned DestReg, unsigned SrcReg,
1266                           unsigned ShiftAmtReg) {
1267   bool isSigned = I.getType()->isSigned();
1268
1269   switch (I.getOpcode ()) {
1270   case Instruction::Shr: {
1271     unsigned CarryReg = makeAnotherReg (Type::IntTy),
1272              ThirtyTwo = makeAnotherReg (Type::IntTy),
1273              HalfShiftReg = makeAnotherReg (Type::IntTy),
1274              NegHalfShiftReg = makeAnotherReg (Type::IntTy),
1275              TempReg = makeAnotherReg (Type::IntTy);
1276     unsigned OneShiftOutReg = makeAnotherReg (Type::ULongTy),
1277              TwoShiftsOutReg = makeAnotherReg (Type::ULongTy);
1278
1279     MachineBasicBlock *thisMBB = BB;
1280     const BasicBlock *LLVM_BB = BB->getBasicBlock ();
1281     MachineBasicBlock *shiftMBB = new MachineBasicBlock (LLVM_BB);
1282     F->getBasicBlockList ().push_back (shiftMBB);
1283     MachineBasicBlock *oneShiftMBB = new MachineBasicBlock (LLVM_BB);
1284     F->getBasicBlockList ().push_back (oneShiftMBB);
1285     MachineBasicBlock *twoShiftsMBB = new MachineBasicBlock (LLVM_BB);
1286     F->getBasicBlockList ().push_back (twoShiftsMBB);
1287     MachineBasicBlock *continueMBB = new MachineBasicBlock (LLVM_BB);
1288     F->getBasicBlockList ().push_back (continueMBB);
1289
1290     // .lshr_begin:
1291     //   ...
1292     //   subcc %g0, ShiftAmtReg, %g0                   ! Is ShAmt == 0?
1293     //   be .lshr_continue                             ! Then don't shift.
1294     //   ba .lshr_shift                                ! else shift.
1295
1296     BuildMI (BB, V8::SUBCCrr, 2, V8::G0).addReg (V8::G0)
1297       .addReg (ShiftAmtReg);
1298     BuildMI (BB, V8::BE, 1).addMBB (continueMBB);
1299     BuildMI (BB, V8::BA, 1).addMBB (shiftMBB);
1300
1301     // Update machine-CFG edges
1302     BB->addSuccessor (continueMBB);
1303     BB->addSuccessor (shiftMBB);
1304
1305     // .lshr_shift: ! [preds: begin]
1306     //   or %g0, 32, ThirtyTwo
1307     //   subcc ThirtyTwo, ShiftAmtReg, HalfShiftReg    ! Calculate 32 - shamt
1308     //   bg .lshr_two_shifts                           ! If >0, b two_shifts
1309     //   ba .lshr_one_shift                            ! else one_shift.
1310
1311     BB = shiftMBB;
1312
1313     BuildMI (BB, V8::ORri, 2, ThirtyTwo).addReg (V8::G0).addSImm (32);
1314     BuildMI (BB, V8::SUBCCrr, 2, HalfShiftReg).addReg (ThirtyTwo)
1315       .addReg (ShiftAmtReg);
1316     BuildMI (BB, V8::BG, 1).addMBB (twoShiftsMBB);
1317     BuildMI (BB, V8::BA, 1).addMBB (oneShiftMBB);
1318
1319     // Update machine-CFG edges
1320     BB->addSuccessor (twoShiftsMBB);
1321     BB->addSuccessor (oneShiftMBB);
1322
1323     // .lshr_two_shifts: ! [preds: shift]
1324     //   sll SrcReg, HalfShiftReg, CarryReg            ! Save the borrows
1325     //  ! <SHIFT> in following is sra if signed, srl if unsigned
1326     //   <SHIFT> SrcReg, ShiftAmtReg, TwoShiftsOutReg  ! Shift top half
1327     //   srl SrcReg+1, ShiftAmtReg, TempReg            ! Shift bottom half
1328     //   or TempReg, CarryReg, TwoShiftsOutReg+1       ! Restore the borrows
1329     //   ba .lshr_continue
1330     unsigned ShiftOpcode = (isSigned ? V8::SRArr : V8::SRLrr);
1331
1332     BB = twoShiftsMBB;
1333
1334     BuildMI (BB, V8::SLLrr, 2, CarryReg).addReg (SrcReg)
1335       .addReg (HalfShiftReg);
1336     BuildMI (BB, ShiftOpcode, 2, TwoShiftsOutReg).addReg (SrcReg)
1337       .addReg (ShiftAmtReg);
1338     BuildMI (BB, V8::SRLrr, 2, TempReg).addReg (SrcReg+1)
1339       .addReg (ShiftAmtReg);
1340     BuildMI (BB, V8::ORrr, 2, TwoShiftsOutReg+1).addReg (TempReg)
1341       .addReg (CarryReg);
1342     BuildMI (BB, V8::BA, 1).addMBB (continueMBB);
1343
1344     // Update machine-CFG edges
1345     BB->addSuccessor (continueMBB);
1346
1347     // .lshr_one_shift: ! [preds: shift]
1348     //  ! if unsigned:
1349     //   or %g0, %g0, OneShiftOutReg                       ! Zero top half
1350     //  ! or, if signed:
1351     //   sra SrcReg, 31, OneShiftOutReg                    ! Sign-ext top half
1352     //   sub %g0, HalfShiftReg, NegHalfShiftReg            ! Make ShiftAmt >0
1353     //   <SHIFT> SrcReg, NegHalfShiftReg, OneShiftOutReg+1 ! Shift bottom half
1354     //   ba .lshr_continue
1355
1356     BB = oneShiftMBB;
1357
1358     if (isSigned)
1359       BuildMI (BB, V8::SRAri, 2, OneShiftOutReg).addReg (SrcReg).addZImm (31);
1360     else
1361       BuildMI (BB, V8::ORrr, 2, OneShiftOutReg).addReg (V8::G0)
1362         .addReg (V8::G0);
1363     BuildMI (BB, V8::SUBrr, 2, NegHalfShiftReg).addReg (V8::G0)
1364       .addReg (HalfShiftReg);
1365     BuildMI (BB, ShiftOpcode, 2, OneShiftOutReg+1).addReg (SrcReg)
1366       .addReg (NegHalfShiftReg);
1367     BuildMI (BB, V8::BA, 1).addMBB (continueMBB);
1368
1369     // Update machine-CFG edges
1370     BB->addSuccessor (continueMBB);
1371
1372     // .lshr_continue: ! [preds: begin, do_one_shift, do_two_shifts]
1373     //   phi (SrcReg, begin), (TwoShiftsOutReg, two_shifts),
1374     //       (OneShiftOutReg, one_shift), DestReg      ! Phi top half...
1375     //   phi (SrcReg+1, begin), (TwoShiftsOutReg+1, two_shifts),
1376     //       (OneShiftOutReg+1, one_shift), DestReg+1  ! And phi bottom half.
1377
1378     BB = continueMBB;
1379     BuildMI (BB, V8::PHI, 6, DestReg).addReg (SrcReg).addMBB (thisMBB)
1380       .addReg (TwoShiftsOutReg).addMBB (twoShiftsMBB)
1381       .addReg (OneShiftOutReg).addMBB (oneShiftMBB);
1382     BuildMI (BB, V8::PHI, 6, DestReg+1).addReg (SrcReg+1).addMBB (thisMBB)
1383       .addReg (TwoShiftsOutReg+1).addMBB (twoShiftsMBB)
1384       .addReg (OneShiftOutReg+1).addMBB (oneShiftMBB);
1385     return;
1386   }
1387   case Instruction::Shl:
1388   default:
1389     std::cerr << "Sorry, 64-bit shifts are not yet supported:\n" << I;
1390     abort ();
1391   }
1392 }
1393
1394 void V8ISel::visitBinaryOperator (Instruction &I) {
1395   unsigned DestReg = getReg (I);
1396   unsigned Op0Reg = getReg (I.getOperand (0));
1397
1398   unsigned Class = getClassB (I.getType());
1399   unsigned OpCase = ~0;
1400
1401   if (Class > cLong) {
1402     unsigned Op1Reg = getReg (I.getOperand (1));
1403     switch (I.getOpcode ()) {
1404     case Instruction::Add: OpCase = 0; break;
1405     case Instruction::Sub: OpCase = 1; break;
1406     case Instruction::Mul: OpCase = 2; break;
1407     case Instruction::Div: OpCase = 3; break;
1408     default: visitInstruction (I); return;
1409     }
1410     static unsigned Opcodes[] = { V8::FADDS, V8::FADDD,
1411                                   V8::FSUBS, V8::FSUBD,
1412                                   V8::FMULS, V8::FMULD,
1413                                   V8::FDIVS, V8::FDIVD };
1414     BuildMI (BB, Opcodes[2*OpCase + (Class - cFloat)], 2, DestReg)
1415       .addReg (Op0Reg).addReg (Op1Reg);
1416     return;
1417   }
1418
1419   unsigned ResultReg = DestReg;
1420   if (Class != cInt && Class != cLong)
1421     ResultReg = makeAnotherReg (I.getType ());
1422
1423   if (Class == cLong) {
1424     const char *FuncName;
1425     unsigned Op1Reg = getReg (I.getOperand (1));
1426     DEBUG (std::cerr << "Class = cLong\n");
1427     DEBUG (std::cerr << "Op0Reg = " << Op0Reg << ", " << Op0Reg+1 << "\n");
1428     DEBUG (std::cerr << "Op1Reg = " << Op1Reg << ", " << Op1Reg+1 << "\n");
1429     DEBUG (std::cerr << "ResultReg = " << ResultReg << ", " << ResultReg+1 << "\n");
1430     DEBUG (std::cerr << "DestReg = " << DestReg << ", " << DestReg+1 <<  "\n");
1431     switch (I.getOpcode ()) {
1432     case Instruction::Add:
1433       BuildMI (BB, V8::ADDCCrr, 2, ResultReg+1).addReg (Op0Reg+1)
1434         .addReg (Op1Reg+1);
1435       BuildMI (BB, V8::ADDXrr, 2, ResultReg).addReg (Op0Reg).addReg (Op1Reg);
1436       return;
1437     case Instruction::Sub:
1438       BuildMI (BB, V8::SUBCCrr, 2, ResultReg+1).addReg (Op0Reg+1)
1439         .addReg (Op1Reg+1);
1440       BuildMI (BB, V8::SUBXrr, 2, ResultReg).addReg (Op0Reg).addReg (Op1Reg);
1441       return;
1442     case Instruction::Mul:
1443       FuncName = I.getType ()->isSigned () ? "__mul64" : "__umul64";
1444       emitOp64LibraryCall (BB, BB->end (), DestReg, FuncName, Op0Reg, Op1Reg);
1445       return;
1446     case Instruction::Div:
1447       FuncName = I.getType ()->isSigned () ? "__div64" : "__udiv64";
1448       emitOp64LibraryCall (BB, BB->end (), DestReg, FuncName, Op0Reg, Op1Reg);
1449       return;
1450     case Instruction::Rem:
1451       FuncName = I.getType ()->isSigned () ? "__rem64" : "__urem64";
1452       emitOp64LibraryCall (BB, BB->end (), DestReg, FuncName, Op0Reg, Op1Reg);
1453       return;
1454     case Instruction::Shl:
1455     case Instruction::Shr:
1456       emitShift64 (BB, BB->end (), I, DestReg, Op0Reg, Op1Reg);
1457       return;
1458     }
1459   }
1460
1461   switch (I.getOpcode ()) {
1462   case Instruction::Add: OpCase = 0; break;
1463   case Instruction::Sub: OpCase = 1; break;
1464   case Instruction::Mul: OpCase = 2; break;
1465   case Instruction::And: OpCase = 3; break;
1466   case Instruction::Or:  OpCase = 4; break;
1467   case Instruction::Xor: OpCase = 5; break;
1468   case Instruction::Shl: OpCase = 6; break;
1469   case Instruction::Shr: OpCase = 7+I.getType()->isSigned(); break;
1470
1471   case Instruction::Div:
1472   case Instruction::Rem: {
1473     unsigned Dest = ResultReg;
1474     unsigned Op1Reg = getReg (I.getOperand (1));
1475     if (I.getOpcode() == Instruction::Rem)
1476       Dest = makeAnotherReg(I.getType());
1477
1478     // FIXME: this is probably only right for 32 bit operands.
1479     if (I.getType ()->isSigned()) {
1480       unsigned Tmp = makeAnotherReg (I.getType ());
1481       // Sign extend into the Y register
1482       BuildMI (BB, V8::SRAri, 2, Tmp).addReg (Op0Reg).addZImm (31);
1483       BuildMI (BB, V8::WRYrr, 2).addReg (Tmp).addReg (V8::G0);
1484       BuildMI (BB, V8::SDIVrr, 2, Dest).addReg (Op0Reg).addReg (Op1Reg);
1485     } else {
1486       // Zero extend into the Y register, ie, just set it to zero
1487       BuildMI (BB, V8::WRYrr, 2).addReg (V8::G0).addReg (V8::G0);
1488       BuildMI (BB, V8::UDIVrr, 2, Dest).addReg (Op0Reg).addReg (Op1Reg);
1489     }
1490
1491     if (I.getOpcode() == Instruction::Rem) {
1492       unsigned Tmp = makeAnotherReg (I.getType ());
1493       BuildMI (BB, V8::SMULrr, 2, Tmp).addReg(Dest).addReg(Op1Reg);
1494       BuildMI (BB, V8::SUBrr, 2, ResultReg).addReg(Op0Reg).addReg(Tmp);
1495     }
1496     break;
1497   }
1498   default:
1499     visitInstruction (I);
1500     return;
1501   }
1502
1503   static const unsigned Opcodes[] = {
1504     V8::ADDrr, V8::SUBrr, V8::SMULrr, V8::ANDrr, V8::ORrr, V8::XORrr,
1505     V8::SLLrr, V8::SRLrr, V8::SRArr
1506   };
1507   static const unsigned OpcodesRI[] = {
1508     V8::ADDri, V8::SUBri, V8::SMULri, V8::ANDri, V8::ORri, V8::XORri,
1509     V8::SLLri, V8::SRLri, V8::SRAri
1510   };
1511   unsigned Op1Reg = ~0U;
1512   if (OpCase != ~0U) {
1513     Value *Arg1 = I.getOperand (1);
1514     bool useImmed = false;
1515     int64_t Val = 0;
1516     if ((getClassB (I.getType ()) <= cInt) && (isa<ConstantIntegral> (Arg1))) {
1517       Val = cast<ConstantIntegral> (Arg1)->getRawValue ();
1518       useImmed = (Val > -4096 && Val < 4095);
1519     }
1520     if (useImmed) {
1521       BuildMI (BB, OpcodesRI[OpCase], 2, ResultReg).addReg (Op0Reg).addSImm (Val);
1522     } else {
1523       Op1Reg = getReg (I.getOperand (1));
1524       BuildMI (BB, Opcodes[OpCase], 2, ResultReg).addReg (Op0Reg).addReg (Op1Reg);
1525     }
1526   }
1527
1528   switch (getClassB (I.getType ())) {
1529     case cByte:
1530       if (I.getType ()->isSigned ()) { // add byte
1531         BuildMI (BB, V8::ANDri, 2, DestReg).addReg (ResultReg).addZImm (0xff);
1532       } else { // add ubyte
1533         unsigned TmpReg = makeAnotherReg (I.getType ());
1534         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (24);
1535         BuildMI (BB, V8::SRAri, 2, DestReg).addReg (TmpReg).addZImm (24);
1536       }
1537       break;
1538     case cShort:
1539       if (I.getType ()->isSigned ()) { // add short
1540         unsigned TmpReg = makeAnotherReg (I.getType ());
1541         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (16);
1542         BuildMI (BB, V8::SRAri, 2, DestReg).addReg (TmpReg).addZImm (16);
1543       } else { // add ushort
1544         unsigned TmpReg = makeAnotherReg (I.getType ());
1545         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (16);
1546         BuildMI (BB, V8::SRLri, 2, DestReg).addReg (TmpReg).addZImm (16);
1547       }
1548       break;
1549     case cInt:
1550       // Nothing to do here.
1551       break;
1552     case cLong: {
1553       // Only support and, or, xor here - others taken care of above.
1554       if (OpCase < 3 || OpCase > 5) {
1555         visitInstruction (I);
1556         return;
1557       }
1558       // Do the other half of the value:
1559       BuildMI (BB, Opcodes[OpCase], 2, ResultReg+1).addReg (Op0Reg+1)
1560         .addReg (Op1Reg+1);
1561       break;
1562     }
1563     default:
1564       visitInstruction (I);
1565   }
1566 }
1567
1568 void V8ISel::visitSetCondInst(SetCondInst &I) {
1569   if (canFoldSetCCIntoBranch(&I))
1570     return;  // Fold this into a branch.
1571
1572   unsigned Op0Reg = getReg (I.getOperand (0));
1573   unsigned Op1Reg = getReg (I.getOperand (1));
1574   unsigned DestReg = getReg (I);
1575   const Type *Ty = I.getOperand (0)->getType ();
1576
1577   // Compare the two values.
1578   if (getClass (Ty) < cLong) {
1579     BuildMI(BB, V8::SUBCCrr, 2, V8::G0).addReg(Op0Reg).addReg(Op1Reg);
1580   } else if (getClass (Ty) == cLong) {
1581     switch (I.getOpcode()) {
1582     default: assert(0 && "Unknown setcc instruction!");
1583     case Instruction::SetEQ:
1584     case Instruction::SetNE: {
1585       unsigned TempReg0 = makeAnotherReg (Type::IntTy),
1586                TempReg1 = makeAnotherReg (Type::IntTy),
1587                TempReg2 = makeAnotherReg (Type::IntTy),
1588                TempReg3 = makeAnotherReg (Type::IntTy);
1589       MachineOpCode Opcode;
1590       int Immed;
1591       // These guys are special - no branches needed!
1592       BuildMI (BB, V8::XORrr, 2, TempReg0).addReg (Op0Reg+1).addReg (Op1Reg+1);
1593       BuildMI (BB, V8::XORrr, 2, TempReg1).addReg (Op0Reg).addReg (Op1Reg);
1594       BuildMI (BB, V8::SUBCCrr, 2, V8::G0).addReg (V8::G0).addReg (TempReg1);
1595       Opcode = I.getOpcode() == Instruction::SetEQ ? V8::SUBXri : V8::ADDXri;
1596       Immed  = I.getOpcode() == Instruction::SetEQ ? -1         : 0;
1597       BuildMI (BB, Opcode, 2, TempReg2).addReg (V8::G0).addSImm (Immed);
1598       BuildMI (BB, V8::SUBCCrr, 2, V8::G0).addReg (V8::G0).addReg (TempReg0);
1599       BuildMI (BB, Opcode, 2, TempReg3).addReg (V8::G0).addSImm (Immed);
1600       Opcode = I.getOpcode() == Instruction::SetEQ ? V8::ANDrr  : V8::ORrr;
1601       BuildMI (BB, Opcode, 2, DestReg).addReg (TempReg2).addReg (TempReg3);
1602       return;
1603     }
1604     case Instruction::SetLT:
1605     case Instruction::SetGE:
1606       BuildMI (BB, V8::SUBCCrr, 2, V8::G0).addReg (Op0Reg+1).addReg (Op1Reg+1);
1607       BuildMI (BB, V8::SUBXCCrr, 2, V8::G0).addReg (Op0Reg).addReg (Op1Reg);
1608       break;
1609     case Instruction::SetGT:
1610     case Instruction::SetLE:
1611       BuildMI (BB, V8::SUBCCri, 2, V8::G0).addReg (V8::G0).addSImm (1);
1612       BuildMI (BB, V8::SUBXCCrr, 2, V8::G0).addReg (Op0Reg+1).addReg (Op1Reg+1);
1613       BuildMI (BB, V8::SUBXCCrr, 2, V8::G0).addReg (Op0Reg).addReg (Op1Reg);
1614       break;
1615     }
1616   } else if (getClass (Ty) == cFloat) {
1617     BuildMI(BB, V8::FCMPS, 2).addReg(Op0Reg).addReg(Op1Reg);
1618   } else if (getClass (Ty) == cDouble) {
1619     BuildMI(BB, V8::FCMPD, 2).addReg(Op0Reg).addReg(Op1Reg);
1620   }
1621
1622   unsigned BranchIdx;
1623   switch (I.getOpcode()) {
1624   default: assert(0 && "Unknown setcc instruction!");
1625   case Instruction::SetEQ: BranchIdx = 0; break;
1626   case Instruction::SetNE: BranchIdx = 1; break;
1627   case Instruction::SetLT: BranchIdx = 2; break;
1628   case Instruction::SetGT: BranchIdx = 3; break;
1629   case Instruction::SetLE: BranchIdx = 4; break;
1630   case Instruction::SetGE: BranchIdx = 5; break;
1631   }
1632
1633   unsigned Column = 0;
1634   if (Ty->isSigned() && !Ty->isFloatingPoint()) Column = 1;
1635   if (Ty->isFloatingPoint()) Column = 2;
1636   static unsigned OpcodeTab[3*6] = {
1637                                  // LLVM            SparcV8
1638                                  //        unsigned signed  fp
1639     V8::BE,   V8::BE,  V8::FBE,  // seteq = be      be      fbe
1640     V8::BNE,  V8::BNE, V8::FBNE, // setne = bne     bne     fbne
1641     V8::BCS,  V8::BL,  V8::FBL,  // setlt = bcs     bl      fbl
1642     V8::BGU,  V8::BG,  V8::FBG,  // setgt = bgu     bg      fbg
1643     V8::BLEU, V8::BLE, V8::FBLE, // setle = bleu    ble     fble
1644     V8::BCC,  V8::BGE, V8::FBGE  // setge = bcc     bge     fbge
1645   };
1646   unsigned Opcode = OpcodeTab[3*BranchIdx + Column];
1647
1648   MachineBasicBlock *thisMBB = BB;
1649   const BasicBlock *LLVM_BB = BB->getBasicBlock ();
1650   //  thisMBB:
1651   //  ...
1652   //   subcc %reg0, %reg1, %g0
1653   //   TrueVal = or G0, 1
1654   //   bCC sinkMBB
1655
1656   unsigned TrueValue = makeAnotherReg (I.getType ());
1657   BuildMI (BB, V8::ORri, 2, TrueValue).addReg (V8::G0).addZImm (1);
1658
1659   MachineBasicBlock *copy0MBB = new MachineBasicBlock (LLVM_BB);
1660   MachineBasicBlock *sinkMBB = new MachineBasicBlock (LLVM_BB);
1661   BuildMI (BB, Opcode, 1).addMBB (sinkMBB);
1662
1663   // Update machine-CFG edges
1664   BB->addSuccessor (sinkMBB);
1665   BB->addSuccessor (copy0MBB);
1666
1667   //  copy0MBB:
1668   //   %FalseValue = or %G0, 0
1669   //   # fall through
1670   BB = copy0MBB;
1671   F->getBasicBlockList ().push_back (BB);
1672   unsigned FalseValue = makeAnotherReg (I.getType ());
1673   BuildMI (BB, V8::ORrr, 2, FalseValue).addReg (V8::G0).addReg (V8::G0);
1674
1675   // Update machine-CFG edges
1676   BB->addSuccessor (sinkMBB);
1677
1678   DEBUG (std::cerr << "thisMBB is at " << (void*)thisMBB << "\n");
1679   DEBUG (std::cerr << "copy0MBB is at " << (void*)copy0MBB << "\n");
1680   DEBUG (std::cerr << "sinkMBB is at " << (void*)sinkMBB << "\n");
1681
1682   //  sinkMBB:
1683   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1684   //  ...
1685   BB = sinkMBB;
1686   F->getBasicBlockList ().push_back (BB);
1687   BuildMI (BB, V8::PHI, 4, DestReg).addReg (FalseValue)
1688     .addMBB (copy0MBB).addReg (TrueValue).addMBB (thisMBB);
1689 }
1690
1691 void V8ISel::visitAllocaInst(AllocaInst &I) {
1692   // Find the data size of the alloca inst's getAllocatedType.
1693   const Type *Ty = I.getAllocatedType();
1694   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
1695
1696   unsigned ArraySizeReg = getReg (I.getArraySize ());
1697   unsigned TySizeReg = getReg (ConstantUInt::get (Type::UIntTy, TySize));
1698   unsigned TmpReg1 = makeAnotherReg (Type::UIntTy);
1699   unsigned TmpReg2 = makeAnotherReg (Type::UIntTy);
1700   unsigned StackAdjReg = makeAnotherReg (Type::UIntTy);
1701
1702   // StackAdjReg = (ArraySize * TySize) rounded up to nearest
1703   // doubleword boundary.
1704   BuildMI (BB, V8::UMULrr, 2, TmpReg1).addReg (ArraySizeReg).addReg (TySizeReg);
1705
1706   // Round up TmpReg1 to nearest doubleword boundary:
1707   BuildMI (BB, V8::ADDri, 2, TmpReg2).addReg (TmpReg1).addSImm (7);
1708   BuildMI (BB, V8::ANDri, 2, StackAdjReg).addReg (TmpReg2).addSImm (-8);
1709
1710   // Subtract size from stack pointer, thereby allocating some space.
1711   BuildMI (BB, V8::SUBrr, 2, V8::O6).addReg (V8::O6).addReg (StackAdjReg);
1712
1713   // Put a pointer to the space into the result register, by copying
1714   // the stack pointer.
1715   BuildMI (BB, V8::ADDri, 2, getReg(I)).addReg (V8::O6).addSImm (96);
1716
1717   // Inform the Frame Information that we have just allocated a variable-sized
1718   // object.
1719   F->getFrameInfo()->CreateVariableSizedObject();
1720 }
1721
1722 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1723 /// function, lowering any calls to unknown intrinsic functions into the
1724 /// equivalent LLVM code.
1725 void V8ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1726   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1727     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1728       if (CallInst *CI = dyn_cast<CallInst>(I++))
1729         if (Function *F = CI->getCalledFunction())
1730           switch (F->getIntrinsicID()) {
1731           case Intrinsic::vastart:
1732           case Intrinsic::vacopy:
1733           case Intrinsic::vaend:
1734             // We directly implement these intrinsics
1735           case Intrinsic::not_intrinsic: break;
1736           default:
1737             // All other intrinsic calls we must lower.
1738             Instruction *Before = CI->getPrev();
1739             TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1740             if (Before) {        // Move iterator to instruction after call
1741               I = Before;  ++I;
1742             } else {
1743               I = BB->begin();
1744             }
1745           }
1746 }
1747
1748
1749 void V8ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1750   switch (ID) {
1751   default:
1752     std::cerr << "Sorry, unknown intrinsic function call:\n" << CI; abort ();
1753
1754   case Intrinsic::vastart: {
1755     // Add the VarArgsOffset to the frame pointer, and copy it to the result.
1756     unsigned DestReg = getReg (CI.getOperand(1));
1757     unsigned Tmp = makeAnotherReg(Type::IntTy);
1758     BuildMI (BB, V8::ADDri, 2, Tmp).addReg (V8::I6).addSImm (VarArgsOffset);
1759     BuildMI(BB, V8::STri, 3).addReg(DestReg).addSImm(0).addReg(Tmp);
1760     return;
1761   }
1762
1763   case Intrinsic::vaend:
1764     // va_end is a no-op on SparcV8.
1765     return;
1766
1767   case Intrinsic::vacopy: {
1768     // Copy the va_list ptr (arg1) to the result.
1769     unsigned DestReg = getReg (CI.getOperand(1)), SrcReg = getReg (CI.getOperand (2));
1770     BuildMI(BB, V8::STri, 3).addReg(DestReg).addSImm(0).addReg(SrcReg);
1771     return;
1772   }
1773   }
1774 }
1775
1776 void V8ISel::visitVAArgInst (VAArgInst &I) {
1777   unsigned VAListPtr = getReg (I.getOperand (0));
1778   unsigned DestReg = getReg (I);
1779   unsigned Size;
1780   unsigned VAList = makeAnotherReg(Type::IntTy);
1781   BuildMI(BB, V8::LDri, 2, VAList).addReg(VAListPtr).addSImm(0);
1782
1783   switch (I.getType ()->getTypeID ()) {
1784   case Type::PointerTyID:
1785   case Type::UIntTyID:
1786   case Type::IntTyID:
1787     Size = 4;
1788     BuildMI (BB, V8::LDri, 2, DestReg).addReg (VAList).addSImm (0);
1789     break;
1790
1791   case Type::ULongTyID:
1792   case Type::LongTyID:
1793     Size = 8;
1794     BuildMI (BB, V8::LDri, 2, DestReg).addReg (VAList).addSImm (0);
1795     BuildMI (BB, V8::LDri, 2, DestReg+1).addReg (VAList).addSImm (4);
1796     break;
1797
1798   case Type::DoubleTyID: {
1799     Size = 8;
1800     unsigned DblAlign = TM.getTargetData().getDoubleAlignment();
1801     unsigned TempReg = makeAnotherReg (Type::IntTy);
1802     unsigned TempReg2 = makeAnotherReg (Type::IntTy);
1803     int FI = F->getFrameInfo()->CreateStackObject(8, DblAlign);
1804     BuildMI (BB, V8::LDri, 2, TempReg).addReg (VAList).addSImm (0);
1805     BuildMI (BB, V8::LDri, 2, TempReg2).addReg (VAList).addSImm (4);
1806     BuildMI (BB, V8::STri, 3).addFrameIndex (FI).addSImm (0).addReg (TempReg);
1807     BuildMI (BB, V8::STri, 3).addFrameIndex (FI).addSImm (4).addReg (TempReg2);
1808     BuildMI (BB, V8::LDDFri, 2, DestReg).addFrameIndex (FI).addSImm (0);
1809     break;
1810   }
1811
1812   default:
1813     std::cerr << "Sorry, vaarg instruction of this type still unsupported:\n"
1814               << I;
1815     abort ();
1816     return;
1817   }
1818   unsigned tmp = makeAnotherReg(Type::IntTy);
1819   BuildMI (BB, V8::ADDri, 2, tmp).addReg(VAList).addSImm(Size);
1820   BuildMI(BB, V8::STri, 3).addReg(VAListPtr).addSImm(0).addReg(VAList);
1821   return;
1822 }