469b3a230c56301374979e53dc3cebb22a1e9245
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9CodeEmitter.cpp
1 //===-- SparcV9CodeEmitter.cpp --------------------------------------------===//
2 //
3 // SPARC-specific backend for emitting machine code to memory.
4 //
5 // This module also contains the code for lazily resolving the targets
6 // of call instructions, including the callback used to redirect calls
7 // to functions for which the code has not yet been generated into the
8 // JIT compiler.
9 //
10 // This file #includes SparcV9CodeEmitter.inc, which contains the code
11 // for getBinaryCodeForInstr(), a method that converts a MachineInstr
12 // into the corresponding binary machine code word.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Constants.h"
17 #include "llvm/Function.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/CodeGen/MachineCodeEmitter.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFunctionInfo.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetData.h"
27 #include "Support/Debug.h"
28 #include "Support/hash_set"
29 #include "Support/Statistic.h"
30 #include "SparcInternals.h"
31 #include "SparcV9CodeEmitter.h"
32 #include "Config/alloca.h"
33
34 namespace {
35   Statistic<> OverwrittenCalls("call-ovwr", "Number of over-written calls");
36   Statistic<> UnmodifiedCalls("call-skip", "Number of unmodified calls");
37   Statistic<> CallbackCalls("callback", "Number CompilationCallback() calls");
38 }
39
40 bool UltraSparc::addPassesToEmitMachineCode(FunctionPassManager &PM,
41                                             MachineCodeEmitter &MCE) {
42   MachineCodeEmitter *M = &MCE;
43   DEBUG(M = MachineCodeEmitter::createFilePrinterEmitter(MCE));
44   PM.add(new SparcV9CodeEmitter(*this, *M));
45   PM.add(createMachineCodeDestructionPass()); // Free stuff no longer needed
46   return false;
47 }
48
49 namespace {
50   class JITResolver {
51     SparcV9CodeEmitter &SparcV9;
52     MachineCodeEmitter &MCE;
53
54     /// LazyCodeGenMap - Keep track of call sites for functions that are to be
55     /// lazily resolved.
56     ///
57     std::map<uint64_t, Function*> LazyCodeGenMap;
58
59     /// LazyResolverMap - Keep track of the lazy resolver created for a
60     /// particular function so that we can reuse them if necessary.
61     ///
62     std::map<Function*, uint64_t> LazyResolverMap;
63
64   public:
65     enum CallType { ShortCall, FarCall };
66
67   private:
68     /// We need to keep track of whether we used a simple call or a far call
69     /// (many instructions) in sequence. This means we need to keep track of
70     /// what type of stub we generate.
71     static std::map<uint64_t, CallType> LazyCallFlavor;
72
73   public:
74     JITResolver(SparcV9CodeEmitter &V9,
75                 MachineCodeEmitter &mce) : SparcV9(V9), MCE(mce) {}
76     uint64_t getLazyResolver(Function *F);
77     uint64_t addFunctionReference(uint64_t Address, Function *F);
78     void deleteFunctionReference(uint64_t Address);
79     void addCallFlavor(uint64_t Address, CallType Flavor) {
80       LazyCallFlavor[Address] = Flavor;
81     }
82
83     // Utility functions for accessing data from static callback
84     uint64_t getCurrentPCValue() {
85       return MCE.getCurrentPCValue();
86     }
87     unsigned getBinaryCodeForInstr(MachineInstr &MI) {
88       return SparcV9.getBinaryCodeForInstr(MI);
89     }
90
91     inline void insertFarJumpAtAddr(int64_t Value, uint64_t Addr);
92     void insertJumpAtAddr(int64_t Value, uint64_t &Addr);
93
94   private:
95     uint64_t emitStubForFunction(Function *F);
96     static void SaveRegisters(uint64_t DoubleFP[], uint64_t &FSR,
97                               uint64_t &FPRS, uint64_t &CCR);
98     static void RestoreRegisters(uint64_t DoubleFP[], uint64_t &FSR,
99                                  uint64_t &FPRS, uint64_t &CCR);
100     static void CompilationCallback();
101     uint64_t resolveFunctionReference(uint64_t RetAddr);
102
103   };
104
105   JITResolver *TheJITResolver;
106   std::map<uint64_t, JITResolver::CallType> JITResolver::LazyCallFlavor;
107 }
108
109 /// addFunctionReference - This method is called when we need to emit the
110 /// address of a function that has not yet been emitted, so we don't know the
111 /// address.  Instead, we emit a call to the CompilationCallback method, and
112 /// keep track of where we are.
113 ///
114 uint64_t JITResolver::addFunctionReference(uint64_t Address, Function *F) {
115   LazyCodeGenMap[Address] = F;
116   return (intptr_t)&JITResolver::CompilationCallback;
117 }
118
119 /// deleteFunctionReference - If we are emitting a far call, we already added a
120 /// reference to the function, but it is now incorrect, since the address to the
121 /// JIT resolver is too far away to be a simple call instruction. This is used
122 /// to remove the address from the map.
123 ///
124 void JITResolver::deleteFunctionReference(uint64_t Address) {
125   std::map<uint64_t, Function*>::iterator I = LazyCodeGenMap.find(Address);
126   assert(I != LazyCodeGenMap.end() && "Not in map!");
127   LazyCodeGenMap.erase(I);  
128 }
129
130 uint64_t JITResolver::resolveFunctionReference(uint64_t RetAddr) {
131   std::map<uint64_t, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
132   assert(I != LazyCodeGenMap.end() && "Not in map!");
133   Function *F = I->second;
134   LazyCodeGenMap.erase(I);
135   return MCE.forceCompilationOf(F);
136 }
137
138 uint64_t JITResolver::getLazyResolver(Function *F) {
139   std::map<Function*, uint64_t>::iterator I = LazyResolverMap.lower_bound(F);
140   if (I != LazyResolverMap.end() && I->first == F) return I->second;
141   
142   uint64_t Stub = emitStubForFunction(F);
143   LazyResolverMap.insert(I, std::make_pair(F, Stub));
144   return Stub;
145 }
146
147 void JITResolver::insertJumpAtAddr(int64_t JumpTarget, uint64_t &Addr) {
148   DEBUG(std::cerr << "Emitting a jump to 0x" << std::hex << JumpTarget << "\n");
149
150   // If the target function is close enough to fit into the 19bit disp of
151   // BA, we should use this version, as it's much cheaper to generate.
152   int64_t BranchTarget = (JumpTarget-Addr) >> 2;
153   if (BranchTarget >= (1 << 19) || BranchTarget <= -(1 << 19)) {
154     TheJITResolver->insertFarJumpAtAddr(JumpTarget, Addr);
155   } else {
156     // ba <target>
157     MachineInstr *I = BuildMI(V9::BA, 1).addSImm(BranchTarget);
158     *((unsigned*)(intptr_t)Addr) = getBinaryCodeForInstr(*I);
159     Addr += 4;
160     delete I;
161
162     // nop
163     I = BuildMI(V9::NOP, 0);
164     *((unsigned*)(intptr_t)Addr) = getBinaryCodeForInstr(*I);
165     delete I;
166   }
167 }
168
169 void JITResolver::insertFarJumpAtAddr(int64_t Target, uint64_t Addr) {
170   static const unsigned 
171     o6 = SparcIntRegClass::o6, g0 = SparcIntRegClass::g0,
172     g1 = SparcIntRegClass::g1, g5 = SparcIntRegClass::g5;
173
174   MachineInstr* BinaryCode[] = {
175     //
176     // Get address to branch into %g1, using %g5 as a temporary
177     //
178     // sethi %uhi(Target), %g5     ;; get upper 22 bits of Target into %g5
179     BuildMI(V9::SETHI, 2).addSImm(Target >> 42).addReg(g5),
180     // or %g5, %ulo(Target), %g5   ;; get 10 lower bits of upper word into %g5
181     BuildMI(V9::ORi, 3).addReg(g5).addSImm((Target >> 32) & 0x03ff).addReg(g5),
182     // sllx %g5, 32, %g5           ;; shift those 10 bits to the upper word
183     BuildMI(V9::SLLXi6, 3).addReg(g5).addSImm(32).addReg(g5),
184     // sethi %hi(Target), %g1      ;; extract bits 10-31 into the dest reg
185     BuildMI(V9::SETHI, 2).addSImm((Target >> 10) & 0x03fffff).addReg(g1),
186     // or %g5, %g1, %g1            ;; get upper word (in %g5) into %g1
187     BuildMI(V9::ORr, 3).addReg(g5).addReg(g1).addReg(g1),
188     // or %g1, %lo(Target), %g1    ;; get lowest 10 bits of Target into %g1
189     BuildMI(V9::ORi, 3).addReg(g1).addSImm(Target & 0x03ff).addReg(g1),
190     // jmpl %g1, %g0, %g0          ;; indirect branch on %g1
191     BuildMI(V9::JMPLRETr, 3).addReg(g1).addReg(g0).addReg(g0),
192     // nop                         ;; delay slot
193     BuildMI(V9::NOP, 0)
194   };
195
196   for (unsigned i=0, e=sizeof(BinaryCode)/sizeof(BinaryCode[0]); i!=e; ++i) {
197     *((unsigned*)(intptr_t)Addr) = getBinaryCodeForInstr(*BinaryCode[i]);
198     delete BinaryCode[i];
199     Addr += 4;
200   }
201 }
202
203 void JITResolver::SaveRegisters(uint64_t DoubleFP[], uint64_t &FSR, 
204                                 uint64_t &FPRS, uint64_t &CCR) {
205 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
206
207 #if 0
208   __asm__ __volatile__ (// Save condition-code registers
209                         "stx %%fsr, %0;\n\t" 
210                         "rd %%fprs, %1;\n\t" 
211                         "rd %%ccr,  %2;\n\t"
212                         : "=m"(FSR), "=r"(FPRS), "=r"(CCR));
213 #endif
214
215   // GCC says: `asm' only allows up to thirty parameters!
216   __asm__ __volatile__ (// Save Single/Double FP registers, part 1
217                         "std  %%f0,  %0;\n\t"  "std  %%f2,  %1;\n\t"
218                         "std  %%f4,  %2;\n\t"  "std  %%f6,  %3;\n\t"
219                         "std  %%f8,  %4;\n\t"  "std  %%f10, %5;\n\t"
220                         "std  %%f12, %6;\n\t"  "std  %%f14, %7;\n\t"
221                         "std  %%f16, %8;\n\t"  "std  %%f18, %9;\n\t"
222                         "std  %%f20, %10;\n\t" "std  %%f22, %11;\n\t"
223                         "std  %%f24, %12;\n\t" "std  %%f26, %13;\n\t"
224                         "std  %%f28, %14;\n\t" "std  %%f30, %15;\n\t"
225                         : "=m"(DoubleFP[ 0]), "=m"(DoubleFP[ 1]),
226                           "=m"(DoubleFP[ 2]), "=m"(DoubleFP[ 3]),
227                           "=m"(DoubleFP[ 4]), "=m"(DoubleFP[ 5]),
228                           "=m"(DoubleFP[ 6]), "=m"(DoubleFP[ 7]),
229                           "=m"(DoubleFP[ 8]), "=m"(DoubleFP[ 9]),
230                           "=m"(DoubleFP[10]), "=m"(DoubleFP[11]),
231                           "=m"(DoubleFP[12]), "=m"(DoubleFP[13]),
232                           "=m"(DoubleFP[14]), "=m"(DoubleFP[15]));
233                         
234   __asm__ __volatile__ (// Save Double FP registers, part 2
235                         "std %%f32, %0;\n\t"  "std %%f34, %1;\n\t"
236                         "std %%f36, %2;\n\t"  "std %%f38, %3;\n\t"
237                         "std %%f40, %4;\n\t"  "std %%f42, %5;\n\t"
238                         "std %%f44, %6;\n\t"  "std %%f46, %7;\n\t"
239                         "std %%f48, %8;\n\t"  "std %%f50, %9;\n\t"
240                         "std %%f52, %10;\n\t" "std %%f54, %11;\n\t"
241                         "std %%f56, %12;\n\t" "std %%f58, %13;\n\t"
242                         "std %%f60, %14;\n\t" "std %%f62, %15;\n\t"
243                         : "=m"(DoubleFP[16]), "=m"(DoubleFP[17]),
244                           "=m"(DoubleFP[18]), "=m"(DoubleFP[19]),
245                           "=m"(DoubleFP[20]), "=m"(DoubleFP[21]),
246                           "=m"(DoubleFP[22]), "=m"(DoubleFP[23]),
247                           "=m"(DoubleFP[24]), "=m"(DoubleFP[25]),
248                           "=m"(DoubleFP[26]), "=m"(DoubleFP[27]),
249                           "=m"(DoubleFP[28]), "=m"(DoubleFP[29]),
250                           "=m"(DoubleFP[30]), "=m"(DoubleFP[31]));
251 #endif
252 }
253
254
255 void JITResolver::RestoreRegisters(uint64_t DoubleFP[], uint64_t &FSR, 
256                                    uint64_t &FPRS, uint64_t &CCR)
257 {
258 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
259
260 #if 0
261   __asm__ __volatile__ (// Restore condition-code registers
262                         "ldx %0,    %%fsr;\n\t" 
263                         "wr  %1, 0, %%fprs;\n\t"
264                         "wr  %2, 0, %%ccr;\n\t" 
265                         :: "m"(FSR), "r"(FPRS), "r"(CCR));
266 #endif
267
268   // GCC says: `asm' only allows up to thirty parameters!
269   __asm__ __volatile__ (// Restore Single/Double FP registers, part 1
270                         "ldd %0,  %%f0;\n\t"   "ldd %1, %%f2;\n\t" 
271                         "ldd %2,  %%f4;\n\t"   "ldd %3, %%f6;\n\t" 
272                         "ldd %4,  %%f8;\n\t"   "ldd %5, %%f10;\n\t" 
273                         "ldd %6,  %%f12;\n\t"  "ldd %7, %%f14;\n\t" 
274                         "ldd %8,  %%f16;\n\t"  "ldd %9, %%f18;\n\t" 
275                         "ldd %10, %%f20;\n\t" "ldd %11, %%f22;\n\t"
276                         "ldd %12, %%f24;\n\t" "ldd %13, %%f26;\n\t"
277                         "ldd %14, %%f28;\n\t" "ldd %15, %%f30;\n\t"
278                         :: "m"(DoubleFP[0]), "m"(DoubleFP[1]),
279                            "m"(DoubleFP[2]), "m"(DoubleFP[3]),
280                            "m"(DoubleFP[4]), "m"(DoubleFP[5]),
281                            "m"(DoubleFP[6]), "m"(DoubleFP[7]),
282                            "m"(DoubleFP[8]), "m"(DoubleFP[9]),
283                            "m"(DoubleFP[10]), "m"(DoubleFP[11]),
284                            "m"(DoubleFP[12]), "m"(DoubleFP[13]),
285                            "m"(DoubleFP[14]), "m"(DoubleFP[15]));
286
287   __asm__ __volatile__ (// Restore Double FP registers, part 2
288                         "ldd %0, %%f32;\n\t"  "ldd %1, %%f34;\n\t"
289                         "ldd %2, %%f36;\n\t"  "ldd %3, %%f38;\n\t"
290                         "ldd %4, %%f40;\n\t"  "ldd %5, %%f42;\n\t"
291                         "ldd %6, %%f44;\n\t"  "ldd %7, %%f46;\n\t"
292                         "ldd %8, %%f48;\n\t"  "ldd %9, %%f50;\n\t"
293                         "ldd %10, %%f52;\n\t" "ldd %11, %%f54;\n\t"
294                         "ldd %12, %%f56;\n\t" "ldd %13, %%f58;\n\t"
295                         "ldd %14, %%f60;\n\t" "ldd %15, %%f62;\n\t"
296                         :: "m"(DoubleFP[16]), "m"(DoubleFP[17]),
297                            "m"(DoubleFP[18]), "m"(DoubleFP[19]),
298                            "m"(DoubleFP[20]), "m"(DoubleFP[21]),
299                            "m"(DoubleFP[22]), "m"(DoubleFP[23]),
300                            "m"(DoubleFP[24]), "m"(DoubleFP[25]),
301                            "m"(DoubleFP[26]), "m"(DoubleFP[27]),
302                            "m"(DoubleFP[28]), "m"(DoubleFP[29]),
303                            "m"(DoubleFP[30]), "m"(DoubleFP[31]));
304 #endif
305 }
306
307 void JITResolver::CompilationCallback() {
308   // Local space to save double registers
309   uint64_t DoubleFP[32];
310   uint64_t FSR, FPRS, CCR;
311
312   SaveRegisters(DoubleFP, FSR, FPRS, CCR);
313   ++CallbackCalls;
314
315   uint64_t CameFrom = (uint64_t)(intptr_t)__builtin_return_address(0);
316   uint64_t CameFrom1 = (uint64_t)(intptr_t)__builtin_return_address(1);
317   int64_t Target = (int64_t)TheJITResolver->resolveFunctionReference(CameFrom);
318   DEBUG(std::cerr << "In callback! Addr=0x" << std::hex << CameFrom << "\n");
319   register int64_t returnAddr = 0;
320 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
321   __asm__ __volatile__ ("add %%i7, %%g0, %0" : "=r" (returnAddr) : );
322   DEBUG(std::cerr << "Read i7 (return addr) = "
323                   << std::hex << returnAddr << ", value: "
324                   << std::hex << *(unsigned*)returnAddr << "\n");
325 #endif
326
327   // If we can rewrite the ORIGINAL caller, we eliminate the whole need for a
328   // trampoline function stub!!
329   unsigned OrigCallInst = *((unsigned*)(intptr_t)CameFrom1);
330   int64_t OrigTarget = (Target-CameFrom1) >> 2;
331   if ((OrigCallInst & (1 << 30)) && 
332       (OrigTarget <= (1 << 30) && OrigTarget >= -(1 << 30)))
333   {
334     // The original call instruction was CALL <immed>, which means we can
335     // overwrite it directly, since the offset will fit into 30 bits
336     MachineInstr *C = BuildMI(V9::CALL, 1).addSImm(OrigTarget);
337     *((unsigned*)(intptr_t)CameFrom1)=TheJITResolver->getBinaryCodeForInstr(*C);
338     delete C;
339     ++OverwrittenCalls;
340   } else {
341     ++UnmodifiedCalls;
342   }
343
344   // Rewrite the call target so that we don't fault every time we execute it.
345   //
346
347   static const unsigned o6 = SparcIntRegClass::o6;
348
349   // Subtract enough to overwrite up to the 'save' instruction
350   // This depends on whether we made a short call (1 instruction) or the
351   // farCall (7 instructions)
352   uint64_t Offset = (LazyCallFlavor[CameFrom] == ShortCall) ? 4 : 28;
353   uint64_t CodeBegin = CameFrom - Offset;
354
355   // FIXME FIXME FIXME FIXME: __builtin_frame_address doesn't work if frame
356   // pointer elimination has been performed.  Having a variable sized alloca
357   // disables frame pointer elimination currently, even if it's dead.  This is
358   // a gross hack.
359   alloca(42+Offset);
360   // FIXME FIXME FIXME FIXME
361   
362   // Make sure that what we're about to overwrite is indeed "save"
363   MachineInstr *SV =BuildMI(V9::SAVEi, 3).addReg(o6).addSImm(-192).addReg(o6);
364   unsigned SaveInst = TheJITResolver->getBinaryCodeForInstr(*SV);
365   delete SV;
366   unsigned CodeInMem = *(unsigned*)(intptr_t)CodeBegin;
367   if (CodeInMem != SaveInst) {
368     std::cerr << "About to overwrite smthg not a save instr!";
369     abort();
370   }
371   // Overwrite it
372   TheJITResolver->insertJumpAtAddr(Target, CodeBegin);
373
374   RestoreRegisters(DoubleFP, FSR, FPRS, CCR);
375
376   // Change the return address to re-execute the restore, then the jump.
377   // However, we can't just modify %i7 here, because we return to the function
378   // that will restore the floating-point registers for us. Thus, we just return
379   // the value we want it to be, and the parent will take care of setting %i7
380   // correctly.
381   DEBUG(std::cerr << "Callback returning to: 0x"
382                   << std::hex << (CameFrom-Offset-12) << "\n");
383 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
384   __asm__ __volatile__ ("sub %%i7, %0, %%i7" : : "r" (Offset+12));
385 #endif
386 }
387
388 /// emitStubForFunction - This method is used by the JIT when it needs to emit
389 /// the address of a function for a function whose code has not yet been
390 /// generated.  In order to do this, it generates a stub which jumps to the lazy
391 /// function compiler, which will eventually get fixed to call the function
392 /// directly.
393 ///
394 uint64_t JITResolver::emitStubForFunction(Function *F) {
395   MCE.startFunctionStub(*F, 44);
396
397   DEBUG(std::cerr << "Emitting stub at addr: 0x" 
398                   << std::hex << MCE.getCurrentPCValue() << "\n");
399
400   unsigned o6 = SparcIntRegClass::o6, g0 = SparcIntRegClass::g0;
401
402   // restore %g0, 0, %g0
403   MachineInstr *R = BuildMI(V9::RESTOREi, 3).addMReg(g0).addSImm(0)
404                                             .addMReg(g0, MOTy::Def);
405   SparcV9.emitWord(SparcV9.getBinaryCodeForInstr(*R));
406   delete R;
407
408   // save %sp, -192, %sp
409   MachineInstr *SV = BuildMI(V9::SAVEi, 3).addReg(o6).addSImm(-192).addReg(o6);
410   SparcV9.emitWord(SparcV9.getBinaryCodeForInstr(*SV));
411   delete SV;
412
413   int64_t CurrPC = MCE.getCurrentPCValue();
414   int64_t Addr = (int64_t)addFunctionReference(CurrPC, F);
415   int64_t CallTarget = (Addr-CurrPC) >> 2;
416   if (CallTarget >= (1 << 29) || CallTarget <= -(1 << 29)) {
417     // Since this is a far call, the actual address of the call is shifted
418     // by the number of instructions it takes to calculate the exact address
419     deleteFunctionReference(CurrPC);
420     SparcV9.emitFarCall(Addr, F);
421   } else {
422     // call CallTarget              ;; invoke the callback
423     MachineInstr *Call = BuildMI(V9::CALL, 1).addSImm(CallTarget);
424     SparcV9.emitWord(SparcV9.getBinaryCodeForInstr(*Call));
425     delete Call;
426   
427     // nop                          ;; call delay slot
428     MachineInstr *Nop = BuildMI(V9::NOP, 0);
429     SparcV9.emitWord(SparcV9.getBinaryCodeForInstr(*Nop));
430     delete Nop;
431
432     addCallFlavor(CurrPC, ShortCall);
433   }
434
435   SparcV9.emitWord(0xDEADBEEF); // marker so that we know it's really a stub
436   return (intptr_t)MCE.finishFunctionStub(*F)+4; /* 1 instr past the restore */
437 }
438
439
440 SparcV9CodeEmitter::SparcV9CodeEmitter(TargetMachine &tm,
441                                        MachineCodeEmitter &M): TM(tm), MCE(M)
442 {
443   TheJITResolver = new JITResolver(*this, M);
444 }
445
446 SparcV9CodeEmitter::~SparcV9CodeEmitter() {
447   delete TheJITResolver;
448 }
449
450 void SparcV9CodeEmitter::emitWord(unsigned Val) {
451   // Output the constant in big endian byte order...
452   unsigned byteVal;
453   for (int i = 3; i >= 0; --i) {
454     byteVal = Val >> 8*i;
455     MCE.emitByte(byteVal & 255);
456   }
457 }
458
459 unsigned 
460 SparcV9CodeEmitter::getRealRegNum(unsigned fakeReg,
461                                   MachineInstr &MI) {
462   const TargetRegInfo &RI = TM.getRegInfo();
463   unsigned regClass, regType = RI.getRegType(fakeReg);
464   // At least map fakeReg into its class
465   fakeReg = RI.getClassRegNum(fakeReg, regClass);
466
467   switch (regClass) {
468   case UltraSparcRegInfo::IntRegClassID: {
469     // Sparc manual, p31
470     static const unsigned IntRegMap[] = {
471       // "o0", "o1", "o2", "o3", "o4", "o5",       "o7",
472       8, 9, 10, 11, 12, 13, 15,
473       // "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
474       16, 17, 18, 19, 20, 21, 22, 23,
475       // "i0", "i1", "i2", "i3", "i4", "i5", "i6", "i7",
476       24, 25, 26, 27, 28, 29, 30, 31,
477       // "g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7", 
478       0, 1, 2, 3, 4, 5, 6, 7,
479       // "o6"
480       14
481     }; 
482  
483     return IntRegMap[fakeReg];
484     break;
485   }
486   case UltraSparcRegInfo::FloatRegClassID: {
487     DEBUG(std::cerr << "FP reg: " << fakeReg << "\n");
488     if (regType == UltraSparcRegInfo::FPSingleRegType) {
489       // only numbered 0-31, hence can already fit into 5 bits (and 6)
490       DEBUG(std::cerr << "FP single reg, returning: " << fakeReg << "\n");
491     } else if (regType == UltraSparcRegInfo::FPDoubleRegType) {
492       // FIXME: This assumes that we only have 5-bit register fields!
493       // From Sparc Manual, page 40.
494       // The bit layout becomes: b[4], b[3], b[2], b[1], b[5]
495       fakeReg |= (fakeReg >> 5) & 1;
496       fakeReg &= 0x1f;
497       DEBUG(std::cerr << "FP double reg, returning: " << fakeReg << "\n");      
498     }
499     return fakeReg;
500   }
501   case UltraSparcRegInfo::IntCCRegClassID: {
502     /*                                   xcc, icc, ccr */
503     static const unsigned IntCCReg[] = {  6,   4,   2 };
504     
505     assert(fakeReg < sizeof(IntCCReg)/sizeof(IntCCReg[0])
506              && "CC register out of bounds for IntCCReg map");      
507     DEBUG(std::cerr << "IntCC reg: " << IntCCReg[fakeReg] << "\n");
508     return IntCCReg[fakeReg];
509   }
510   case UltraSparcRegInfo::FloatCCRegClassID: {
511     /* These are laid out %fcc0 - %fcc3 => 0 - 3, so are correct */
512     DEBUG(std::cerr << "FP CC reg: " << fakeReg << "\n");
513     return fakeReg;
514   }
515   default:
516     assert(0 && "Invalid unified register number in getRegType");
517     return fakeReg;
518   }
519 }
520
521
522 // WARNING: if the call used the delay slot to do meaningful work, that's not
523 // being accounted for, and the behavior will be incorrect!!
524 inline void SparcV9CodeEmitter::emitFarCall(uint64_t Target, Function *F) {
525   static const unsigned o6 = SparcIntRegClass::o6,
526       o7 = SparcIntRegClass::o7, g0 = SparcIntRegClass::g0,
527       g1 = SparcIntRegClass::g1, g5 = SparcIntRegClass::g5;
528
529   MachineInstr* BinaryCode[] = {
530     //
531     // Get address to branch into %g1, using %g5 as a temporary
532     //
533     // sethi %uhi(Target), %g5   ;; get upper 22 bits of Target into %g5
534     BuildMI(V9::SETHI, 2).addSImm(Target >> 42).addReg(g5),
535     // or %g5, %ulo(Target), %g5 ;; get 10 lower bits of upper word into %1
536     BuildMI(V9::ORi, 3).addReg(g5).addSImm((Target >> 32) & 0x03ff).addReg(g5),
537     // sllx %g5, 32, %g5         ;; shift those 10 bits to the upper word
538     BuildMI(V9::SLLXi6, 3).addReg(g5).addSImm(32).addReg(g5),
539     // sethi %hi(Target), %g1    ;; extract bits 10-31 into the dest reg
540     BuildMI(V9::SETHI, 2).addSImm((Target >> 10) & 0x03fffff).addReg(g1),
541     // or %g5, %g1, %g1          ;; get upper word (in %g5) into %g1
542     BuildMI(V9::ORr, 3).addReg(g5).addReg(g1).addReg(g1),
543     // or %g1, %lo(Target), %g1  ;; get lowest 10 bits of Target into %g1
544     BuildMI(V9::ORi, 3).addReg(g1).addSImm(Target & 0x03ff).addReg(g1),
545     // jmpl %g1, %g0, %o7        ;; indirect call on %g1
546     BuildMI(V9::JMPLRETr, 3).addReg(g1).addReg(g0).addReg(o7),
547     // nop                       ;; delay slot
548     BuildMI(V9::NOP, 0)
549   };
550
551   for (unsigned i=0, e=sizeof(BinaryCode)/sizeof(BinaryCode[0]); i!=e; ++i) {
552     // This is where we save the return address in the LazyResolverMap!!
553     if (i == 6 && F != 0) { // Do this right before the JMPL
554       uint64_t CurrPC = MCE.getCurrentPCValue();
555       TheJITResolver->addFunctionReference(CurrPC, F);
556       // Remember that this is a far call, to subtract appropriate offset later
557       TheJITResolver->addCallFlavor(CurrPC, JITResolver::FarCall);
558     }
559
560     emitWord(getBinaryCodeForInstr(*BinaryCode[i]));
561     delete BinaryCode[i];
562   }
563 }
564
565 bool UltraSparc::replaceMachineCodeForFunction (void *Old, void *New) {
566   if (!TheJITResolver) return true; // fail if not in JIT.
567   uint64_t Target = (uint64_t)(intptr_t)New;
568   uint64_t CodeBegin = (uint64_t)(intptr_t)Old;
569   TheJITResolver->insertJumpAtAddr(Target, CodeBegin);
570   return false;
571 }
572
573 int64_t SparcV9CodeEmitter::getMachineOpValue(MachineInstr &MI,
574                                               MachineOperand &MO) {
575   int64_t rv = 0; // Return value; defaults to 0 for unhandled cases
576                   // or things that get fixed up later by the JIT.
577
578   if (MO.isVirtualRegister()) {
579     std::cerr << "ERROR: virtual register found in machine code.\n";
580     abort();
581   } else if (MO.isPCRelativeDisp()) {
582     DEBUG(std::cerr << "PCRelativeDisp: ");
583     Value *V = MO.getVRegValue();
584     if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
585       DEBUG(std::cerr << "Saving reference to BB (VReg)\n");
586       unsigned* CurrPC = (unsigned*)(intptr_t)MCE.getCurrentPCValue();
587       BBRefs.push_back(std::make_pair(BB, std::make_pair(CurrPC, &MI)));
588     } else if (const Constant *C = dyn_cast<Constant>(V)) {
589       if (ConstantMap.find(C) != ConstantMap.end()) {
590         rv = (int64_t)MCE.getConstantPoolEntryAddress(ConstantMap[C]);
591         DEBUG(std::cerr << "const: 0x" << std::hex << rv << "\n");
592       } else {
593         std::cerr << "ERROR: constant not in map:" << MO << "\n";
594         abort();
595       }
596     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
597       // same as MO.isGlobalAddress()
598       DEBUG(std::cerr << "GlobalValue: ");
599       // external function calls, etc.?
600       if (Function *F = dyn_cast<Function>(GV)) {
601         DEBUG(std::cerr << "Function: ");
602         if (F->isExternal()) {
603           // Sparc backend broken: this MO should be `ExternalSymbol'
604           rv = (int64_t)MCE.getGlobalValueAddress(F->getName());
605         } else {
606           rv = (int64_t)MCE.getGlobalValueAddress(F);
607         }
608         if (rv == 0) {
609           DEBUG(std::cerr << "not yet generated\n");
610           // Function has not yet been code generated!
611           TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(), F);
612           // Delayed resolution...
613           rv = TheJITResolver->getLazyResolver(F);
614         } else {
615           DEBUG(std::cerr << "already generated: 0x" << std::hex << rv << "\n");
616         }
617       } else {
618         rv = (int64_t)MCE.getGlobalValueAddress(GV);
619         if (rv == 0) {
620           if (Constant *C = ConstantPointerRef::get(GV)) {
621             if (ConstantMap.find(C) != ConstantMap.end()) {
622               rv = MCE.getConstantPoolEntryAddress(ConstantMap[C]);
623             } else {
624               std::cerr << "Constant: 0x" << std::hex << (intptr_t)C
625                         << ", " << *V << " not found in ConstantMap!\n";
626               abort();
627             }
628           }
629         }
630         DEBUG(std::cerr << "Global addr: 0x" << std::hex << rv << "\n");
631       }
632       // The real target of the call is Addr = PC + (rv * 4)
633       // So undo that: give the instruction (Addr - PC) / 4
634       if (MI.getOpcode() == V9::CALL) {
635         int64_t CurrPC = MCE.getCurrentPCValue();
636         DEBUG(std::cerr << "rv addr: 0x" << std::hex << rv << "\n"
637                         << "curr PC: 0x" << std::hex << CurrPC << "\n");
638         int64_t CallInstTarget = (rv - CurrPC) >> 2;
639         if (CallInstTarget >= (1<<29) || CallInstTarget <= -(1<<29)) {
640           DEBUG(std::cerr << "Making far call!\n");
641           // address is out of bounds for the 30-bit call,
642           // make an indirect jump-and-link
643           emitFarCall(rv);
644           // this invalidates the instruction so that the call with an incorrect
645           // address will not be emitted
646           rv = 0; 
647         } else {
648           // The call fits into 30 bits, so just return the corrected address
649           rv = CallInstTarget;
650         }
651         DEBUG(std::cerr << "returning addr: 0x" << rv << "\n");
652       }
653     } else {
654       std::cerr << "ERROR: PC relative disp unhandled:" << MO << "\n";
655       abort();
656     }
657   } else if (MO.isPhysicalRegister() ||
658              MO.getType() == MachineOperand::MO_CCRegister)
659   {
660     // This is necessary because the Sparc backend doesn't actually lay out
661     // registers in the real fashion -- it skips those that it chooses not to
662     // allocate, i.e. those that are the FP, SP, etc.
663     unsigned fakeReg = MO.getAllocatedRegNum();
664     unsigned realRegByClass = getRealRegNum(fakeReg, MI);
665     DEBUG(std::cerr << MO << ": Reg[" << std::dec << fakeReg << "] => "
666                     << realRegByClass << " (LLC: " 
667                     << TM.getRegInfo().getUnifiedRegName(fakeReg) << ")\n");
668     rv = realRegByClass;
669   } else if (MO.isImmediate()) {
670     rv = MO.getImmedValue();
671     DEBUG(std::cerr << "immed: " << rv << "\n");
672   } else if (MO.isGlobalAddress()) {
673     DEBUG(std::cerr << "GlobalAddress: not PC-relative\n");
674     rv = (int64_t)
675       (intptr_t)getGlobalAddress(cast<GlobalValue>(MO.getVRegValue()),
676                                  MI, MO.isPCRelative());
677   } else if (MO.isMachineBasicBlock()) {
678     // Duplicate code of the above case for VirtualRegister, BasicBlock... 
679     // It should really hit this case, but Sparc backend uses VRegs instead
680     DEBUG(std::cerr << "Saving reference to MBB\n");
681     const BasicBlock *BB = MO.getMachineBasicBlock()->getBasicBlock();
682     unsigned* CurrPC = (unsigned*)(intptr_t)MCE.getCurrentPCValue();
683     BBRefs.push_back(std::make_pair(BB, std::make_pair(CurrPC, &MI)));
684   } else if (MO.isExternalSymbol()) {
685     // Sparc backend doesn't generate this (yet...)
686     std::cerr << "ERROR: External symbol unhandled: " << MO << "\n";
687     abort();
688   } else if (MO.isFrameIndex()) {
689     // Sparc backend doesn't generate this (yet...)
690     int FrameIndex = MO.getFrameIndex();
691     std::cerr << "ERROR: Frame index unhandled.\n";
692     abort();
693   } else if (MO.isConstantPoolIndex()) {
694     // Sparc backend doesn't generate this (yet...)
695     std::cerr << "ERROR: Constant Pool index unhandled.\n";
696     abort();
697   } else {
698     std::cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
699     abort();
700   }
701
702   // Finally, deal with the various bitfield-extracting functions that
703   // are used in SPARC assembly. (Some of these make no sense in combination
704   // with some of the above; we'll trust that the instruction selector
705   // will not produce nonsense, and not check for valid combinations here.)
706   if (MO.opLoBits32()) {          // %lo(val) == %lo() in Sparc ABI doc
707     return rv & 0x03ff;
708   } else if (MO.opHiBits32()) {   // %lm(val) == %hi() in Sparc ABI doc
709     return (rv >> 10) & 0x03fffff;
710   } else if (MO.opLoBits64()) {   // %hm(val) == %ulo() in Sparc ABI doc
711     return (rv >> 32) & 0x03ff;
712   } else if (MO.opHiBits64()) {   // %hh(val) == %uhi() in Sparc ABI doc
713     return rv >> 42;
714   } else {                        // (unadorned) val
715     return rv;
716   }
717 }
718
719 unsigned SparcV9CodeEmitter::getValueBit(int64_t Val, unsigned bit) {
720   Val >>= bit;
721   return (Val & 1);
722 }
723
724 bool SparcV9CodeEmitter::runOnMachineFunction(MachineFunction &MF) {
725   MCE.startFunction(MF);
726   DEBUG(std::cerr << "Starting function " << MF.getFunction()->getName()
727             << ", address: " << "0x" << std::hex 
728             << (long)MCE.getCurrentPCValue() << "\n");
729
730   // The Sparc backend does not use MachineConstantPool;
731   // instead, it has its own constant pool implementation.
732   // We create a new MachineConstantPool here to be compatible with the emitter.
733   MachineConstantPool MCP;
734   const hash_set<const Constant*> &pool = MF.getInfo()->getConstantPoolValues();
735   for (hash_set<const Constant*>::const_iterator I = pool.begin(),
736          E = pool.end();  I != E; ++I)
737   {
738     Constant *C = (Constant*)*I;
739     unsigned idx = MCP.getConstantPoolIndex(C);
740     DEBUG(std::cerr << "Constant[" << idx << "] = 0x" << (intptr_t)C << "\n");
741     ConstantMap[C] = idx;
742   }  
743   MCE.emitConstantPool(&MCP);
744
745   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
746     emitBasicBlock(*I);
747   MCE.finishFunction(MF);
748
749   DEBUG(std::cerr << "Finishing fn " << MF.getFunction()->getName() << "\n");
750   ConstantMap.clear();
751
752   // Resolve branches to BasicBlocks for the entire function
753   for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
754     long Location = BBLocations[BBRefs[i].first];
755     unsigned *Ref = BBRefs[i].second.first;
756     MachineInstr *MI = BBRefs[i].second.second;
757     DEBUG(std::cerr << "Fixup @ " << std::hex << Ref << " to 0x" << Location
758                     << " in instr: " << std::dec << *MI);
759     for (unsigned ii = 0, ee = MI->getNumOperands(); ii != ee; ++ii) {
760       MachineOperand &op = MI->getOperand(ii);
761       if (op.isPCRelativeDisp()) {
762         // the instruction's branch target is made such that it branches to
763         // PC + (branchTarget * 4), so undo that arithmetic here:
764         // Location is the target of the branch
765         // Ref is the location of the instruction, and hence the PC
766         int64_t branchTarget = (Location - (long)Ref) >> 2;
767         // Save the flags.
768         bool loBits32=false, hiBits32=false, loBits64=false, hiBits64=false;   
769         if (op.opLoBits32()) { loBits32=true; }
770         if (op.opHiBits32()) { hiBits32=true; }
771         if (op.opLoBits64()) { loBits64=true; }
772         if (op.opHiBits64()) { hiBits64=true; }
773         MI->SetMachineOperandConst(ii, MachineOperand::MO_SignExtendedImmed,
774                                    branchTarget);
775         if (loBits32) { MI->setOperandLo32(ii); }
776         else if (hiBits32) { MI->setOperandHi32(ii); }
777         else if (loBits64) { MI->setOperandLo64(ii); }
778         else if (hiBits64) { MI->setOperandHi64(ii); }
779         DEBUG(std::cerr << "Rewrote BB ref: ");
780         unsigned fixedInstr = SparcV9CodeEmitter::getBinaryCodeForInstr(*MI);
781         *Ref = fixedInstr;
782         break;
783       }
784     }
785   }
786   BBRefs.clear();
787   BBLocations.clear();
788
789   return false;
790 }
791
792 void SparcV9CodeEmitter::emitBasicBlock(MachineBasicBlock &MBB) {
793   currBB = MBB.getBasicBlock();
794   BBLocations[currBB] = MCE.getCurrentPCValue();
795   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I){
796     unsigned binCode = getBinaryCodeForInstr(**I);
797     if (binCode == (1 << 30)) {
798       // this is an invalid call: the addr is out of bounds. that means a code
799       // sequence has already been emitted, and this is a no-op
800       DEBUG(std::cerr << "Call supressed: already emitted far call.\n");
801     } else {
802       emitWord(binCode);
803     }
804   }
805 }
806
807 void* SparcV9CodeEmitter::getGlobalAddress(GlobalValue *V, MachineInstr &MI,
808                                            bool isPCRelative)
809 {
810   if (isPCRelative) { // must be a call, this is a major hack!
811     // Try looking up the function to see if it is already compiled!
812     if (void *Addr = (void*)(intptr_t)MCE.getGlobalValueAddress(V)) {
813       intptr_t CurByte = MCE.getCurrentPCValue();
814       // The real target of the call is Addr = PC + (target * 4)
815       // CurByte is the PC, Addr we just received
816       return (void*) (((long)Addr - (long)CurByte) >> 2);
817     } else {
818       if (Function *F = dyn_cast<Function>(V)) {
819         // Function has not yet been code generated!
820         TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(),
821                                              cast<Function>(V));
822         // Delayed resolution...
823         return 
824           (void*)(intptr_t)TheJITResolver->getLazyResolver(cast<Function>(V));
825
826       } else if (Constant *C = ConstantPointerRef::get(V)) {
827         if (ConstantMap.find(C) != ConstantMap.end()) {
828           return (void*)
829             (intptr_t)MCE.getConstantPoolEntryAddress(ConstantMap[C]);
830         } else {
831           std::cerr << "Constant: 0x" << std::hex << &*C << std::dec
832                     << ", " << *V << " not found in ConstantMap!\n";
833           abort();
834         }
835       } else {
836         std::cerr << "Unhandled global: " << *V << "\n";
837         abort();
838       }
839     }
840   } else {
841     return (void*)(intptr_t)MCE.getGlobalValueAddress(V);
842   }
843 }
844
845 #include "SparcV9CodeEmitter.inc"