blob: e9752842a2e276753667d2229c6b06db53e22bb0 [file] [log] [blame]
Brian Gaeke4acfd032004-03-04 06:00:41 +00001//===-- SparcV8AsmPrinter.cpp - SparcV8 LLVM assembly writer --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a printer that converts from our internal representation
11// of machine-dependent LLVM code to GAS-format Sparc V8 assembly language.
12//
13//===----------------------------------------------------------------------===//
14
15#include "SparcV8.h"
16#include "SparcV8InstrInfo.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Module.h"
20#include "llvm/Assembly/Writer.h"
21#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineConstantPool.h"
23#include "llvm/CodeGen/MachineInstr.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Support/Mangler.h"
26#include "Support/Statistic.h"
27#include "Support/StringExtras.h"
28#include "Support/CommandLine.h"
29using namespace llvm;
30
31namespace {
32 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
33
34 struct V8Printer : public MachineFunctionPass {
35 /// Output stream on which we're printing assembly code.
36 ///
37 std::ostream &O;
38
39 /// Target machine description which we query for reg. names, data
40 /// layout, etc.
41 ///
42 TargetMachine &TM;
43
44 /// Name-mangler for global names.
45 ///
46 Mangler *Mang;
47
48 V8Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
49
50 /// We name each basic block in a Function with a unique number, so
51 /// that we can consistently refer to them later. This is cleared
52 /// at the beginning of each call to runOnMachineFunction().
53 ///
54 typedef std::map<const Value *, unsigned> ValueMapTy;
55 ValueMapTy NumberForBB;
56
57 /// Cache of mangled name for current function. This is
58 /// recalculated at the beginning of each call to
59 /// runOnMachineFunction().
60 ///
61 std::string CurrentFnName;
62
63 virtual const char *getPassName() const {
64 return "SparcV8 Assembly Printer";
65 }
66
67 void emitConstantValueOnly(const Constant *CV);
68 void emitGlobalConstant(const Constant *CV);
69 void printConstantPool(MachineConstantPool *MCP);
Brian Gaeke62aa28a2004-03-05 08:39:09 +000070 void printOperand(const MachineOperand &MI);
Brian Gaeke4acfd032004-03-04 06:00:41 +000071 void printMachineInstruction(const MachineInstr *MI);
72 bool runOnMachineFunction(MachineFunction &F);
73 bool doInitialization(Module &M);
74 bool doFinalization(Module &M);
75 };
76} // end of anonymous namespace
77
78/// createSparcV8CodePrinterPass - Returns a pass that prints the SparcV8
79/// assembly code for a MachineFunction to the given output stream,
80/// using the given target machine description. This should work
81/// regardless of whether the function is in SSA form.
82///
83FunctionPass *llvm::createSparcV8CodePrinterPass (std::ostream &o,
84 TargetMachine &tm) {
85 return new V8Printer(o, tm);
86}
87
88/// toOctal - Convert the low order bits of X into an octal digit.
89///
90static inline char toOctal(int X) {
91 return (X&7)+'0';
92}
93
94/// getAsCString - Return the specified array as a C compatible
95/// string, only if the predicate isStringCompatible is true.
96///
97static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
98 assert(CVA->isString() && "Array is not string compatible!");
99
100 O << "\"";
101 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
102 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
103
104 if (C == '"') {
105 O << "\\\"";
106 } else if (C == '\\') {
107 O << "\\\\";
108 } else if (isprint(C)) {
109 O << C;
110 } else {
111 switch(C) {
112 case '\b': O << "\\b"; break;
113 case '\f': O << "\\f"; break;
114 case '\n': O << "\\n"; break;
115 case '\r': O << "\\r"; break;
116 case '\t': O << "\\t"; break;
117 default:
118 O << '\\';
119 O << toOctal(C >> 6);
120 O << toOctal(C >> 3);
121 O << toOctal(C >> 0);
122 break;
123 }
124 }
125 }
126 O << "\"";
127}
128
129// Print out the specified constant, without a storage class. Only the
130// constants valid in constant expressions can occur here.
131void V8Printer::emitConstantValueOnly(const Constant *CV) {
132 if (CV->isNullValue())
133 O << "0";
134 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
135 assert(CB == ConstantBool::True);
136 O << "1";
137 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
138 if (((CI->getValue() << 32) >> 32) == CI->getValue())
139 O << CI->getValue();
140 else
141 O << (unsigned long long)CI->getValue();
142 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
143 O << CI->getValue();
144 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
145 // This is a constant address for a global variable or function. Use the
146 // name of the variable or function as the address value.
147 O << Mang->getValueName(CPR->getValue());
148 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
149 const TargetData &TD = TM.getTargetData();
150 switch(CE->getOpcode()) {
151 case Instruction::GetElementPtr: {
152 // generate a symbolic expression for the byte address
153 const Constant *ptrVal = CE->getOperand(0);
154 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
155 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
156 O << "(";
157 emitConstantValueOnly(ptrVal);
158 O << ") + " << Offset;
159 } else {
160 emitConstantValueOnly(ptrVal);
161 }
162 break;
163 }
164 case Instruction::Cast: {
165 // Support only non-converting or widening casts for now, that is, ones
166 // that do not involve a change in value. This assertion is really gross,
167 // and may not even be a complete check.
168 Constant *Op = CE->getOperand(0);
169 const Type *OpTy = Op->getType(), *Ty = CE->getType();
170
171 // Pointers on ILP32 machines can be losslessly converted back and
172 // forth into 32-bit or wider integers, regardless of signedness.
173 assert(((isa<PointerType>(OpTy)
174 && (Ty == Type::LongTy || Ty == Type::ULongTy
175 || Ty == Type::IntTy || Ty == Type::UIntTy))
176 || (isa<PointerType>(Ty)
177 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
178 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
179 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
180 && OpTy->isLosslesslyConvertibleTo(Ty))))
181 && "FIXME: Don't yet support this kind of constant cast expr");
182 O << "(";
183 emitConstantValueOnly(Op);
184 O << ")";
185 break;
186 }
187 case Instruction::Add:
188 O << "(";
189 emitConstantValueOnly(CE->getOperand(0));
190 O << ") + (";
191 emitConstantValueOnly(CE->getOperand(1));
192 O << ")";
193 break;
194 default:
195 assert(0 && "Unsupported operator!");
196 }
197 } else {
198 assert(0 && "Unknown constant value!");
199 }
200}
201
202// Print a constant value or values, with the appropriate storage class as a
203// prefix.
204void V8Printer::emitGlobalConstant(const Constant *CV) {
205 const TargetData &TD = TM.getTargetData();
206
207 if (CV->isNullValue()) {
208 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
209 return;
210 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
211 if (CVA->isString()) {
212 O << "\t.ascii\t";
213 printAsCString(O, CVA);
214 O << "\n";
215 } else { // Not a string. Print the values in successive locations
216 const std::vector<Use> &constValues = CVA->getValues();
217 for (unsigned i=0; i < constValues.size(); i++)
218 emitGlobalConstant(cast<Constant>(constValues[i].get()));
219 }
220 return;
221 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
222 // Print the fields in successive locations. Pad to align if needed!
223 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
224 const std::vector<Use>& constValues = CVS->getValues();
225 unsigned sizeSoFar = 0;
226 for (unsigned i=0, N = constValues.size(); i < N; i++) {
227 const Constant* field = cast<Constant>(constValues[i].get());
228
229 // Check if padding is needed and insert one or more 0s.
230 unsigned fieldSize = TD.getTypeSize(field->getType());
231 unsigned padSize = ((i == N-1? cvsLayout->StructSize
232 : cvsLayout->MemberOffsets[i+1])
233 - cvsLayout->MemberOffsets[i]) - fieldSize;
234 sizeSoFar += fieldSize + padSize;
235
236 // Now print the actual field value
237 emitGlobalConstant(field);
238
239 // Insert the field padding unless it's zero bytes...
240 if (padSize)
241 O << "\t.zero\t " << padSize << "\n";
242 }
243 assert(sizeSoFar == cvsLayout->StructSize &&
244 "Layout of constant struct may be incorrect!");
245 return;
246 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
247 // FP Constants are printed as integer constants to avoid losing
248 // precision...
249 double Val = CFP->getValue();
250 switch (CFP->getType()->getPrimitiveID()) {
251 default: assert(0 && "Unknown floating point type!");
252 case Type::FloatTyID: {
253 union FU { // Abide by C TBAA rules
254 float FVal;
255 unsigned UVal;
256 } U;
257 U.FVal = Val;
258 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
259 return;
260 }
261 case Type::DoubleTyID: {
262 union DU { // Abide by C TBAA rules
263 double FVal;
264 uint64_t UVal;
265 } U;
266 U.FVal = Val;
267 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
268 return;
269 }
270 }
271 }
272
273 const Type *type = CV->getType();
274 O << "\t";
275 switch (type->getPrimitiveID()) {
276 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
277 O << ".byte";
278 break;
279 case Type::UShortTyID: case Type::ShortTyID:
280 O << ".word";
281 break;
282 case Type::FloatTyID: case Type::PointerTyID:
283 case Type::UIntTyID: case Type::IntTyID:
284 O << ".long";
285 break;
286 case Type::DoubleTyID:
287 case Type::ULongTyID: case Type::LongTyID:
288 O << ".quad";
289 break;
290 default:
291 assert (0 && "Can't handle printing this type of thing");
292 break;
293 }
294 O << "\t";
295 emitConstantValueOnly(CV);
296 O << "\n";
297}
298
299/// printConstantPool - Print to the current output stream assembly
300/// representations of the constants in the constant pool MCP. This is
301/// used to print out constants which have been "spilled to memory" by
302/// the code generator.
303///
304void V8Printer::printConstantPool(MachineConstantPool *MCP) {
305 const std::vector<Constant*> &CP = MCP->getConstants();
306 const TargetData &TD = TM.getTargetData();
307
308 if (CP.empty()) return;
309
310 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
311 O << "\t.section .rodata\n";
312 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
313 << "\n";
314 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
315 << *CP[i] << "\n";
316 emitGlobalConstant(CP[i]);
317 }
318}
319
320/// runOnMachineFunction - This uses the printMachineInstruction()
321/// method to print assembly for each instruction.
322///
323bool V8Printer::runOnMachineFunction(MachineFunction &MF) {
324 // BBNumber is used here so that a given Printer will never give two
325 // BBs the same name. (If you have a better way, please let me know!)
326 static unsigned BBNumber = 0;
327
328 O << "\n\n";
329 // What's my mangled name?
330 CurrentFnName = Mang->getValueName(MF.getFunction());
331
332 // Print out constants referenced by the function
333 printConstantPool(MF.getConstantPool());
334
335 // Print out labels for the function.
336 O << "\t.text\n";
337 O << "\t.align 16\n";
338 O << "\t.globl\t" << CurrentFnName << "\n";
339 O << "\t.type\t" << CurrentFnName << ", @function\n";
340 O << CurrentFnName << ":\n";
341
342 // Number each basic block so that we can consistently refer to them
343 // in PC-relative references.
344 NumberForBB.clear();
345 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
346 I != E; ++I) {
347 NumberForBB[I->getBasicBlock()] = BBNumber++;
348 }
349
350 // Print out code for the function.
351 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
352 I != E; ++I) {
353 // Print a label for the basic block.
354 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
355 << I->getBasicBlock()->getName() << "\n";
356 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
357 II != E; ++II) {
358 // Print the assembly for the instruction.
359 O << "\t";
360 printMachineInstruction(II);
361 }
362 }
363
364 // We didn't modify anything.
365 return false;
366}
367
Brian Gaeke62aa28a2004-03-05 08:39:09 +0000368void V8Printer::printOperand(const MachineOperand &MO) {
369 const MRegisterInfo &RI = *TM.getRegisterInfo();
370 switch (MO.getType()) {
371 case MachineOperand::MO_VirtualRegister:
372 if (Value *V = MO.getVRegValueOrNull()) {
373 O << "<" << V->getName() << ">";
374 return;
375 }
376 // FALLTHROUGH
377 case MachineOperand::MO_MachineRegister:
378 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
379 O << "%" << RI.get(MO.getReg()).Name;
380 else
381 O << "%reg" << MO.getReg();
382 return;
383
384 case MachineOperand::MO_SignExtendedImmed:
385 case MachineOperand::MO_UnextendedImmed:
386 O << (int)MO.getImmedValue();
387 return;
388 case MachineOperand::MO_PCRelativeDisp: {
389 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
390 assert (i != NumberForBB.end()
391 && "Could not find a BB in the NumberForBB map!");
392 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
393 return;
394 }
395 case MachineOperand::MO_GlobalAddress:
396 O << Mang->getValueName(MO.getGlobal());
397 return;
398 case MachineOperand::MO_ExternalSymbol:
399 O << MO.getSymbolName();
400 return;
401 default:
402 O << "<unknown operand type>"; return;
403 }
404}
405
Brian Gaeke4acfd032004-03-04 06:00:41 +0000406/// printMachineInstruction -- Print out a single SparcV8 LLVM instruction
407/// MI in GAS syntax to the current output stream.
408///
409void V8Printer::printMachineInstruction(const MachineInstr *MI) {
410 unsigned Opcode = MI->getOpcode();
411 const TargetInstrInfo &TII = TM.getInstrInfo();
412 const TargetInstrDescriptor &Desc = TII.get(Opcode);
Brian Gaeke62aa28a2004-03-05 08:39:09 +0000413 O << Desc.Name << " ";
414
415 // print non-immediate, non-register-def operands
416 // then print immediate operands
417 // then print register-def operands.
418 std::vector<MachineOperand> print_order;
419 for (unsigned i = 0; i < MI->getNumOperands (); ++i)
420 if (!(MI->getOperand (i).isImmediate ()
421 || (MI->getOperand (i).isRegister ()
422 && MI->getOperand (i).isDef ())))
423 print_order.push_back (MI->getOperand (i));
424 for (unsigned i = 0; i < MI->getNumOperands (); ++i)
425 if (MI->getOperand (i).isImmediate ())
426 print_order.push_back (MI->getOperand (i));
427 for (unsigned i = 0; i < MI->getNumOperands (); ++i)
428 if (MI->getOperand (i).isRegister () && MI->getOperand (i).isDef ())
429 print_order.push_back (MI->getOperand (i));
430 for (unsigned i = 0, e = print_order.size (); i != e; ++i) {
431 printOperand (print_order[i]);
432 if (i != (print_order.size () - 1))
433 O << ", ";
434 }
435 O << "\n";
Brian Gaeke4acfd032004-03-04 06:00:41 +0000436}
437
438bool V8Printer::doInitialization(Module &M) {
439 Mang = new Mangler(M);
440 return false; // success
441}
442
443// SwitchSection - Switch to the specified section of the executable if we are
444// not already in it!
445//
446static void SwitchSection(std::ostream &OS, std::string &CurSection,
447 const char *NewSection) {
448 if (CurSection != NewSection) {
449 CurSection = NewSection;
450 if (!CurSection.empty())
451 OS << "\t" << NewSection << "\n";
452 }
453}
454
455bool V8Printer::doFinalization(Module &M) {
456 const TargetData &TD = TM.getTargetData();
457 std::string CurSection;
458
459 // Print out module-level global variables here.
460 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
461 if (I->hasInitializer()) { // External global require no code
462 O << "\n\n";
463 std::string name = Mang->getValueName(I);
464 Constant *C = I->getInitializer();
465 unsigned Size = TD.getTypeSize(C->getType());
466 unsigned Align = TD.getTypeAlignment(C->getType());
467
468 if (C->isNullValue() &&
469 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
470 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
471 SwitchSection(O, CurSection, ".data");
472 if (I->hasInternalLinkage())
473 O << "\t.local " << name << "\n";
474
475 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
476 << "," << (unsigned)TD.getTypeAlignment(C->getType());
477 O << "\t\t# ";
478 WriteAsOperand(O, I, true, true, &M);
479 O << "\n";
480 } else {
481 switch (I->getLinkage()) {
482 case GlobalValue::LinkOnceLinkage:
483 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
484 // Nonnull linkonce -> weak
485 O << "\t.weak " << name << "\n";
486 SwitchSection(O, CurSection, "");
487 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
488 break;
489
490 case GlobalValue::AppendingLinkage:
491 // FIXME: appending linkage variables should go into a section of
492 // their name or something. For now, just emit them as external.
493 case GlobalValue::ExternalLinkage:
494 // If external or appending, declare as a global symbol
495 O << "\t.globl " << name << "\n";
496 // FALL THROUGH
497 case GlobalValue::InternalLinkage:
498 if (C->isNullValue())
499 SwitchSection(O, CurSection, ".bss");
500 else
501 SwitchSection(O, CurSection, ".data");
502 break;
503 }
504
505 O << "\t.align " << Align << "\n";
506 O << "\t.type " << name << ",@object\n";
507 O << "\t.size " << name << "," << Size << "\n";
508 O << name << ":\t\t\t\t# ";
509 WriteAsOperand(O, I, true, true, &M);
510 O << " = ";
511 WriteAsOperand(O, C, false, false, &M);
512 O << "\n";
513 emitGlobalConstant(C);
514 }
515 }
516
517 delete Mang;
518 return false; // success
519}