Constants are laid out in memory in PC-relative form.
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9CodeEmitter.cpp
1 //===-- SparcV9CodeEmitter.cpp -  --------===//
2 //
3 //
4 //===----------------------------------------------------------------------===//
5
6 #include "llvm/Constants.h"
7 #include "llvm/Function.h"
8 #include "llvm/GlobalVariable.h"
9 #include "llvm/PassManager.h"
10 #include "llvm/CodeGen/MachineCodeEmitter.h"
11 #include "llvm/CodeGen/MachineFunctionInfo.h"
12 #include "llvm/CodeGen/MachineFunctionPass.h"
13 #include "llvm/CodeGen/MachineInstr.h"
14 #include "llvm/Target/TargetMachine.h"
15 #include "llvm/Target/TargetData.h"
16 #include "Support/hash_set"
17 #include "SparcInternals.h"
18 #include "SparcV9CodeEmitter.h"
19
20 bool UltraSparc::addPassesToEmitMachineCode(PassManager &PM,
21                                             MachineCodeEmitter &MCE) {
22   //PM.add(new SparcV9CodeEmitter(MCE));
23   //MachineCodeEmitter *M = MachineCodeEmitter::createDebugMachineCodeEmitter();
24   MachineCodeEmitter *M = MachineCodeEmitter::createFilePrinterEmitter(MCE);
25   PM.add(new SparcV9CodeEmitter(this, *M));
26   PM.add(createMachineCodeDestructionPass()); // Free stuff no longer needed
27   return false;
28 }
29
30 namespace {
31   class JITResolver {
32     MachineCodeEmitter &MCE;
33
34     // LazyCodeGenMap - Keep track of call sites for functions that are to be
35     // lazily resolved.
36     std::map<unsigned, Function*> LazyCodeGenMap;
37
38     // LazyResolverMap - Keep track of the lazy resolver created for a
39     // particular function so that we can reuse them if necessary.
40     std::map<Function*, unsigned> LazyResolverMap;
41   public:
42     JITResolver(MachineCodeEmitter &mce) : MCE(mce) {}
43     unsigned getLazyResolver(Function *F);
44     unsigned addFunctionReference(unsigned Address, Function *F);
45     
46   private:
47     unsigned emitStubForFunction(Function *F);
48     static void CompilationCallback();
49     unsigned resolveFunctionReference(unsigned RetAddr);
50   };
51
52   JITResolver *TheJITResolver;
53 }
54
55 /// addFunctionReference - This method is called when we need to emit the
56 /// address of a function that has not yet been emitted, so we don't know the
57 /// address.  Instead, we emit a call to the CompilationCallback method, and
58 /// keep track of where we are.
59 ///
60 unsigned JITResolver::addFunctionReference(unsigned Address, Function *F) {
61   LazyCodeGenMap[Address] = F;  
62   return (intptr_t)&JITResolver::CompilationCallback;
63 }
64
65 unsigned JITResolver::resolveFunctionReference(unsigned RetAddr) {
66   std::map<unsigned, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
67   assert(I != LazyCodeGenMap.end() && "Not in map!");
68   Function *F = I->second;
69   LazyCodeGenMap.erase(I);
70   return MCE.forceCompilationOf(F);
71 }
72
73 unsigned JITResolver::getLazyResolver(Function *F) {
74   std::map<Function*, unsigned>::iterator I = LazyResolverMap.lower_bound(F);
75   if (I != LazyResolverMap.end() && I->first == F) return I->second;
76   
77 //std::cerr << "Getting lazy resolver for : " << ((Value*)F)->getName() << "\n";
78
79   unsigned Stub = emitStubForFunction(F);
80   LazyResolverMap.insert(I, std::make_pair(F, Stub));
81   return Stub;
82 }
83
84 void JITResolver::CompilationCallback() {
85   uint64_t *StackPtr = (uint64_t*)__builtin_frame_address(0);
86   uint64_t RetAddr = (uint64_t)(intptr_t)__builtin_return_address(0);
87
88 #if 0  
89   std::cerr << "In callback! Addr=0x" << std::hex << RetAddr
90             << " SP=0x" << (unsigned)StackPtr << std::dec
91             << ": Resolving call to function: "
92             << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n";
93 #endif
94
95   std::cerr << "Sparc's JIT Resolver not implemented!\n";
96   abort();
97
98 #if 0
99   unsigned NewVal = TheJITResolver->resolveFunctionReference((void*)RetAddr);
100
101   // Rewrite the call target... so that we don't fault every time we execute
102   // the call.
103   *(unsigned*)RetAddr = NewVal;
104   
105   // Change the return address to reexecute the call instruction...
106   StackPtr[1] -= 4;
107 #endif
108 }
109
110 /// emitStubForFunction - This method is used by the JIT when it needs to emit
111 /// the address of a function for a function whose code has not yet been
112 /// generated.  In order to do this, it generates a stub which jumps to the lazy
113 /// function compiler, which will eventually get fixed to call the function
114 /// directly.
115 ///
116 unsigned JITResolver::emitStubForFunction(Function *F) {
117 #if 0
118   MCE.startFunctionStub(*F, 6);
119   MCE.emitByte(0xE8);   // Call with 32 bit pc-rel destination...
120
121   unsigned Address = addFunctionReference(MCE.getCurrentPCValue(), F);
122   MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
123
124   MCE.emitByte(0xCD);   // Interrupt - Just a marker identifying the stub!
125   return (intptr_t)MCE.finishFunctionStub(*F);
126 #endif
127   std::cerr << "Sparc's JITResolver::emitStubForFunction() not implemented!\n";
128   abort();
129 }
130
131
132 void SparcV9CodeEmitter::emitConstant(unsigned Val, unsigned Size) {
133   // Output the constant in big endian byte order...
134   unsigned byteVal;
135   for (int i = Size-1; i >= 0; --i) {
136     byteVal = Val >> 8*i;
137     MCE->emitByte(byteVal & 255);
138   }
139 }
140
141 unsigned getRealRegNum(unsigned fakeReg, unsigned regClass) {
142   switch (regClass) {
143   case UltraSparcRegInfo::IntRegType: {
144     // Sparc manual, p31
145     static const unsigned IntRegMap[] = {
146       // "o0", "o1", "o2", "o3", "o4", "o5",       "o7",
147       8, 9, 10, 11, 12, 13, 15,
148       // "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
149       16, 17, 18, 19, 20, 21, 22, 23,
150       // "i0", "i1", "i2", "i3", "i4", "i5",  
151       24, 25, 26, 27, 28, 29,
152       // "i6", "i7",
153       30, 31,
154       // "g0", "g1", "g2", "g3", "g4", "g5",  "g6", "g7", 
155       0, 1, 2, 3, 4, 5, 6, 7,
156       // "o6"
157       14
158     }; 
159  
160     return IntRegMap[fakeReg];
161     break;
162   }
163   case UltraSparcRegInfo::FPSingleRegType: {
164     return fakeReg;
165   }
166   case UltraSparcRegInfo::FPDoubleRegType: {
167     return fakeReg;
168   }
169   case UltraSparcRegInfo::FloatCCRegType: {
170     return fakeReg;
171
172   }
173   case UltraSparcRegInfo::IntCCRegType: {
174     return fakeReg;
175   }
176   default:
177     assert(0 && "Invalid unified register number in getRegType");
178     return fakeReg;
179   }
180 }
181
182 int64_t SparcV9CodeEmitter::getMachineOpValue(MachineInstr &MI,
183                                               MachineOperand &MO) {
184   int64_t rv = 0; // Return value; defaults to 0 for unhandled cases
185                   // or things that get fixed up later by the JIT.
186
187   if (MO.isVirtualRegister()) {
188     std::cerr << "ERROR: virtual register found in machine code.\n";
189     abort();
190   } else if (MO.isPCRelativeDisp()) {
191     Value *V = MO.getVRegValue();
192     if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
193       std::cerr << "Saving reference to BB (VReg)\n";
194       unsigned* CurrPC = (unsigned*)(intptr_t)MCE->getCurrentPCValue();
195       BBRefs.push_back(std::make_pair(BB, std::make_pair(CurrPC, &MI)));
196     } else if (Constant *C = dyn_cast<Constant>(V)) {
197       if (ConstantMap.find(C) != ConstantMap.end())
198         rv = (int64_t)(intptr_t)ConstantMap[C] - MCE->getCurrentPCValue();
199       else {
200         std::cerr << "ERROR: constant not in map:" << MO << "\n";
201         abort();
202       }
203     } else {
204       std::cerr << "ERROR: PC relative disp unhandled:" << MO << "\n";
205       abort();
206     }
207   } else if (MO.isPhysicalRegister()) {
208     // This is necessary because the Sparc doesn't actually lay out registers
209     // in the real fashion -- it skips those that it chooses not to allocate,
210     // i.e. those that are the SP, etc.
211     unsigned fakeReg = MO.getReg(), realReg, regClass, regType;
212     regType = TM->getRegInfo().getRegType(fakeReg);
213     // At least map fakeReg into its class
214     fakeReg = TM->getRegInfo().getClassRegNum(fakeReg, regClass);
215     // Find the real register number for use in an instruction
216     realReg = getRealRegNum(fakeReg, regClass);
217     std::cerr << "Reg[" << std::dec << fakeReg << "] = " << realReg << "\n";
218     rv = realReg;
219   } else if (MO.isImmediate()) {
220     rv = MO.getImmedValue();
221   } else if (MO.isGlobalAddress()) {
222     rv = (int64_t)
223       (intptr_t)getGlobalAddress(cast<GlobalValue>(MO.getVRegValue()),
224                                  MI, MO.isPCRelative());
225   } else if (MO.isMachineBasicBlock()) {
226     // Duplicate code of the above case for VirtualRegister, BasicBlock... 
227     // It should really hit this case, but Sparc backend uses VRegs instead
228     std::cerr << "Saving reference to MBB\n";
229     BasicBlock *BB = MO.getMachineBasicBlock()->getBasicBlock();
230     unsigned* CurrPC = (unsigned*)(intptr_t)MCE->getCurrentPCValue();
231     BBRefs.push_back(std::make_pair(BB, std::make_pair(CurrPC, &MI)));
232   } else if (MO.isExternalSymbol()) {
233     // Sparc backend doesn't generate this (yet...)
234     std::cerr << "ERROR: External symbol unhandled: " << MO << "\n";
235     abort();
236   } else if (MO.isFrameIndex()) {
237     // Sparc backend doesn't generate this (yet...)
238     int FrameIndex = MO.getFrameIndex();
239     std::cerr << "ERROR: Frame index unhandled.\n";
240     abort();
241   } else if (MO.isConstantPoolIndex()) {
242     // Sparc backend doesn't generate this (yet...)
243     std::cerr << "ERROR: Constant Pool index unhandled.\n";
244     abort();
245   } else {
246     std::cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
247     abort();
248   }
249
250   // Finally, deal with the various bitfield-extracting functions that
251   // are used in SPARC assembly. (Some of these make no sense in combination
252   // with some of the above; we'll trust that the instruction selector
253   // will not produce nonsense, and not check for valid combinations here.)
254   if (MO.opLoBits32()) {          // %lo(val)
255     return rv & 0x03ff;
256   } else if (MO.opHiBits32()) {   // %lm(val)
257     return (rv >> 10) & 0x03fffff;
258   } else if (MO.opLoBits64()) {   // %hm(val)
259     return (rv >> 32) & 0x03ff;
260   } else if (MO.opHiBits64()) {   // %hh(val)
261     return rv >> 42;
262   } else {                        // (unadorned) val
263     return rv;
264   }
265 }
266
267 unsigned SparcV9CodeEmitter::getValueBit(int64_t Val, unsigned bit) {
268   Val >>= bit;
269   return (Val & 1);
270 }
271
272 void* SparcV9CodeEmitter::convertAddress(intptr_t Addr, bool isPCRelative) {
273   if (isPCRelative) {
274     return (void*)(Addr - (intptr_t)MCE->getCurrentPCValue());
275   } else {
276     return (void*)Addr;
277   }
278 }
279
280
281
282 bool SparcV9CodeEmitter::runOnMachineFunction(MachineFunction &MF) {
283   std::cerr << "Starting function " << MF.getFunction()->getName()
284             << ", address: " << "0x" << std::hex 
285             << (long)MCE->getCurrentPCValue() << "\n";
286
287   MCE->startFunction(MF);
288
289   // FIXME: the Sparc backend does not use the ConstantPool!!
290   //MCE->emitConstantPool(MF.getConstantPool());
291
292   // Instead, the Sparc backend has its own constant pool implementation:
293   const hash_set<const Constant*> &pool = MF.getInfo()->getConstantPoolValues();
294   for (hash_set<const Constant*>::const_iterator I = pool.begin(),
295          E = pool.end();  I != E; ++I)
296   {
297     const Constant *C = *I;
298     // For now we just allocate some memory on the heap, this can be
299     // dramatically improved.
300     const Type *Ty = ((Value*)C)->getType();
301     void *Addr = malloc(TM->getTargetData().getTypeSize(Ty));
302     //FIXME
303     //TheVM.InitializeMemory(C, Addr);
304     std::cerr << "Adding ConstantMap[" << C << "]=" << std::dec << Addr << "\n";
305     ConstantMap[C] = Addr;
306   }  
307
308   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
309     emitBasicBlock(*I);
310   MCE->finishFunction(MF);
311
312   std::cerr << "Finishing function " << MF.getFunction()->getName() << "\n";
313   ConstantMap.clear();
314   for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
315     long Location = BBLocations[BBRefs[i].first];
316     unsigned *Ref = BBRefs[i].second.first;
317     MachineInstr *MI = BBRefs[i].second.second;
318     std::cerr << "Fixup @" << std::hex << Ref << " to " << Location
319               << " in instr: " << std::dec << *MI << "\n";
320   }
321
322   // Resolve branches to BasicBlocks for the entire function
323   for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
324     long Location = BBLocations[BBRefs[i].first];
325     unsigned *Ref = BBRefs[i].second.first;
326     MachineInstr *MI = BBRefs[i].second.second;
327     std::cerr << "attempting to resolve BB: " << i << "\n";
328     for (unsigned ii = 0, ee = MI->getNumOperands(); ii != ee; ++ii) {
329       MachineOperand &op = MI->getOperand(ii);
330       if (op.isPCRelativeDisp()) {
331         // the instruction's branch target is made such that it branches to
332         // PC + (br target * 4), so undo that arithmetic here:
333         // Location is the target of the branch
334         // Ref is the location of the instruction, and hence the PC
335         unsigned branchTarget = (Location - (long)Ref) >> 2;
336         // Save the flags.
337         bool loBits32=false, hiBits32=false, loBits64=false, hiBits64=false;   
338         if (op.opLoBits32()) { loBits32=true; }
339         if (op.opHiBits32()) { hiBits32=true; }
340         if (op.opLoBits64()) { loBits64=true; }
341         if (op.opHiBits64()) { hiBits64=true; }
342         MI->SetMachineOperandConst(ii, MachineOperand::MO_SignExtendedImmed,
343                                    branchTarget);
344         if (loBits32) { MI->setOperandLo32(ii); }
345         else if (hiBits32) { MI->setOperandHi32(ii); }
346         else if (loBits64) { MI->setOperandLo64(ii); }
347         else if (hiBits64) { MI->setOperandHi64(ii); }
348         std::cerr << "Rewrote BB ref: ";
349         unsigned fixedInstr = SparcV9CodeEmitter::getBinaryCodeForInstr(*MI);
350         *Ref = fixedInstr;
351         break;
352       }
353     }
354   }
355   BBRefs.clear();
356   BBLocations.clear();
357
358   return false;
359 }
360
361 void SparcV9CodeEmitter::emitBasicBlock(MachineBasicBlock &MBB) {
362   currBB = MBB.getBasicBlock();
363   BBLocations[currBB] = MCE->getCurrentPCValue();
364   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
365     emitInstruction(**I);
366 }
367
368 void SparcV9CodeEmitter::emitInstruction(MachineInstr &MI) {
369   emitConstant(getBinaryCodeForInstr(MI), 4);
370 }
371
372 void* SparcV9CodeEmitter::getGlobalAddress(GlobalValue *V, MachineInstr &MI,
373                                            bool isPCRelative)
374 {
375   if (isPCRelative) { // must be a call, this is a major hack!
376     // Try looking up the function to see if it is already compiled!
377     if (void *Addr = (void*)(intptr_t)MCE->getGlobalValueAddress(V)) {
378       intptr_t CurByte = MCE->getCurrentPCValue();
379       // The real target of the call is Addr = PC + (target * 4)
380       // CurByte is the PC, Addr we just received
381       return (void*) (((long)Addr - (long)CurByte) >> 2);
382     } else {
383       if (Function *F = dyn_cast<Function>(V)) {
384         // Function has not yet been code generated!
385         TheJITResolver->addFunctionReference(MCE->getCurrentPCValue(),
386                                              cast<Function>(V));
387         // Delayed resolution...
388         return 
389           (void*)(intptr_t)TheJITResolver->getLazyResolver(cast<Function>(V));
390
391       } else if (Constant *C = ConstantPointerRef::get(V)) {
392         if (ConstantMap.find(C) != ConstantMap.end()) {
393           return ConstantMap[C];
394         } else {
395           std::cerr << "Constant: 0x" << std::hex << &*C << std::dec
396                     << ", " << *V << " not found in ConstantMap!\n";
397           abort();
398         }
399
400 #if 0
401       } else if (const GlobalVariable *G = dyn_cast<GlobalVariable>(V)) {
402         if (G->isConstant()) {
403           const Constant* C = G->getInitializer();
404           if (ConstantMap.find(C) != ConstantMap.end()) {
405             return ConstantMap[C];
406           } else {
407             std::cerr << "Constant: " << *G << " not found in ConstantMap!\n";
408             abort();
409           }
410         } else {
411           std::cerr << "Variable: " << *G << " address not found!\n";
412           abort();          
413         }
414 #endif
415       } else {
416         std::cerr << "Unhandled global: " << *V << "\n";
417         abort();
418       }
419     }
420   } else {
421     return convertAddress((intptr_t)MCE->getGlobalValueAddress(V),
422                           isPCRelative);
423   }
424 }
425
426
427 #include "SparcV9CodeEmitter.inc"
428