1 //===-- SparcV9CodeEmitter.cpp --------------------------------------------===//
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Constants.h"
8 #include "llvm/Function.h"
9 #include "llvm/GlobalVariable.h"
10 #include "llvm/PassManager.h"
11 #include "llvm/CodeGen/MachineCodeEmitter.h"
12 #include "llvm/CodeGen/MachineConstantPool.h"
13 #include "llvm/CodeGen/MachineFunctionInfo.h"
14 #include "llvm/CodeGen/MachineFunctionPass.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/Target/TargetMachine.h"
17 #include "llvm/Target/TargetData.h"
18 #include "Support/Debug.h"
19 #include "Support/hash_set"
20 #include "SparcInternals.h"
21 #include "SparcV9CodeEmitter.h"
23 bool UltraSparc::addPassesToEmitMachineCode(FunctionPassManager &PM,
24 MachineCodeEmitter &MCE) {
25 MachineCodeEmitter *M = &MCE;
26 DEBUG(M = MachineCodeEmitter::createFilePrinterEmitter(MCE));
27 PM.add(new SparcV9CodeEmitter(*this, *M));
28 PM.add(createMachineCodeDestructionPass()); // Free stuff no longer needed
34 SparcV9CodeEmitter &SparcV9;
35 MachineCodeEmitter &MCE;
37 /// LazyCodeGenMap - Keep track of call sites for functions that are to be
40 std::map<uint64_t, Function*> LazyCodeGenMap;
42 /// LazyResolverMap - Keep track of the lazy resolver created for a
43 /// particular function so that we can reuse them if necessary.
45 std::map<Function*, uint64_t> LazyResolverMap;
48 enum CallType { ShortCall, FarCall };
51 /// We need to keep track of whether we used a simple call or a far call
52 /// (many instructions) in sequence. This means we need to keep track of
53 /// what type of stub we generate.
54 static std::map<uint64_t, CallType> LazyCallFlavor;
57 JITResolver(SparcV9CodeEmitter &V9,
58 MachineCodeEmitter &mce) : SparcV9(V9), MCE(mce) {}
59 uint64_t getLazyResolver(Function *F);
60 uint64_t addFunctionReference(uint64_t Address, Function *F);
61 void deleteFunctionReference(uint64_t Address);
62 void addCallFlavor(uint64_t Address, CallType Flavor) {
63 LazyCallFlavor[Address] = Flavor;
66 // Utility functions for accessing data from static callback
67 uint64_t getCurrentPCValue() {
68 return MCE.getCurrentPCValue();
70 unsigned getBinaryCodeForInstr(MachineInstr &MI) {
71 return SparcV9.getBinaryCodeForInstr(MI);
74 inline uint64_t insertFarJumpAtAddr(int64_t Value, uint64_t Addr);
77 uint64_t emitStubForFunction(Function *F);
78 static void SaveRestoreRegisters();
79 static uint64_t CompilationCallback();
80 uint64_t resolveFunctionReference(uint64_t RetAddr);
84 JITResolver *TheJITResolver;
85 std::map<uint64_t, JITResolver::CallType> JITResolver::LazyCallFlavor;
88 /// addFunctionReference - This method is called when we need to emit the
89 /// address of a function that has not yet been emitted, so we don't know the
90 /// address. Instead, we emit a call to the CompilationCallback method, and
91 /// keep track of where we are.
93 uint64_t JITResolver::addFunctionReference(uint64_t Address, Function *F) {
94 LazyCodeGenMap[Address] = F;
95 return (intptr_t)&JITResolver::SaveRestoreRegisters;
98 /// deleteFunctionReference - If we are emitting a far call, we already added a
99 /// reference to the function, but it is now incorrect, since the address to the
100 /// JIT resolver is too far away to be a simple call instruction. This is used
101 /// to remove the address from the map.
103 void JITResolver::deleteFunctionReference(uint64_t Address) {
104 std::map<uint64_t, Function*>::iterator I = LazyCodeGenMap.find(Address);
105 assert(I != LazyCodeGenMap.end() && "Not in map!");
106 LazyCodeGenMap.erase(I);
109 uint64_t JITResolver::resolveFunctionReference(uint64_t RetAddr) {
110 std::map<uint64_t, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
111 assert(I != LazyCodeGenMap.end() && "Not in map!");
112 Function *F = I->second;
113 LazyCodeGenMap.erase(I);
114 return MCE.forceCompilationOf(F);
117 uint64_t JITResolver::getLazyResolver(Function *F) {
118 std::map<Function*, uint64_t>::iterator I = LazyResolverMap.lower_bound(F);
119 if (I != LazyResolverMap.end() && I->first == F) return I->second;
121 //std::cerr << "Getting lazy resolver for : " << ((Value*)F)->getName() << "\n";
123 uint64_t Stub = emitStubForFunction(F);
124 LazyResolverMap.insert(I, std::make_pair(F, Stub));
128 uint64_t JITResolver::insertFarJumpAtAddr(int64_t Target, uint64_t Addr) {
130 static const unsigned
131 o6 = SparcIntRegClass::o6, g0 = SparcIntRegClass::g0,
132 g1 = SparcIntRegClass::g1, g5 = SparcIntRegClass::g5;
134 MachineInstr* BinaryCode[] = {
136 // Get address to branch into %g1, using %g5 as a temporary
138 // sethi %uhi(Target), %g5 ;; get upper 22 bits of Target into %g5
139 BuildMI(V9::SETHI, 2).addSImm(Target >> 42).addReg(g5),
140 // or %g5, %ulo(Target), %g5 ;; get 10 lower bits of upper word into %g5
141 BuildMI(V9::ORi, 3).addReg(g5).addSImm((Target >> 32) & 0x03ff).addReg(g5),
142 // sllx %g5, 32, %g5 ;; shift those 10 bits to the upper word
143 BuildMI(V9::SLLXi6, 3).addReg(g5).addSImm(32).addReg(g5),
144 // sethi %hi(Target), %g1 ;; extract bits 10-31 into the dest reg
145 BuildMI(V9::SETHI, 2).addSImm((Target >> 10) & 0x03fffff).addReg(g1),
146 // or %g5, %g1, %g1 ;; get upper word (in %g5) into %g1
147 BuildMI(V9::ORr, 3).addReg(g5).addReg(g1).addReg(g1),
148 // or %g1, %lo(Target), %g1 ;; get lowest 10 bits of Target into %g1
149 BuildMI(V9::ORi, 3).addReg(g1).addSImm(Target & 0x03ff).addReg(g1),
150 // jmpl %g1, %g0, %g0 ;; indirect branch on %g1
151 BuildMI(V9::JMPLRETr, 3).addReg(g1).addReg(g0).addReg(g0),
156 for (unsigned i=0, e=sizeof(BinaryCode)/sizeof(BinaryCode[0]); i!=e; ++i) {
157 *((unsigned*)(intptr_t)Addr) = getBinaryCodeForInstr(*BinaryCode[i]);
158 delete BinaryCode[i];
165 void JITResolver::SaveRestoreRegisters() {
166 uint32_t SingleFP[32];
167 uint64_t DoubleFP[16];
168 // FIXME: uint128_t QuadFloatRegs[..];
169 uint64_t CCR, FSR, FPRS, g1, g5;
171 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
172 __asm__ __volatile__ (// Save g1 and g5
173 "stx %%g1, %0;\n\t" "stx %%g5, %1;\n\t"
174 : "=m"(g1), "=m"(g5));
176 __asm__ __volatile__ (// Save condition-code registers
180 : "=m"(FSR), "=r"(FPRS), "=r"(CCR));
182 // GCC says: `asm' only allows up to thirty parameters!
183 __asm__ __volatile__ (// Save Single FP registers, part 1
184 "st %%f0, %0;\n\t" "st %%f1, %1;\n\t"
185 "st %%f2, %2;\n\t" "st %%f3, %3;\n\t"
186 "st %%f4, %4;\n\t" "st %%f5, %5;\n\t"
187 "st %%f6, %6;\n\t" "st %%f7, %7;\n\t"
188 "st %%f8, %8;\n\t" "st %%f9, %9;\n\t"
189 "st %%f10, %10;\n\t" "st %%f11, %11;\n\t"
190 "st %%f12, %12;\n\t" "st %%f13, %13;\n\t"
191 "st %%f14, %14;\n\t" "st %%f15, %15;\n\t"
192 : "=m"(SingleFP[ 0]), "=m"(SingleFP[ 1]),
193 "=m"(SingleFP[ 2]), "=m"(SingleFP[ 3]),
194 "=m"(SingleFP[ 4]), "=m"(SingleFP[ 5]),
195 "=m"(SingleFP[ 6]), "=m"(SingleFP[ 7]),
196 "=m"(SingleFP[ 8]), "=m"(SingleFP[ 9]),
197 "=m"(SingleFP[10]), "=m"(SingleFP[11]),
198 "=m"(SingleFP[12]), "=m"(SingleFP[13]),
199 "=m"(SingleFP[14]), "=m"(SingleFP[15]));
201 __asm__ __volatile__ (// Save Single FP registers, part 2
202 "st %%f16, %0;\n\t" "st %%f17, %1;\n\t"
203 "st %%f18, %2;\n\t" "st %%f19, %3;\n\t"
204 "st %%f20, %4;\n\t" "st %%f21, %5;\n\t"
205 "st %%f22, %6;\n\t" "st %%f23, %7;\n\t"
206 "st %%f24, %8;\n\t" "st %%f25, %9;\n\t"
207 "st %%f26, %10;\n\t" "st %%f27, %11;\n\t"
208 "st %%f28, %12;\n\t" "st %%f29, %13;\n\t"
209 "st %%f30, %14;\n\t" "st %%f31, %15;\n\t"
210 : "=m"(SingleFP[16]), "=m"(SingleFP[17]),
211 "=m"(SingleFP[18]), "=m"(SingleFP[19]),
212 "=m"(SingleFP[20]), "=m"(SingleFP[21]),
213 "=m"(SingleFP[22]), "=m"(SingleFP[23]),
214 "=m"(SingleFP[24]), "=m"(SingleFP[25]),
215 "=m"(SingleFP[26]), "=m"(SingleFP[27]),
216 "=m"(SingleFP[28]), "=m"(SingleFP[29]),
217 "=m"(SingleFP[30]), "=m"(SingleFP[31]));
219 __asm__ __volatile__ (// Save Double FP registers
220 "std %%f32, %0;\n\t" "std %%f34, %1;\n\t"
221 "std %%f36, %2;\n\t" "std %%f38, %3;\n\t"
222 "std %%f40, %4;\n\t" "std %%f42, %5;\n\t"
223 "std %%f44, %6;\n\t" "std %%f46, %7;\n\t"
224 "std %%f48, %8;\n\t" "std %%f50, %9;\n\t"
225 "std %%f52, %10;\n\t" "std %%f54, %11;\n\t"
226 "std %%f56, %12;\n\t" "std %%f58, %13;\n\t"
227 "std %%f60, %14;\n\t" "std %%f62, %15;\n\t"
228 : "=m"(DoubleFP[32/2-16]), "=m"(DoubleFP[34/2-16]),
229 "=m"(DoubleFP[36/2-16]), "=m"(DoubleFP[38/2-16]),
230 "=m"(DoubleFP[40/2-16]), "=m"(DoubleFP[42/2-16]),
231 "=m"(DoubleFP[44/2-16]), "=m"(DoubleFP[46/2-16]),
232 "=m"(DoubleFP[48/2-16]), "=m"(DoubleFP[50/2-16]),
233 "=m"(DoubleFP[52/2-16]), "=m"(DoubleFP[54/2-16]),
234 "=m"(DoubleFP[56/2-16]), "=m"(DoubleFP[58/2-16]),
235 "=m"(DoubleFP[60/2-16]), "=m"(DoubleFP[62/2-16]));
238 // Resolve the function call
239 register uint64_t restoreAddr = CompilationCallback();
241 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
242 // Set the return address to re-execute the `restore' instruction
243 __asm__ __volatile__ ("or %%o0, %%g0, %%i7;\n\t"
246 "ldx %0, %%g1;\n\t" "ldx %1, %%g5;\n\t"
247 :: "m"(g1), "m"(g5));
249 __asm__ __volatile__ (// Restore condition-code registers
251 "wr %1, 0, %%fprs;\n\t"
252 "wr %2, 0, %%ccr;\n\t"
253 :: "m"(FSR), "r"(FPRS), "r"(CCR));
255 // GCC says: `asm' only allows up to thirty parameters!
256 __asm__ __volatile__ (// Restore Single FP registers, part 1
257 "ld %0, %%f0;\n\t" "ld %1, %%f1;\n\t"
258 "ld %2, %%f2;\n\t" "ld %3, %%f3;\n\t"
259 "ld %4, %%f4;\n\t" "ld %5, %%f5;\n\t"
260 "ld %6, %%f6;\n\t" "ld %7, %%f7;\n\t"
261 "ld %8, %%f8;\n\t" "ld %9, %%f9;\n\t"
262 "ld %10, %%f10;\n\t" "ld %11, %%f11;\n\t"
263 "ld %12, %%f12;\n\t" "ld %13, %%f13;\n\t"
264 "ld %14, %%f14;\n\t" "ld %15, %%f15;\n\t"
265 :: "m"(SingleFP[0]), "m"(SingleFP[1]),
266 "m"(SingleFP[2]), "m"(SingleFP[3]),
267 "m"(SingleFP[4]), "m"(SingleFP[5]),
268 "m"(SingleFP[6]), "m"(SingleFP[7]),
269 "m"(SingleFP[8]), "m"(SingleFP[9]),
270 "m"(SingleFP[10]), "m"(SingleFP[11]),
271 "m"(SingleFP[12]), "m"(SingleFP[13]),
272 "m"(SingleFP[14]), "m"(SingleFP[15]));
274 __asm__ __volatile__ (// Restore Single FP registers, part 2
275 "ld %0, %%f16;\n\t" "ld %1, %%f17;\n\t"
276 "ld %2, %%f18;\n\t" "ld %3, %%f19;\n\t"
277 "ld %4, %%f20;\n\t" "ld %5, %%f21;\n\t"
278 "ld %6, %%f22;\n\t" "ld %7, %%f23;\n\t"
279 "ld %8, %%f24;\n\t" "ld %9, %%f25;\n\t"
280 "ld %10, %%f26;\n\t" "ld %11, %%f27;\n\t"
281 "ld %12, %%f28;\n\t" "ld %13, %%f29;\n\t"
282 "ld %14, %%f30;\n\t" "ld %15, %%f31;\n\t"
283 :: "m"(SingleFP[16]), "m"(SingleFP[17]),
284 "m"(SingleFP[18]), "m"(SingleFP[19]),
285 "m"(SingleFP[20]), "m"(SingleFP[21]),
286 "m"(SingleFP[22]), "m"(SingleFP[23]),
287 "m"(SingleFP[24]), "m"(SingleFP[25]),
288 "m"(SingleFP[26]), "m"(SingleFP[27]),
289 "m"(SingleFP[28]), "m"(SingleFP[29]),
290 "m"(SingleFP[30]), "m"(SingleFP[31]));
292 __asm__ __volatile__ (// Restore Double FP registers
293 "ldd %0, %%f32;\n\t" "ldd %1, %%f34;\n\t"
294 "ldd %2, %%f36;\n\t" "ldd %3, %%f38;\n\t"
295 "ldd %4, %%f40;\n\t" "ldd %5, %%f42;\n\t"
296 "ldd %6, %%f44;\n\t" "ldd %7, %%f46;\n\t"
297 "ldd %8, %%f48;\n\t" "ldd %9, %%f50;\n\t"
298 "ldd %10, %%f52;\n\t" "ldd %11, %%f54;\n\t"
299 "ldd %12, %%f56;\n\t" "ldd %13, %%f58;\n\t"
300 "ldd %14, %%f60;\n\t" "ldd %15, %%f62;\n\t"
301 :: "m"(DoubleFP[32/2-16]), "m"(DoubleFP[34/2-16]),
302 "m"(DoubleFP[36/2-16]), "m"(DoubleFP[38/2-16]),
303 "m"(DoubleFP[40/2-16]), "m"(DoubleFP[42/2-16]),
304 "m"(DoubleFP[44/2-16]), "m"(DoubleFP[46/2-16]),
305 "m"(DoubleFP[48/2-16]), "m"(DoubleFP[50/2-16]),
306 "m"(DoubleFP[52/2-16]), "m"(DoubleFP[54/2-16]),
307 "m"(DoubleFP[56/2-16]), "m"(DoubleFP[58/2-16]),
308 "m"(DoubleFP[60/2-16]), "m"(DoubleFP[62/2-16]));
312 uint64_t JITResolver::CompilationCallback() {
313 uint64_t CameFrom = (uint64_t)(intptr_t)__builtin_return_address(1);
314 int64_t Target = (int64_t)TheJITResolver->resolveFunctionReference(CameFrom);
315 DEBUG(std::cerr << "In callback! Addr=0x" << std::hex << CameFrom << "\n");
316 register int64_t returnAddr = 0;
317 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
318 __asm__ __volatile__ ("add %%i7, %%g0, %0" : "=r" (returnAddr) : );
319 DEBUG(std::cerr << "Read i7 (return addr) = "
320 << std::hex << returnAddr << ", value: "
321 << std::hex << *(unsigned*)returnAddr << "\n");
324 // Rewrite the call target so that we don't fault every time we execute it.
327 static const unsigned o6 = SparcIntRegClass::o6;
329 // Subtract enough to overwrite up to the 'save' instruction
330 // This depends on whether we made a short call (1 instruction) or the
331 // farCall (7 instructions)
332 uint64_t Offset = (LazyCallFlavor[CameFrom] == ShortCall) ? 4 : 28;
333 uint64_t CodeBegin = CameFrom - Offset;
335 // Make sure that what we're about to overwrite is indeed "save"
336 MachineInstr *SV = BuildMI(V9::SAVEi, 3).addReg(o6).addSImm(-192).addReg(o6);
337 unsigned SaveInst = TheJITResolver->getBinaryCodeForInstr(*SV);
339 unsigned CodeInMem = *(unsigned*)(intptr_t)CodeBegin;
340 assert(CodeInMem == SaveInst && "About to overwrite smthg not a save instr!");
341 DEBUG(std::cerr << "Emitting a far jump to 0x" << std::hex << Target << "\n");
342 TheJITResolver->insertFarJumpAtAddr(Target, CodeBegin);
344 // FIXME: if the target function is close enough to fit into the 19bit disp of
345 // BA, we should use this version, as its much cheaper to generate.
347 uint64_t InstAddr = CodeBegin;
349 MachineInstr *MI = BuildMI(V9::BA, 1).addSImm(Target);
350 *((unsigned*)(intptr_t)InstAddr)=TheJITResolver->getBinaryCodeForInstr(*MI);
355 MI = BuildMI(V9::NOP, 0);
356 *((unsigned*)(intptr_t))=TheJITResolver->getBinaryCodeForInstr(*Nop);
360 // Change the return address to reexecute the restore, then the jump However,
361 // we can't just modify %i7 here, because we return to the function that will
362 // restore the floating-point registers for us. Thus, we just return the value
363 // we want it to be, and the parent will take care of setting %i7 correctly.
364 DEBUG(std::cerr << "Callback returning the addr of restore inst: "
365 << std::hex << (CameFrom-Offset-12) << "\n");
366 return CameFrom - Offset - 12; // 8 because of call+delay, 4 more to restore
369 /// emitStubForFunction - This method is used by the JIT when it needs to emit
370 /// the address of a function for a function whose code has not yet been
371 /// generated. In order to do this, it generates a stub which jumps to the lazy
372 /// function compiler, which will eventually get fixed to call the function
375 uint64_t JITResolver::emitStubForFunction(Function *F) {
376 // FIXME: 40 is not enough... but should be
377 MCE.startFunctionStub(*F, 64);
379 DEBUG(std::cerr << "Emitting stub at addr: 0x"
380 << std::hex << MCE.getCurrentPCValue() << "\n");
382 unsigned o6 = SparcIntRegClass::o6, g0 = SparcIntRegClass::g0;
384 // restore %g0, 0, %g0
385 MachineInstr *R = BuildMI(V9::RESTOREi, 3).addMReg(g0).addSImm(0)
386 .addMReg(g0, MOTy::Def);
387 SparcV9.emitWord(SparcV9.getBinaryCodeForInstr(*R));
390 // save %sp, -192, %sp
391 MachineInstr *SV = BuildMI(V9::SAVEi, 3).addReg(o6).addSImm(-192).addReg(o6);
392 SparcV9.emitWord(SparcV9.getBinaryCodeForInstr(*SV));
395 int64_t CurrPC = MCE.getCurrentPCValue();
396 int64_t Addr = (int64_t)addFunctionReference(CurrPC, F);
397 int64_t CallTarget = (Addr-CurrPC) >> 2;
398 //if (CallTarget >= (1 << 29) || CallTarget <= -(1 << 29)) {
399 // Since this is a far call, the actual address of the call is shifted
400 // by the number of instructions it takes to calculate the exact address
401 deleteFunctionReference(CurrPC);
402 SparcV9.emitFarCall(Addr, F);
405 // call CallTarget ;; invoke the callback
406 MachineInstr *Call = BuildMI(V9::CALL, 1).addSImm(CallTarget);
407 SparcV9.emitWord(SparcV9.getBinaryCodeForInstr(*Call));
410 // nop ;; call delay slot
411 MachineInstr *Nop = BuildMI(V9::NOP, 0);
412 SparcV9.emitWord(SparcV9.getBinaryCodeForInstr(*Nop));
415 addCallFlavor(CurrPC, ShortCall);
419 SparcV9.emitWord(0xDEADBEEF); // marker so that we know it's really a stub
420 return (intptr_t)MCE.finishFunctionStub(*F)+4; /* 1 instr past the restore */
424 SparcV9CodeEmitter::SparcV9CodeEmitter(TargetMachine &tm,
425 MachineCodeEmitter &M): TM(tm), MCE(M)
427 TheJITResolver = new JITResolver(*this, M);
430 SparcV9CodeEmitter::~SparcV9CodeEmitter() {
431 delete TheJITResolver;
434 void SparcV9CodeEmitter::emitWord(unsigned Val) {
435 // Output the constant in big endian byte order...
437 for (int i = 3; i >= 0; --i) {
438 byteVal = Val >> 8*i;
439 MCE.emitByte(byteVal & 255);
444 SparcV9CodeEmitter::getRealRegNum(unsigned fakeReg,
446 const TargetRegInfo &RI = TM.getRegInfo();
447 unsigned regClass, regType = RI.getRegType(fakeReg);
448 // At least map fakeReg into its class
449 fakeReg = RI.getClassRegNum(fakeReg, regClass);
452 case UltraSparcRegInfo::IntRegClassID: {
454 static const unsigned IntRegMap[] = {
455 // "o0", "o1", "o2", "o3", "o4", "o5", "o7",
456 8, 9, 10, 11, 12, 13, 15,
457 // "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
458 16, 17, 18, 19, 20, 21, 22, 23,
459 // "i0", "i1", "i2", "i3", "i4", "i5", "i6", "i7",
460 24, 25, 26, 27, 28, 29, 30, 31,
461 // "g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7",
462 0, 1, 2, 3, 4, 5, 6, 7,
467 return IntRegMap[fakeReg];
470 case UltraSparcRegInfo::FloatRegClassID: {
471 DEBUG(std::cerr << "FP reg: " << fakeReg << "\n");
472 if (regType == UltraSparcRegInfo::FPSingleRegType) {
473 // only numbered 0-31, hence can already fit into 5 bits (and 6)
474 DEBUG(std::cerr << "FP single reg, returning: " << fakeReg << "\n");
475 } else if (regType == UltraSparcRegInfo::FPDoubleRegType) {
476 // FIXME: This assumes that we only have 5-bit register fiels!
477 // From Sparc Manual, page 40.
478 // The bit layout becomes: b[4], b[3], b[2], b[1], b[5]
479 fakeReg |= (fakeReg >> 5) & 1;
481 DEBUG(std::cerr << "FP double reg, returning: " << fakeReg << "\n");
485 case UltraSparcRegInfo::IntCCRegClassID: {
487 static const unsigned IntCCReg[] = { 6, 4, 2 };
489 assert(fakeReg < sizeof(IntCCReg)/sizeof(IntCCReg[0])
490 && "CC register out of bounds for IntCCReg map");
491 DEBUG(std::cerr << "IntCC reg: " << IntCCReg[fakeReg] << "\n");
492 return IntCCReg[fakeReg];
494 case UltraSparcRegInfo::FloatCCRegClassID: {
495 /* These are laid out %fcc0 - %fcc3 => 0 - 3, so are correct */
496 DEBUG(std::cerr << "FP CC reg: " << fakeReg << "\n");
500 assert(0 && "Invalid unified register number in getRegType");
506 // WARNING: if the call used the delay slot to do meaningful work, that's not
507 // being accounted for, and the behavior will be incorrect!!
508 inline void SparcV9CodeEmitter::emitFarCall(uint64_t Target, Function *F) {
509 static const unsigned o6 = SparcIntRegClass::o6,
510 o7 = SparcIntRegClass::o7, g0 = SparcIntRegClass::g0,
511 g1 = SparcIntRegClass::g1, g5 = SparcIntRegClass::g5;
513 MachineInstr* BinaryCode[] = {
515 // Get address to branch into %g1, using %g5 as a temporary
517 // sethi %uhi(Target), %g5 ;; get upper 22 bits of Target into %g5
518 BuildMI(V9::SETHI, 2).addSImm(Target >> 42).addReg(g5),
519 // or %g5, %ulo(Target), %g5 ;; get 10 lower bits of upper word into %1
520 BuildMI(V9::ORi, 3).addReg(g5).addSImm((Target >> 32) & 0x03ff).addReg(g5),
521 // sllx %g5, 32, %g5 ;; shift those 10 bits to the upper word
522 BuildMI(V9::SLLXi6, 3).addReg(g5).addSImm(32).addReg(g5),
523 // sethi %hi(Target), %g1 ;; extract bits 10-31 into the dest reg
524 BuildMI(V9::SETHI, 2).addSImm((Target >> 10) & 0x03fffff).addReg(g1),
525 // or %g5, %g1, %g1 ;; get upper word (in %g5) into %g1
526 BuildMI(V9::ORr, 3).addReg(g5).addReg(g1).addReg(g1),
527 // or %g1, %lo(Target), %g1 ;; get lowest 10 bits of Target into %g1
528 BuildMI(V9::ORi, 3).addReg(g1).addSImm(Target & 0x03ff).addReg(g1),
529 // jmpl %g1, %g0, %o7 ;; indirect call on %g1
530 BuildMI(V9::JMPLRETr, 3).addReg(g1).addReg(g0).addReg(o7),
535 for (unsigned i=0, e=sizeof(BinaryCode)/sizeof(BinaryCode[0]); i!=e; ++i) {
536 // This is where we save the return address in the LazyResolverMap!!
537 if (i == 6 && F != 0) { // Do this right before the JMPL
538 uint64_t CurrPC = MCE.getCurrentPCValue();
539 TheJITResolver->addFunctionReference(CurrPC, F);
540 // Remember that this is a far call, to subtract appropriate offset later
541 TheJITResolver->addCallFlavor(CurrPC, JITResolver::FarCall);
544 emitWord(getBinaryCodeForInstr(*BinaryCode[i]));
545 delete BinaryCode[i];
550 int64_t SparcV9CodeEmitter::getMachineOpValue(MachineInstr &MI,
551 MachineOperand &MO) {
552 int64_t rv = 0; // Return value; defaults to 0 for unhandled cases
553 // or things that get fixed up later by the JIT.
555 if (MO.isVirtualRegister()) {
556 std::cerr << "ERROR: virtual register found in machine code.\n";
558 } else if (MO.isPCRelativeDisp()) {
559 DEBUG(std::cerr << "PCRelativeDisp: ");
560 Value *V = MO.getVRegValue();
561 if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
562 DEBUG(std::cerr << "Saving reference to BB (VReg)\n");
563 unsigned* CurrPC = (unsigned*)(intptr_t)MCE.getCurrentPCValue();
564 BBRefs.push_back(std::make_pair(BB, std::make_pair(CurrPC, &MI)));
565 } else if (const Constant *C = dyn_cast<Constant>(V)) {
566 if (ConstantMap.find(C) != ConstantMap.end()) {
567 rv = (int64_t)MCE.getConstantPoolEntryAddress(ConstantMap[C]);
568 DEBUG(std::cerr << "const: 0x" << std::hex << rv << "\n");
570 std::cerr << "ERROR: constant not in map:" << MO << "\n";
573 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
574 // same as MO.isGlobalAddress()
575 DEBUG(std::cerr << "GlobalValue: ");
576 // external function calls, etc.?
577 if (Function *F = dyn_cast<Function>(GV)) {
578 DEBUG(std::cerr << "Function: ");
579 if (F->isExternal()) {
580 // Sparc backend broken: this MO should be `ExternalSymbol'
581 rv = (int64_t)MCE.getGlobalValueAddress(F->getName());
583 rv = (int64_t)MCE.getGlobalValueAddress(F);
586 DEBUG(std::cerr << "not yet generated\n");
587 // Function has not yet been code generated!
588 TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(), F);
589 // Delayed resolution...
590 rv = TheJITResolver->getLazyResolver(F);
592 DEBUG(std::cerr << "already generated: 0x" << std::hex << rv << "\n");
595 rv = (int64_t)MCE.getGlobalValueAddress(GV);
597 if (Constant *C = ConstantPointerRef::get(GV)) {
598 if (ConstantMap.find(C) != ConstantMap.end()) {
599 rv = MCE.getConstantPoolEntryAddress(ConstantMap[C]);
601 std::cerr << "Constant: 0x" << std::hex << (intptr_t)C
602 << ", " << *V << " not found in ConstantMap!\n";
607 DEBUG(std::cerr << "Global addr: 0x" << std::hex << rv << "\n");
609 // The real target of the call is Addr = PC + (rv * 4)
610 // So undo that: give the instruction (Addr - PC) / 4
611 if (MI.getOpcode() == V9::CALL) {
612 int64_t CurrPC = MCE.getCurrentPCValue();
613 DEBUG(std::cerr << "rv addr: 0x" << std::hex << rv << "\n"
614 << "curr PC: 0x" << std::hex << CurrPC << "\n");
615 int64_t CallInstTarget = (rv - CurrPC) >> 2;
616 if (CallInstTarget >= (1<<29) || CallInstTarget <= -(1<<29)) {
617 DEBUG(std::cerr << "Making far call!\n");
618 // addresss is out of bounds for the 30-bit call,
619 // make an indirect jump-and-link
621 // this invalidates the instruction so that the call with an incorrect
622 // address will not be emitted
625 // The call fits into 30 bits, so just return the corrected address
628 DEBUG(std::cerr << "returning addr: 0x" << rv << "\n");
631 std::cerr << "ERROR: PC relative disp unhandled:" << MO << "\n";
634 } else if (MO.isPhysicalRegister() ||
635 MO.getType() == MachineOperand::MO_CCRegister)
637 // This is necessary because the Sparc backend doesn't actually lay out
638 // registers in the real fashion -- it skips those that it chooses not to
639 // allocate, i.e. those that are the FP, SP, etc.
640 unsigned fakeReg = MO.getAllocatedRegNum();
641 unsigned realRegByClass = getRealRegNum(fakeReg, MI);
642 DEBUG(std::cerr << MO << ": Reg[" << std::dec << fakeReg << "] => "
643 << realRegByClass << " (LLC: "
644 << TM.getRegInfo().getUnifiedRegName(fakeReg) << ")\n");
646 } else if (MO.isImmediate()) {
647 rv = MO.getImmedValue();
648 DEBUG(std::cerr << "immed: " << rv << "\n");
649 } else if (MO.isGlobalAddress()) {
650 DEBUG(std::cerr << "GlobalAddress: not PC-relative\n");
652 (intptr_t)getGlobalAddress(cast<GlobalValue>(MO.getVRegValue()),
653 MI, MO.isPCRelative());
654 } else if (MO.isMachineBasicBlock()) {
655 // Duplicate code of the above case for VirtualRegister, BasicBlock...
656 // It should really hit this case, but Sparc backend uses VRegs instead
657 DEBUG(std::cerr << "Saving reference to MBB\n");
658 const BasicBlock *BB = MO.getMachineBasicBlock()->getBasicBlock();
659 unsigned* CurrPC = (unsigned*)(intptr_t)MCE.getCurrentPCValue();
660 BBRefs.push_back(std::make_pair(BB, std::make_pair(CurrPC, &MI)));
661 } else if (MO.isExternalSymbol()) {
662 // Sparc backend doesn't generate this (yet...)
663 std::cerr << "ERROR: External symbol unhandled: " << MO << "\n";
665 } else if (MO.isFrameIndex()) {
666 // Sparc backend doesn't generate this (yet...)
667 int FrameIndex = MO.getFrameIndex();
668 std::cerr << "ERROR: Frame index unhandled.\n";
670 } else if (MO.isConstantPoolIndex()) {
671 // Sparc backend doesn't generate this (yet...)
672 std::cerr << "ERROR: Constant Pool index unhandled.\n";
675 std::cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
679 // Finally, deal with the various bitfield-extracting functions that
680 // are used in SPARC assembly. (Some of these make no sense in combination
681 // with some of the above; we'll trust that the instruction selector
682 // will not produce nonsense, and not check for valid combinations here.)
683 if (MO.opLoBits32()) { // %lo(val) == %lo() in Sparc ABI doc
685 } else if (MO.opHiBits32()) { // %lm(val) == %hi() in Sparc ABI doc
686 return (rv >> 10) & 0x03fffff;
687 } else if (MO.opLoBits64()) { // %hm(val) == %ulo() in Sparc ABI doc
688 return (rv >> 32) & 0x03ff;
689 } else if (MO.opHiBits64()) { // %hh(val) == %uhi() in Sparc ABI doc
691 } else { // (unadorned) val
696 unsigned SparcV9CodeEmitter::getValueBit(int64_t Val, unsigned bit) {
701 bool SparcV9CodeEmitter::runOnMachineFunction(MachineFunction &MF) {
702 MCE.startFunction(MF);
703 DEBUG(std::cerr << "Starting function " << MF.getFunction()->getName()
704 << ", address: " << "0x" << std::hex
705 << (long)MCE.getCurrentPCValue() << "\n");
707 // The Sparc backend does not use MachineConstantPool;
708 // instead, it has its own constant pool implementation.
709 // We create a new MachineConstantPool here to be compatible with the emitter.
710 MachineConstantPool MCP;
711 const hash_set<const Constant*> &pool = MF.getInfo()->getConstantPoolValues();
712 for (hash_set<const Constant*>::const_iterator I = pool.begin(),
713 E = pool.end(); I != E; ++I)
715 Constant *C = (Constant*)*I;
716 unsigned idx = MCP.getConstantPoolIndex(C);
717 DEBUG(std::cerr << "Constant[" << idx << "] = 0x" << (intptr_t)C << "\n");
718 ConstantMap[C] = idx;
720 MCE.emitConstantPool(&MCP);
722 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
724 MCE.finishFunction(MF);
726 DEBUG(std::cerr << "Finishing fn " << MF.getFunction()->getName() << "\n");
729 // Resolve branches to BasicBlocks for the entire function
730 for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
731 long Location = BBLocations[BBRefs[i].first];
732 unsigned *Ref = BBRefs[i].second.first;
733 MachineInstr *MI = BBRefs[i].second.second;
734 DEBUG(std::cerr << "Fixup @ " << std::hex << Ref << " to 0x" << Location
735 << " in instr: " << std::dec << *MI);
736 for (unsigned ii = 0, ee = MI->getNumOperands(); ii != ee; ++ii) {
737 MachineOperand &op = MI->getOperand(ii);
738 if (op.isPCRelativeDisp()) {
739 // the instruction's branch target is made such that it branches to
740 // PC + (branchTarget * 4), so undo that arithmetic here:
741 // Location is the target of the branch
742 // Ref is the location of the instruction, and hence the PC
743 int64_t branchTarget = (Location - (long)Ref) >> 2;
745 bool loBits32=false, hiBits32=false, loBits64=false, hiBits64=false;
746 if (op.opLoBits32()) { loBits32=true; }
747 if (op.opHiBits32()) { hiBits32=true; }
748 if (op.opLoBits64()) { loBits64=true; }
749 if (op.opHiBits64()) { hiBits64=true; }
750 MI->SetMachineOperandConst(ii, MachineOperand::MO_SignExtendedImmed,
752 if (loBits32) { MI->setOperandLo32(ii); }
753 else if (hiBits32) { MI->setOperandHi32(ii); }
754 else if (loBits64) { MI->setOperandLo64(ii); }
755 else if (hiBits64) { MI->setOperandHi64(ii); }
756 DEBUG(std::cerr << "Rewrote BB ref: ");
757 unsigned fixedInstr = SparcV9CodeEmitter::getBinaryCodeForInstr(*MI);
769 void SparcV9CodeEmitter::emitBasicBlock(MachineBasicBlock &MBB) {
770 currBB = MBB.getBasicBlock();
771 BBLocations[currBB] = MCE.getCurrentPCValue();
772 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I){
773 unsigned binCode = getBinaryCodeForInstr(**I);
774 if (binCode == (1 << 30)) {
775 // this is an invalid call: the addr is out of bounds. that means a code
776 // sequence has already been emitted, and this is a no-op
777 DEBUG(std::cerr << "Call supressed: already emitted far call.\n");
784 void* SparcV9CodeEmitter::getGlobalAddress(GlobalValue *V, MachineInstr &MI,
787 if (isPCRelative) { // must be a call, this is a major hack!
788 // Try looking up the function to see if it is already compiled!
789 if (void *Addr = (void*)(intptr_t)MCE.getGlobalValueAddress(V)) {
790 intptr_t CurByte = MCE.getCurrentPCValue();
791 // The real target of the call is Addr = PC + (target * 4)
792 // CurByte is the PC, Addr we just received
793 return (void*) (((long)Addr - (long)CurByte) >> 2);
795 if (Function *F = dyn_cast<Function>(V)) {
796 // Function has not yet been code generated!
797 TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(),
799 // Delayed resolution...
801 (void*)(intptr_t)TheJITResolver->getLazyResolver(cast<Function>(V));
803 } else if (Constant *C = ConstantPointerRef::get(V)) {
804 if (ConstantMap.find(C) != ConstantMap.end()) {
806 (intptr_t)MCE.getConstantPoolEntryAddress(ConstantMap[C]);
808 std::cerr << "Constant: 0x" << std::hex << &*C << std::dec
809 << ", " << *V << " not found in ConstantMap!\n";
813 std::cerr << "Unhandled global: " << *V << "\n";
818 return (void*)(intptr_t)MCE.getGlobalValueAddress(V);
822 #include "SparcV9CodeEmitter.inc"