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