CPR fixes
[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 "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 #include <iostream>
31 using namespace llvm;
32
33 namespace {
34   struct V8ISel : public FunctionPass, public InstVisitor<V8ISel> {
35     TargetMachine &TM;
36     MachineFunction *F;                 // The function we are compiling into
37     MachineBasicBlock *BB;              // The current MBB we are compiling
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     /// visitBasicBlock - This method is called when we are visiting a new basic
69     /// block.  This simply creates a new MachineBasicBlock to emit code into
70     /// and adds it to the current MachineFunction.  Subsequent visit* for
71     /// instructions will be invoked for all instructions in the basic block.
72     ///
73     void visitBasicBlock(BasicBlock &LLVM_BB) {
74       BB = MBBMap[&LLVM_BB];
75     }
76
77     void visitBinaryOperator(Instruction &I);
78     void visitShiftInst (ShiftInst &SI) { visitBinaryOperator (SI); }
79     void visitSetCondInst(SetCondInst &I);
80     void visitCallInst(CallInst &I);
81     void visitReturnInst(ReturnInst &I);
82     void visitBranchInst(BranchInst &I);
83     void visitCastInst(CastInst &I);
84     void visitLoadInst(LoadInst &I);
85     void visitStoreInst(StoreInst &I);
86     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
87     void visitGetElementPtrInst(GetElementPtrInst &I);
88     void visitAllocaInst(AllocaInst &I);
89
90     void visitInstruction(Instruction &I) {
91       std::cerr << "Unhandled instruction: " << I;
92       abort();
93     }
94
95     /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
96     /// function, lowering any calls to unknown intrinsic functions into the
97     /// equivalent LLVM code.
98     void LowerUnknownIntrinsicFunctionCalls(Function &F);
99     void visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI);
100
101     void LoadArgumentsToVirtualRegs(Function *F);
102
103     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
104     /// because we have to generate our sources into the source basic blocks,
105     /// not the current one.
106     ///
107     void SelectPHINodes();
108
109     /// copyConstantToRegister - Output the instructions required to put the
110     /// specified constant into the specified register.
111     ///
112     void copyConstantToRegister(MachineBasicBlock *MBB,
113                                 MachineBasicBlock::iterator IP,
114                                 Constant *C, unsigned R);
115
116     /// makeAnotherReg - This method returns the next register number we haven't
117     /// yet used.
118     ///
119     /// Long values are handled somewhat specially.  They are always allocated
120     /// as pairs of 32 bit integer values.  The register number returned is the
121     /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
122     /// of the long value.
123     ///
124     unsigned makeAnotherReg(const Type *Ty) {
125       assert(dynamic_cast<const SparcV8RegisterInfo*>(TM.getRegisterInfo()) &&
126              "Current target doesn't have SparcV8 reg info??");
127       const SparcV8RegisterInfo *MRI =
128         static_cast<const SparcV8RegisterInfo*>(TM.getRegisterInfo());
129       if (Ty == Type::LongTy || Ty == Type::ULongTy) {
130         const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
131         // Create the lower part
132         F->getSSARegMap()->createVirtualRegister(RC);
133         // Create the upper part.
134         return F->getSSARegMap()->createVirtualRegister(RC)-1;
135       }
136
137       // Add the mapping of regnumber => reg class to MachineFunction
138       const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
139       return F->getSSARegMap()->createVirtualRegister(RC);
140     }
141
142     unsigned getReg(Value &V) { return getReg (&V); } // allow refs.
143     unsigned getReg(Value *V) {
144       // Just append to the end of the current bb.
145       MachineBasicBlock::iterator It = BB->end();
146       return getReg(V, BB, It);
147     }
148     unsigned getReg(Value *V, MachineBasicBlock *MBB,
149                     MachineBasicBlock::iterator IPt) {
150       unsigned &Reg = RegMap[V];
151       if (Reg == 0) {
152         Reg = makeAnotherReg(V->getType());
153         RegMap[V] = Reg;
154       }
155       // If this operand is a constant, emit the code to copy the constant into
156       // the register here...
157       //
158       if (Constant *C = dyn_cast<Constant>(V)) {
159         copyConstantToRegister(MBB, IPt, C, Reg);
160         RegMap.erase(V);  // Assign a new name to this constant if ref'd again
161       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
162         // Move the address of the global into the register
163         unsigned TmpReg = makeAnotherReg(V->getType());
164         BuildMI (*MBB, IPt, V8::SETHIi, 1, TmpReg).addGlobalAddress (GV);
165         BuildMI (*MBB, IPt, V8::ORri, 2, Reg).addReg (TmpReg)
166           .addGlobalAddress (GV);
167         RegMap.erase(V);  // Assign a new name to this address if ref'd again
168       }
169
170       return Reg;
171     }
172
173   };
174 }
175
176 FunctionPass *llvm::createSparcV8SimpleInstructionSelector(TargetMachine &TM) {
177   return new V8ISel(TM);
178 }
179
180 enum TypeClass {
181   cByte, cShort, cInt, cLong, cFloat, cDouble
182 };
183
184 static TypeClass getClass (const Type *T) {
185   switch (T->getTypeID()) {
186     case Type::UByteTyID:  case Type::SByteTyID:  return cByte;
187     case Type::UShortTyID: case Type::ShortTyID:  return cShort;
188     case Type::PointerTyID:
189     case Type::UIntTyID:   case Type::IntTyID:    return cInt;
190     case Type::ULongTyID:  case Type::LongTyID:   return cLong;
191     case Type::FloatTyID:                         return cFloat;
192     case Type::DoubleTyID:                        return cDouble;
193     default:
194       assert (0 && "Type of unknown class passed to getClass?");
195       return cByte;
196   }
197 }
198 static TypeClass getClassB(const Type *T) {
199   if (T == Type::BoolTy) return cByte;
200   return getClass(T);
201 }
202
203
204
205 /// copyConstantToRegister - Output the instructions required to put the
206 /// specified constant into the specified register.
207 ///
208 void V8ISel::copyConstantToRegister(MachineBasicBlock *MBB,
209                                     MachineBasicBlock::iterator IP,
210                                     Constant *C, unsigned R) {
211   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
212     switch (CE->getOpcode()) {
213     case Instruction::GetElementPtr:
214       emitGEPOperation(MBB, IP, CE->getOperand(0),
215                        CE->op_begin()+1, CE->op_end(), R);
216       return;
217     case Instruction::Cast:
218       emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
219       return;
220     default:
221       std::cerr << "Copying this constant expr not yet handled: " << *CE;
222       abort();
223     }
224   }
225
226   if (C->getType()->isIntegral ()) {
227     uint64_t Val;
228     unsigned Class = getClassB (C->getType ());
229     if (Class == cLong) {
230       unsigned TmpReg = makeAnotherReg (Type::IntTy);
231       unsigned TmpReg2 = makeAnotherReg (Type::IntTy);
232       // Copy the value into the register pair.
233       // R = top(more-significant) half, R+1 = bottom(less-significant) half
234       uint64_t Val = cast<ConstantInt>(C)->getRawValue();
235       unsigned bottomHalf = Val & 0xffffffffU;
236       unsigned topHalf = Val >> 32;
237       unsigned HH = topHalf >> 10;
238       unsigned HM = topHalf & 0x03ff;
239       unsigned LM = bottomHalf >> 10;
240       unsigned LO = bottomHalf & 0x03ff;
241       BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg).addZImm(HH);
242       BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (TmpReg)
243         .addSImm (HM);
244       BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg2).addZImm(LM);
245       BuildMI (*MBB, IP, V8::ORri, 2, R+1).addReg (TmpReg2)
246         .addSImm (LO);
247       return;
248     }
249
250     assert(Class <= cInt && "Type not handled yet!");
251
252     if (C->getType() == Type::BoolTy) {
253       Val = (C == ConstantBool::True);
254     } else {
255       ConstantInt *CI = cast<ConstantInt> (C);
256       Val = CI->getRawValue ();
257     }
258     switch (Class) {
259       case cByte:  Val =  (int8_t) Val; break;
260       case cShort: Val = (int16_t) Val; break;
261       case cInt:   Val = (int32_t) Val; break;
262       default:
263         std::cerr << "Offending constant: " << *C << "\n";
264         assert (0 && "Can't copy this kind of constant into register yet");
265         return;
266     }
267     if (Val == 0) {
268       BuildMI (*MBB, IP, V8::ORrr, 2, R).addReg (V8::G0).addReg(V8::G0);
269     } else if (((int64_t)Val >= -4096) && ((int64_t)Val <= 4095)) {
270       BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (V8::G0).addSImm(Val);
271     } else {
272       unsigned TmpReg = makeAnotherReg (C->getType ());
273       BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg)
274         .addSImm (((uint32_t) Val) >> 10);
275       BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (TmpReg)
276         .addSImm (((uint32_t) Val) & 0x03ff);
277       return;
278     }
279   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
280     // We need to spill the constant to memory...
281     MachineConstantPool *CP = F->getConstantPool();
282     unsigned CPI = CP->getConstantPoolIndex(CFP);
283     const Type *Ty = CFP->getType();
284
285     assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
286     unsigned LoadOpcode = Ty == Type::FloatTy ? V8::LDFri : V8::LDDFri;
287     BuildMI (*MBB, IP, LoadOpcode, 2, R).addConstantPoolIndex (CPI).addSImm (0);
288   } else if (isa<ConstantPointerNull>(C)) {
289     // Copy zero (null pointer) to the register.
290     BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (V8::G0).addSImm (0);
291   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
292     // Copy it with a SETHI/OR pair; the JIT + asmwriter should recognize
293     // that SETHI %reg,global == SETHI %reg,%hi(global) and 
294     // OR %reg,global,%reg == OR %reg,%lo(global),%reg.
295     unsigned TmpReg = makeAnotherReg (C->getType ());
296     BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg).addGlobalAddress(GV);
297     BuildMI (*MBB, IP, V8::ORri, 2, R).addReg(TmpReg).addGlobalAddress(GV);
298   } else {
299     std::cerr << "Offending constant: " << *C << "\n";
300     assert (0 && "Can't copy this kind of constant into register yet");
301   }
302 }
303
304 void V8ISel::LoadArgumentsToVirtualRegs (Function *LF) {
305   unsigned ArgOffset;
306   static const unsigned IncomingArgRegs[] = { V8::I0, V8::I1, V8::I2,
307     V8::I3, V8::I4, V8::I5 };
308   assert (LF->asize () < 7
309           && "Can't handle loading excess call args off the stack yet");
310
311   // Add IMPLICIT_DEFs of input regs.
312   ArgOffset = 0;
313   for (Function::aiterator I = LF->abegin(), E = LF->aend(); I != E; ++I) {
314     unsigned Reg = getReg(*I);
315     switch (getClassB(I->getType())) {
316     case cByte:
317     case cShort:
318     case cInt:
319     case cFloat:
320       BuildMI(BB, V8::IMPLICIT_DEF, 0, IncomingArgRegs[ArgOffset]);
321       break;
322     default:
323       // FIXME: handle cDouble, cLong
324       assert (0 && "64-bit (double, long, etc.) function args not handled");
325       return;
326     }
327     ++ArgOffset;
328   }
329
330   ArgOffset = 0;
331   for (Function::aiterator I = LF->abegin(), E = LF->aend(); I != E; ++I) {
332     unsigned Reg = getReg(*I);
333     switch (getClassB(I->getType())) {
334     case cByte:
335     case cShort:
336     case cInt:
337       BuildMI(BB, V8::ORrr, 2, Reg).addReg (V8::G0)
338         .addReg (IncomingArgRegs[ArgOffset]);
339       break;
340     case cFloat: {
341       // Single-fp args are passed in integer registers; go through
342       // memory to get them into FP registers. (Bleh!)
343       unsigned FltAlign = TM.getTargetData().getFloatAlignment();
344       int FI = F->getFrameInfo()->CreateStackObject(4, FltAlign);
345       BuildMI (BB, V8::ST, 3).addFrameIndex (FI).addSImm (0)
346         .addReg (IncomingArgRegs[ArgOffset]);
347       BuildMI (BB, V8::LDFri, 2, Reg).addFrameIndex (FI).addSImm (0);
348       break;
349     }
350     default:
351       // FIXME: handle cDouble, cLong
352       assert (0 && "64-bit (double, long, etc.) function args not handled");
353       return;
354     }
355     ++ArgOffset;
356   }
357
358 }
359
360 void V8ISel::SelectPHINodes() {
361   const TargetInstrInfo &TII = *TM.getInstrInfo();
362   const Function &LF = *F->getFunction();  // The LLVM function...
363   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
364     const BasicBlock *BB = I;
365     MachineBasicBlock &MBB = *MBBMap[I];
366
367     // Loop over all of the PHI nodes in the LLVM basic block...
368     MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
369     for (BasicBlock::const_iterator I = BB->begin();
370          PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
371
372       // Create a new machine instr PHI node, and insert it.
373       unsigned PHIReg = getReg(*PN);
374       MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
375                                     V8::PHI, PN->getNumOperands(), PHIReg);
376
377       MachineInstr *LongPhiMI = 0;
378       if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
379         LongPhiMI = BuildMI(MBB, PHIInsertPoint,
380                             V8::PHI, PN->getNumOperands(), PHIReg+1);
381
382       // PHIValues - Map of blocks to incoming virtual registers.  We use this
383       // so that we only initialize one incoming value for a particular block,
384       // even if the block has multiple entries in the PHI node.
385       //
386       std::map<MachineBasicBlock*, unsigned> PHIValues;
387
388       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
389         MachineBasicBlock *PredMBB = 0;
390         for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
391              PE = MBB.pred_end (); PI != PE; ++PI)
392           if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
393             PredMBB = *PI;
394             break;
395           }
396         assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
397         
398         unsigned ValReg;
399         std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
400           PHIValues.lower_bound(PredMBB);
401
402         if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
403           // We already inserted an initialization of the register for this
404           // predecessor.  Recycle it.
405           ValReg = EntryIt->second;
406
407         } else {        
408           // Get the incoming value into a virtual register.
409           //
410           Value *Val = PN->getIncomingValue(i);
411
412           // If this is a constant or GlobalValue, we may have to insert code
413           // into the basic block to compute it into a virtual register.
414           if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
415               isa<GlobalValue>(Val)) {
416             // Simple constants get emitted at the end of the basic block,
417             // before any terminator instructions.  We "know" that the code to
418             // move a constant into a register will never clobber any flags.
419             ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
420           } else {
421             // Because we don't want to clobber any values which might be in
422             // physical registers with the computation of this constant (which
423             // might be arbitrarily complex if it is a constant expression),
424             // just insert the computation at the top of the basic block.
425             MachineBasicBlock::iterator PI = PredMBB->begin();
426             
427             // Skip over any PHI nodes though!
428             while (PI != PredMBB->end() && PI->getOpcode() == V8::PHI)
429               ++PI;
430             
431             ValReg = getReg(Val, PredMBB, PI);
432           }
433
434           // Remember that we inserted a value for this PHI for this predecessor
435           PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
436         }
437
438         PhiMI->addRegOperand(ValReg);
439         PhiMI->addMachineBasicBlockOperand(PredMBB);
440         if (LongPhiMI) {
441           LongPhiMI->addRegOperand(ValReg+1);
442           LongPhiMI->addMachineBasicBlockOperand(PredMBB);
443         }
444       }
445
446       // Now that we emitted all of the incoming values for the PHI node, make
447       // sure to reposition the InsertPoint after the PHI that we just added.
448       // This is needed because we might have inserted a constant into this
449       // block, right after the PHI's which is before the old insert point!
450       PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
451       ++PHIInsertPoint;
452     }
453   }
454 }
455
456 bool V8ISel::runOnFunction(Function &Fn) {
457   // First pass over the function, lower any unknown intrinsic functions
458   // with the IntrinsicLowering class.
459   LowerUnknownIntrinsicFunctionCalls(Fn);
460   
461   F = &MachineFunction::construct(&Fn, TM);
462   
463   // Create all of the machine basic blocks for the function...
464   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
465     F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
466   
467   BB = &F->front();
468   
469   // Set up a frame object for the return address.  This is used by the
470   // llvm.returnaddress & llvm.frameaddress intrinisics.
471   //ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
472   
473   // Copy incoming arguments off of the stack and out of fixed registers.
474   LoadArgumentsToVirtualRegs(&Fn);
475   
476   // Instruction select everything except PHI nodes
477   visit(Fn);
478   
479   // Select the PHI nodes
480   SelectPHINodes();
481   
482   RegMap.clear();
483   MBBMap.clear();
484   F = 0;
485   // We always build a machine code representation for the function
486   return true;
487 }
488
489 void V8ISel::visitCastInst(CastInst &I) {
490   Value *Op = I.getOperand(0);
491   unsigned DestReg = getReg(I);
492   MachineBasicBlock::iterator MI = BB->end();
493   emitCastOperation(BB, MI, Op, I.getType(), DestReg);
494 }
495
496 /// emitCastOperation - Common code shared between visitCastInst and constant
497 /// expression cast support.
498 ///
499 void V8ISel::emitCastOperation(MachineBasicBlock *BB,
500                              MachineBasicBlock::iterator IP,
501                              Value *Src, const Type *DestTy,
502                              unsigned DestReg) {
503   const Type *SrcTy = Src->getType();
504   unsigned SrcClass = getClassB(SrcTy);
505   unsigned DestClass = getClassB(DestTy);
506   unsigned SrcReg = getReg(Src, BB, IP);
507
508   const Type *oldTy = SrcTy;
509   const Type *newTy = DestTy;
510   unsigned oldTyClass = SrcClass;
511   unsigned newTyClass = DestClass;
512
513   if (oldTyClass < cLong && newTyClass < cLong) {
514     if (oldTyClass >= newTyClass) {
515       // Emit a reg->reg copy to do a equal-size or narrowing cast,
516       // and do sign/zero extension (necessary if we change signedness).
517       unsigned TmpReg1 = makeAnotherReg (newTy);
518       unsigned TmpReg2 = makeAnotherReg (newTy);
519       BuildMI (*BB, IP, V8::ORrr, 2, TmpReg1).addReg (V8::G0).addReg (SrcReg);
520       unsigned shiftWidth = 32 - (8 * TM.getTargetData ().getTypeSize (newTy));
521       BuildMI (*BB, IP, V8::SLLri, 2, TmpReg2).addZImm (shiftWidth).addReg(TmpReg1);
522       if (newTy->isSigned ()) { // sign-extend with SRA
523         BuildMI(*BB, IP, V8::SRAri, 2, DestReg).addZImm (shiftWidth).addReg(TmpReg2);
524       } else { // zero-extend with SRL
525         BuildMI(*BB, IP, V8::SRLri, 2, DestReg).addZImm (shiftWidth).addReg(TmpReg2);
526       }
527     } else {
528       unsigned TmpReg1 = makeAnotherReg (oldTy);
529       unsigned TmpReg2 = makeAnotherReg (newTy);
530       unsigned TmpReg3 = makeAnotherReg (newTy);
531       // Widening integer cast. Make sure it's fully sign/zero-extended
532       // wrt the input type, then make sure it's fully sign/zero-extended wrt
533       // the output type. Kind of stupid, but simple...
534       unsigned shiftWidth = 32 - (8 * TM.getTargetData ().getTypeSize (oldTy));
535       BuildMI (*BB, IP, V8::SLLri, 2, TmpReg1).addZImm (shiftWidth).addReg(SrcReg);
536       if (oldTy->isSigned ()) { // sign-extend with SRA
537         BuildMI(*BB, IP, V8::SRAri, 2, TmpReg2).addZImm (shiftWidth).addReg(TmpReg1);
538       } else { // zero-extend with SRL
539         BuildMI(*BB, IP, V8::SRLri, 2, TmpReg2).addZImm (shiftWidth).addReg(TmpReg1);
540       }
541       shiftWidth = 32 - (8 * TM.getTargetData ().getTypeSize (newTy));
542       BuildMI (*BB, IP, V8::SLLri, 2, TmpReg3).addZImm (shiftWidth).addReg(TmpReg2);
543       if (newTy->isSigned ()) { // sign-extend with SRA
544         BuildMI(*BB, IP, V8::SRAri, 2, DestReg).addZImm (shiftWidth).addReg(TmpReg3);
545       } else { // zero-extend with SRL
546         BuildMI(*BB, IP, V8::SRLri, 2, DestReg).addZImm (shiftWidth).addReg(TmpReg3);
547       }
548     }
549   } else {
550     if (newTyClass == cFloat) {
551       assert (oldTyClass != cLong && "cast long to float not implemented yet");
552       switch (oldTyClass) {
553       case cFloat:
554         BuildMI (*BB, IP, V8::FMOVS, 1, DestReg).addReg (SrcReg);
555         break;
556       case cDouble:
557         BuildMI (*BB, IP, V8::FDTOS, 1, DestReg).addReg (SrcReg);
558         break;
559       default: {
560         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
561         // cast int to float.  Store it to a stack slot and then load
562         // it using ldf into a floating point register. then do fitos.
563         unsigned TmpReg = makeAnotherReg (newTy);
564         int FI = F->getFrameInfo()->CreateStackObject(4, FltAlign);
565         BuildMI (*BB, IP, V8::ST, 3).addFrameIndex (FI).addSImm (0)
566           .addReg (SrcReg);
567         BuildMI (*BB, IP, V8::LDFri, 2, TmpReg).addFrameIndex (FI).addSImm (0);
568         BuildMI (*BB, IP, V8::FITOS, 1, DestReg).addReg(TmpReg);
569         break;
570       }
571       }
572     } else if (newTyClass == cDouble) {
573       assert (oldTyClass != cLong && "cast long to double not implemented yet");
574       switch (oldTyClass) {
575       case cFloat:
576         BuildMI (*BB, IP, V8::FSTOD, 1, DestReg).addReg (SrcReg);
577         break;
578       case cDouble: {
579         // go through memory, for now
580         unsigned DoubleAlignment = TM.getTargetData().getDoubleAlignment();
581         int FI = F->getFrameInfo()->CreateStackObject(8, DoubleAlignment);
582         BuildMI (*BB, IP, V8::STDFri, 3).addFrameIndex (FI).addSImm (0)
583           .addReg (SrcReg);
584         BuildMI (*BB, IP, V8::LDDFri, 2, DestReg).addFrameIndex (FI)
585           .addSImm (0);
586         break;
587       }
588       default: {
589         unsigned DoubleAlignment = TM.getTargetData().getDoubleAlignment();
590         unsigned TmpReg = makeAnotherReg (newTy);
591         int FI = F->getFrameInfo()->CreateStackObject(8, DoubleAlignment);
592         BuildMI (*BB, IP, V8::ST, 3).addFrameIndex (FI).addSImm (0)
593           .addReg (SrcReg);
594         BuildMI (*BB, IP, V8::LDDFri, 2, TmpReg).addFrameIndex (FI).addSImm (0);
595         BuildMI (*BB, IP, V8::FITOD, 1, DestReg).addReg(TmpReg);
596         break;
597       }
598       }
599     } else if (newTyClass == cLong) {
600       if (oldTyClass == cLong) {
601         // Just copy it
602         BuildMI (*BB, IP, V8::ORrr, 2, DestReg).addReg (V8::G0).addReg (SrcReg);
603         BuildMI (*BB, IP, V8::ORrr, 2, DestReg+1).addReg (V8::G0)
604           .addReg (SrcReg+1);
605       } else {
606         std::cerr << "Cast still unsupported: SrcTy = "
607                   << *SrcTy << ", DestTy = " << *DestTy << "\n";
608         abort ();
609       }
610     } else {
611       std::cerr << "Cast still unsupported: SrcTy = "
612                 << *SrcTy << ", DestTy = " << *DestTy << "\n";
613       abort ();
614     }
615   }
616 }
617
618 void V8ISel::visitLoadInst(LoadInst &I) {
619   unsigned DestReg = getReg (I);
620   unsigned PtrReg = getReg (I.getOperand (0));
621   switch (getClassB (I.getType ())) {
622    case cByte:
623     if (I.getType ()->isSigned ())
624       BuildMI (BB, V8::LDSB, 2, DestReg).addReg (PtrReg).addSImm(0);
625     else
626       BuildMI (BB, V8::LDUB, 2, DestReg).addReg (PtrReg).addSImm(0);
627     return;
628    case cShort:
629     if (I.getType ()->isSigned ())
630       BuildMI (BB, V8::LDSH, 2, DestReg).addReg (PtrReg).addSImm(0);
631     else
632       BuildMI (BB, V8::LDUH, 2, DestReg).addReg (PtrReg).addSImm(0);
633     return;
634    case cInt:
635     BuildMI (BB, V8::LD, 2, DestReg).addReg (PtrReg).addSImm(0);
636     return;
637    case cLong:
638     BuildMI (BB, V8::LD, 2, DestReg).addReg (PtrReg).addSImm(0);
639     BuildMI (BB, V8::LD, 2, DestReg+1).addReg (PtrReg).addSImm(4);
640     return;
641    case cFloat:
642     BuildMI (BB, V8::LDFri, 2, DestReg).addReg (PtrReg).addSImm(0);
643     return;
644    case cDouble:
645     BuildMI (BB, V8::LDDFri, 2, DestReg).addReg (PtrReg).addSImm(0);
646     return;
647    default:
648     std::cerr << "Load instruction not handled: " << I;
649     abort ();
650     return;
651   }
652 }
653
654 void V8ISel::visitStoreInst(StoreInst &I) {
655   Value *SrcVal = I.getOperand (0);
656   unsigned SrcReg = getReg (SrcVal);
657   unsigned PtrReg = getReg (I.getOperand (1));
658   switch (getClassB (SrcVal->getType ())) {
659    case cByte:
660     BuildMI (BB, V8::STB, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
661     return;
662    case cShort:
663     BuildMI (BB, V8::STH, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
664     return;
665    case cInt:
666     BuildMI (BB, V8::ST, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
667     return;
668    case cLong:
669     BuildMI (BB, V8::ST, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
670     BuildMI (BB, V8::ST, 3).addReg (PtrReg).addSImm (4).addReg (SrcReg+1);
671     return;
672    case cFloat:
673     BuildMI (BB, V8::STFri, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
674     return;
675    case cDouble:
676     BuildMI (BB, V8::STDFri, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
677     return;
678    default:
679     std::cerr << "Store instruction not handled: " << I;
680     abort ();
681     return;
682   }
683 }
684
685 void V8ISel::visitCallInst(CallInst &I) {
686   MachineInstr *TheCall;
687   // Is it an intrinsic function call?
688   if (Function *F = I.getCalledFunction()) {
689     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
690       visitIntrinsicCall(ID, I);   // Special intrinsics are not handled here
691       return;
692     }
693   }
694
695   // Deal with args
696   assert (I.getNumOperands () < 8
697           && "Can't handle pushing excess call args on the stack yet");
698   static const unsigned OutgoingArgRegs[] = { V8::O0, V8::O1, V8::O2, V8::O3,
699     V8::O4, V8::O5 };
700   for (unsigned i = 1; i < 7; ++i)
701     if (i < I.getNumOperands ()) {
702       unsigned ArgReg = getReg (I.getOperand (i));
703       if (getClassB (I.getOperand (i)->getType ()) < cLong) {
704         // Schlep it over into the incoming arg register
705         BuildMI (BB, V8::ORrr, 2, OutgoingArgRegs[i - 1]).addReg (V8::G0)
706           .addReg (ArgReg);
707       } else if (getClassB (I.getOperand (i)->getType ()) == cFloat) {
708         // Single-fp args are passed in integer registers; go through
709         // memory to get them out of FP registers. (Bleh!)
710         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
711         int FI = F->getFrameInfo()->CreateStackObject(4, FltAlign);
712         BuildMI (BB, V8::STFri, 3).addFrameIndex (FI).addSImm (0)
713           .addReg (ArgReg);
714         BuildMI (BB, V8::LD, 2, OutgoingArgRegs[i - 1]).addFrameIndex (FI)
715           .addSImm (0);
716       } else {
717         assert (0 && "64-bit (double, long, etc.) 'call' opnds not handled");
718       }
719     }
720
721   // Emit call instruction
722   if (Function *F = I.getCalledFunction ()) {
723     BuildMI (BB, V8::CALL, 1).addGlobalAddress (F, true);
724   } else {  // Emit an indirect call...
725     unsigned Reg = getReg (I.getCalledValue ());
726     BuildMI (BB, V8::JMPLrr, 3, V8::O7).addReg (Reg).addReg (V8::G0);
727   }
728
729   // Deal w/ return value: schlep it over into the destination register
730   if (I.getType () == Type::VoidTy)
731     return;
732   unsigned DestReg = getReg (I);
733   switch (getClass (I.getType ())) {
734     case cByte:
735     case cShort:
736     case cInt:
737       BuildMI (BB, V8::ORrr, 2, DestReg).addReg(V8::G0).addReg(V8::O0);
738       break;
739     case cFloat:
740       BuildMI (BB, V8::FMOVS, 2, DestReg).addReg(V8::F0);
741       break;
742     default:
743       std::cerr << "Return type of call instruction not handled: " << I;
744       abort ();
745   }
746 }
747
748 void V8ISel::visitReturnInst(ReturnInst &I) {
749   if (I.getNumOperands () == 1) {
750     unsigned RetValReg = getReg (I.getOperand (0));
751     switch (getClass (I.getOperand (0)->getType ())) {
752       case cByte:
753       case cShort:
754       case cInt:
755         // Schlep it over into i0 (where it will become o0 after restore).
756         BuildMI (BB, V8::ORrr, 2, V8::I0).addReg(V8::G0).addReg(RetValReg);
757         break;
758       case cFloat:
759         BuildMI (BB, V8::FMOVS, 2, V8::F0).addReg(RetValReg);
760         break;
761       case cDouble: {
762         unsigned DoubleAlignment = TM.getTargetData().getDoubleAlignment();
763         int FI = F->getFrameInfo()->CreateStackObject(8, DoubleAlignment);
764         BuildMI (BB, V8::STDFri, 3).addFrameIndex (FI).addSImm (0)
765           .addReg (RetValReg);
766         BuildMI (BB, V8::LDDFri, 2, V8::F0).addFrameIndex (FI).addSImm (0);
767         break;
768       }
769       case cLong:
770         BuildMI (BB, V8::ORrr, 2, V8::I0).addReg(V8::G0).addReg(RetValReg);
771         BuildMI (BB, V8::ORrr, 2, V8::I1).addReg(V8::G0).addReg(RetValReg+1);
772         break;
773       default:
774         std::cerr << "Return instruction of this type not handled: " << I;
775         abort ();
776     }
777   }
778
779   // Just emit a 'retl' instruction to return.
780   BuildMI(BB, V8::RETL, 0);
781   return;
782 }
783
784 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
785   Function::iterator I = BB; ++I;  // Get iterator to next block
786   return I != BB->getParent()->end() ? &*I : 0;
787 }
788
789 /// visitBranchInst - Handles conditional and unconditional branches.
790 ///
791 void V8ISel::visitBranchInst(BranchInst &I) {
792   BasicBlock *takenSucc = I.getSuccessor (0);
793   MachineBasicBlock *takenSuccMBB = MBBMap[takenSucc];
794   BB->addSuccessor (takenSuccMBB);
795   if (I.isConditional()) {  // conditional branch
796     BasicBlock *notTakenSucc = I.getSuccessor (1);
797     MachineBasicBlock *notTakenSuccMBB = MBBMap[notTakenSucc];
798     BB->addSuccessor (notTakenSuccMBB);
799
800     // CondReg=(<condition>);
801     // If (CondReg==0) goto notTakenSuccMBB;
802     unsigned CondReg = getReg (I.getCondition ());
803     BuildMI (BB, V8::CMPri, 2).addSImm (0).addReg (CondReg);
804     BuildMI (BB, V8::BE, 1).addMBB (notTakenSuccMBB);
805   }
806   // goto takenSuccMBB;
807   BuildMI (BB, V8::BA, 1).addMBB (takenSuccMBB);
808 }
809
810 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
811 /// constant expression GEP support.
812 ///
813 void V8ISel::emitGEPOperation (MachineBasicBlock *MBB,
814                                MachineBasicBlock::iterator IP,
815                                Value *Src, User::op_iterator IdxBegin,
816                                User::op_iterator IdxEnd, unsigned TargetReg) {
817   const TargetData &TD = TM.getTargetData ();
818   const Type *Ty = Src->getType ();
819   unsigned basePtrReg = getReg (Src, MBB, IP);
820
821   // GEPs have zero or more indices; we must perform a struct access
822   // or array access for each one.
823   for (GetElementPtrInst::op_iterator oi = IdxBegin, oe = IdxEnd; oi != oe;
824        ++oi) {
825     Value *idx = *oi;
826     unsigned nextBasePtrReg = makeAnotherReg (Type::UIntTy);
827     if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
828       // It's a struct access.  idx is the index into the structure,
829       // which names the field. Use the TargetData structure to
830       // pick out what the layout of the structure is in memory.
831       // Use the (constant) structure index's value to find the
832       // right byte offset from the StructLayout class's list of
833       // structure member offsets.
834       unsigned fieldIndex = cast<ConstantUInt> (idx)->getValue ();
835       unsigned memberOffset =
836         TD.getStructLayout (StTy)->MemberOffsets[fieldIndex];
837       // Emit an ADD to add memberOffset to the basePtr.
838       BuildMI (*MBB, IP, V8::ADDri, 2,
839                nextBasePtrReg).addReg (basePtrReg).addZImm (memberOffset);
840       // The next type is the member of the structure selected by the
841       // index.
842       Ty = StTy->getElementType (fieldIndex);
843     } else if (const SequentialType *SqTy = dyn_cast<SequentialType> (Ty)) {
844       // It's an array or pointer access: [ArraySize x ElementType].
845       // We want to add basePtrReg to (idxReg * sizeof ElementType). First, we
846       // must find the size of the pointed-to type (Not coincidentally, the next
847       // type is the type of the elements in the array).
848       Ty = SqTy->getElementType ();
849       unsigned elementSize = TD.getTypeSize (Ty);
850       unsigned idxReg = getReg (idx, MBB, IP);
851       unsigned OffsetReg = makeAnotherReg (Type::IntTy);
852       unsigned elementSizeReg = makeAnotherReg (Type::UIntTy);
853       copyConstantToRegister (MBB, IP,
854         ConstantUInt::get(Type::UIntTy, elementSize), elementSizeReg);
855       // Emit a SMUL to multiply the register holding the index by
856       // elementSize, putting the result in OffsetReg.
857       BuildMI (*MBB, IP, V8::SMULrr, 2,
858                OffsetReg).addReg (elementSizeReg).addReg (idxReg);
859       // Emit an ADD to add OffsetReg to the basePtr.
860       BuildMI (*MBB, IP, V8::ADDrr, 2,
861                nextBasePtrReg).addReg (basePtrReg).addReg (OffsetReg);
862     }
863     basePtrReg = nextBasePtrReg;
864   }
865   // After we have processed all the indices, the result is left in
866   // basePtrReg.  Move it to the register where we were expected to
867   // put the answer.
868   BuildMI (BB, V8::ORrr, 1, TargetReg).addReg (V8::G0).addReg (basePtrReg);
869 }
870
871 void V8ISel::visitGetElementPtrInst (GetElementPtrInst &I) {
872   unsigned outputReg = getReg (I);
873   emitGEPOperation (BB, BB->end (), I.getOperand (0),
874                     I.op_begin ()+1, I.op_end (), outputReg);
875 }
876
877
878 void V8ISel::visitBinaryOperator (Instruction &I) {
879   unsigned DestReg = getReg (I);
880   unsigned Op0Reg = getReg (I.getOperand (0));
881   unsigned Op1Reg = getReg (I.getOperand (1));
882
883   unsigned Class = getClassB (I.getType());
884   unsigned OpCase = ~0;
885
886   if (Class > cLong) {
887     switch (I.getOpcode ()) {
888     case Instruction::Add: OpCase = 0; break;
889     case Instruction::Sub: OpCase = 1; break;
890     case Instruction::Mul: OpCase = 2; break;
891     case Instruction::Div: OpCase = 3; break;
892     default: visitInstruction (I); return;
893     }
894     static unsigned Opcodes[] = { V8::FADDS, V8::FADDD,
895                                   V8::FSUBS, V8::FSUBD,
896                                   V8::FMULS, V8::FMULD,
897                                   V8::FDIVS, V8::FDIVD };
898     BuildMI (BB, Opcodes[2*OpCase + (Class - cFloat)], 2, DestReg)
899       .addReg (Op0Reg).addReg (Op1Reg);
900     return;
901   }
902
903   unsigned ResultReg = DestReg;
904   if (Class != cInt)
905     ResultReg = makeAnotherReg (I.getType ());
906
907   // FIXME: support long, ulong, fp.
908   switch (I.getOpcode ()) {
909   case Instruction::Add: OpCase = 0; break;
910   case Instruction::Sub: OpCase = 1; break;
911   case Instruction::Mul: OpCase = 2; break;
912   case Instruction::And: OpCase = 3; break;
913   case Instruction::Or:  OpCase = 4; break;
914   case Instruction::Xor: OpCase = 5; break;
915   case Instruction::Shl: OpCase = 6; break;
916   case Instruction::Shr: OpCase = 7+I.getType()->isSigned(); break;
917
918   case Instruction::Div:
919   case Instruction::Rem: {
920     unsigned Dest = ResultReg;
921     if (I.getOpcode() == Instruction::Rem)
922       Dest = makeAnotherReg(I.getType());
923
924     // FIXME: this is probably only right for 32 bit operands.
925     if (I.getType ()->isSigned()) {
926       unsigned Tmp = makeAnotherReg (I.getType ());
927       // Sign extend into the Y register
928       BuildMI (BB, V8::SRAri, 2, Tmp).addReg (Op0Reg).addZImm (31);
929       BuildMI (BB, V8::WRrr, 2, V8::Y).addReg (Tmp).addReg (V8::G0);
930       BuildMI (BB, V8::SDIVrr, 2, Dest).addReg (Op0Reg).addReg (Op1Reg);
931     } else {
932       // Zero extend into the Y register, ie, just set it to zero
933       BuildMI (BB, V8::WRrr, 2, V8::Y).addReg (V8::G0).addReg (V8::G0);
934       BuildMI (BB, V8::UDIVrr, 2, Dest).addReg (Op0Reg).addReg (Op1Reg);
935     }
936
937     if (I.getOpcode() == Instruction::Rem) {
938       unsigned Tmp = makeAnotherReg (I.getType ());
939       BuildMI (BB, V8::SMULrr, 2, Tmp).addReg(Dest).addReg(Op1Reg);
940       BuildMI (BB, V8::SUBrr, 2, ResultReg).addReg(Op0Reg).addReg(Tmp);
941     }
942     break;
943   }
944   default:
945     visitInstruction (I);
946     return;
947   }
948
949   static const unsigned Opcodes[] = {
950     V8::ADDrr, V8::SUBrr, V8::SMULrr, V8::ANDrr, V8::ORrr, V8::XORrr,
951     V8::SLLrr, V8::SRLrr, V8::SRArr
952   };
953   if (OpCase != ~0U) {
954     BuildMI (BB, Opcodes[OpCase], 2, ResultReg).addReg (Op0Reg).addReg (Op1Reg);
955   }
956
957   switch (getClassB (I.getType ())) {
958     case cByte: 
959       if (I.getType ()->isSigned ()) { // add byte
960         BuildMI (BB, V8::ANDri, 2, DestReg).addReg (ResultReg).addZImm (0xff);
961       } else { // add ubyte
962         unsigned TmpReg = makeAnotherReg (I.getType ());
963         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (24);
964         BuildMI (BB, V8::SRAri, 2, DestReg).addReg (TmpReg).addZImm (24);
965       }
966       break;
967     case cShort:
968       if (I.getType ()->isSigned ()) { // add short
969         unsigned TmpReg = makeAnotherReg (I.getType ());
970         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (16);
971         BuildMI (BB, V8::SRAri, 2, DestReg).addReg (TmpReg).addZImm (16);
972       } else { // add ushort
973         unsigned TmpReg = makeAnotherReg (I.getType ());
974         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (16);
975         BuildMI (BB, V8::SRLri, 2, DestReg).addReg (TmpReg).addZImm (16);
976       }
977       break;
978     case cInt:
979       // Nothing to do here.
980       break;
981     case cLong:
982       // Only support and, or, xor.
983       if (OpCase < 3 || OpCase > 5) {
984         visitInstruction (I);
985         return;
986       }
987       // Do the other half of the value:
988       BuildMI (BB, Opcodes[OpCase], 2, ResultReg+1).addReg (Op0Reg+1)
989         .addReg (Op1Reg+1);
990       break;
991     default:
992       visitInstruction (I);
993   }
994 }
995
996 void V8ISel::visitSetCondInst(SetCondInst &I) {
997   unsigned Op0Reg = getReg (I.getOperand (0));
998   unsigned Op1Reg = getReg (I.getOperand (1));
999   unsigned DestReg = getReg (I);
1000   const Type *Ty = I.getOperand (0)->getType ();
1001   
1002   // Compare the two values.
1003   assert (getClass (Ty) != cLong && "can't setcc on longs yet");
1004   if (getClass (Ty) < cLong) {
1005     BuildMI(BB, V8::SUBCCrr, 2, V8::G0).addReg(Op0Reg).addReg(Op1Reg);
1006   } else if (getClass (Ty) == cFloat) {
1007     BuildMI(BB, V8::FCMPS, 2).addReg(Op0Reg).addReg(Op1Reg);
1008   } else if (getClass (Ty) == cDouble) {
1009     BuildMI(BB, V8::FCMPD, 2).addReg(Op0Reg).addReg(Op1Reg);
1010   }
1011
1012   unsigned BranchIdx;
1013   switch (I.getOpcode()) {
1014   default: assert(0 && "Unknown setcc instruction!");
1015   case Instruction::SetEQ: BranchIdx = 0; break;
1016   case Instruction::SetNE: BranchIdx = 1; break;
1017   case Instruction::SetLT: BranchIdx = 2; break;
1018   case Instruction::SetGT: BranchIdx = 3; break;
1019   case Instruction::SetLE: BranchIdx = 4; break;
1020   case Instruction::SetGE: BranchIdx = 5; break;
1021   }
1022   unsigned Column = 0;
1023   if (Ty->isSigned()) ++Column;
1024   if (Ty->isFloatingPoint()) ++Column;
1025   static unsigned OpcodeTab[3*6] = {
1026                                  // LLVM            SparcV8
1027                                  //        unsigned signed  fp
1028     V8::BE,   V8::BE,  V8::FBE,  // seteq = be      be      fbe
1029     V8::BNE,  V8::BNE, V8::FBNE, // setne = bne     bne     fbne
1030     V8::BCS,  V8::BL,  V8::FBL,  // setlt = bcs     bl      fbl
1031     V8::BGU,  V8::BG,  V8::FBG,  // setgt = bgu     bg      fbg
1032     V8::BLEU, V8::BLE, V8::FBLE, // setle = bleu    ble     fble
1033     V8::BCC,  V8::BGE, V8::FBGE  // setge = bcc     bge     fbge
1034   };
1035   unsigned Opcode = OpcodeTab[3*BranchIdx + Column];
1036
1037   MachineBasicBlock *thisMBB = BB;
1038   const BasicBlock *LLVM_BB = BB->getBasicBlock ();
1039   //  thisMBB:
1040   //  ...
1041   //   subcc %reg0, %reg1, %g0
1042   //   bCC copy1MBB
1043   //   ba copy0MBB
1044
1045   // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1046   // if we could insert other, non-terminator instructions after the
1047   // bCC. But MBB->getFirstTerminator() can't understand this.
1048   MachineBasicBlock *copy1MBB = new MachineBasicBlock (LLVM_BB);
1049   F->getBasicBlockList ().push_back (copy1MBB);
1050   BuildMI (BB, Opcode, 1).addMBB (copy1MBB);
1051   MachineBasicBlock *copy0MBB = new MachineBasicBlock (LLVM_BB);
1052   F->getBasicBlockList ().push_back (copy0MBB);
1053   BuildMI (BB, V8::BA, 1).addMBB (copy0MBB);
1054   // Update machine-CFG edges
1055   BB->addSuccessor (copy1MBB);
1056   BB->addSuccessor (copy0MBB);
1057
1058   //  copy0MBB:
1059   //   %FalseValue = or %G0, 0
1060   //   ba sinkMBB
1061   BB = copy0MBB;
1062   unsigned FalseValue = makeAnotherReg (I.getType ());
1063   BuildMI (BB, V8::ORri, 2, FalseValue).addReg (V8::G0).addZImm (0);
1064   MachineBasicBlock *sinkMBB = new MachineBasicBlock (LLVM_BB);
1065   F->getBasicBlockList ().push_back (sinkMBB);
1066   BuildMI (BB, V8::BA, 1).addMBB (sinkMBB);
1067   // Update machine-CFG edges
1068   BB->addSuccessor (sinkMBB);
1069
1070   DEBUG (std::cerr << "thisMBB is at " << (void*)thisMBB << "\n");
1071   DEBUG (std::cerr << "copy1MBB is at " << (void*)copy1MBB << "\n");
1072   DEBUG (std::cerr << "copy0MBB is at " << (void*)copy0MBB << "\n");
1073   DEBUG (std::cerr << "sinkMBB is at " << (void*)sinkMBB << "\n");
1074
1075   //  copy1MBB:
1076   //   %TrueValue = or %G0, 1
1077   //   ba sinkMBB
1078   BB = copy1MBB;
1079   unsigned TrueValue = makeAnotherReg (I.getType ());
1080   BuildMI (BB, V8::ORri, 2, TrueValue).addReg (V8::G0).addZImm (1);
1081   BuildMI (BB, V8::BA, 1).addMBB (sinkMBB);
1082   // Update machine-CFG edges
1083   BB->addSuccessor (sinkMBB);
1084
1085   //  sinkMBB:
1086   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1087   //  ...
1088   BB = sinkMBB;
1089   BuildMI (BB, V8::PHI, 4, DestReg).addReg (FalseValue)
1090     .addMBB (copy0MBB).addReg (TrueValue).addMBB (copy1MBB);
1091 }
1092
1093 void V8ISel::visitAllocaInst(AllocaInst &I) {
1094   // Find the data size of the alloca inst's getAllocatedType.
1095   const Type *Ty = I.getAllocatedType();
1096   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
1097
1098   unsigned ArraySizeReg = getReg (I.getArraySize ());
1099   unsigned TySizeReg = getReg (ConstantUInt::get (Type::UIntTy, TySize));
1100   unsigned TmpReg1 = makeAnotherReg (Type::UIntTy);
1101   unsigned TmpReg2 = makeAnotherReg (Type::UIntTy);
1102   unsigned StackAdjReg = makeAnotherReg (Type::UIntTy);
1103
1104   // StackAdjReg = (ArraySize * TySize) rounded up to nearest doubleword boundary
1105   BuildMI (BB, V8::UMULrr, 2, TmpReg1).addReg (ArraySizeReg).addReg (TySizeReg);
1106
1107   // Round up TmpReg1 to nearest doubleword boundary:
1108   BuildMI (BB, V8::ADDri, 2, TmpReg2).addReg (TmpReg1).addSImm (7);
1109   BuildMI (BB, V8::ANDri, 2, StackAdjReg).addReg (TmpReg2).addSImm (-8);
1110
1111   // Subtract size from stack pointer, thereby allocating some space.
1112   BuildMI (BB, V8::SUBrr, 2, V8::SP).addReg (V8::SP).addReg (StackAdjReg);
1113
1114   // Put a pointer to the space into the result register, by copying
1115   // the stack pointer.
1116   BuildMI (BB, V8::ADDri, 2, getReg(I)).addReg (V8::SP).addSImm (96);
1117
1118   // Inform the Frame Information that we have just allocated a variable-sized
1119   // object.
1120   F->getFrameInfo()->CreateVariableSizedObject();
1121 }
1122
1123 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1124 /// function, lowering any calls to unknown intrinsic functions into the
1125 /// equivalent LLVM code.
1126 void V8ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1127   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1128     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1129       if (CallInst *CI = dyn_cast<CallInst>(I++))
1130         if (Function *F = CI->getCalledFunction())
1131           switch (F->getIntrinsicID()) {
1132           case Intrinsic::not_intrinsic: break;
1133           default:
1134             // All other intrinsic calls we must lower.
1135             Instruction *Before = CI->getPrev();
1136             TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1137             if (Before) {        // Move iterator to instruction after call
1138               I = Before;  ++I;
1139             } else {
1140               I = BB->begin();
1141             }
1142           }
1143 }
1144
1145
1146 void V8ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1147   unsigned TmpReg1, TmpReg2;
1148   switch (ID) {
1149   default: assert(0 && "Intrinsic not supported!");
1150   }
1151 }