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