1 //===-- SparcV8AsmPrinter.cpp - SparcV8 LLVM assembly writer --------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
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"
32 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
34 struct V8Printer : public MachineFunctionPass {
35 /// Output stream on which we're printing assembly code.
39 /// Target machine description which we query for reg. names, data
44 /// Name-mangler for global names.
48 V8Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
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().
54 typedef std::map<const Value *, unsigned> ValueMapTy;
55 ValueMapTy NumberForBB;
57 /// Cache of mangled name for current function. This is
58 /// recalculated at the beginning of each call to
59 /// runOnMachineFunction().
61 std::string CurrentFnName;
63 virtual const char *getPassName() const {
64 return "SparcV8 Assembly Printer";
67 void emitConstantValueOnly(const Constant *CV);
68 void emitGlobalConstant(const Constant *CV);
69 void printConstantPool(MachineConstantPool *MCP);
70 void printOperand(const MachineOperand &MI);
71 void printMachineInstruction(const MachineInstr *MI);
72 bool runOnMachineFunction(MachineFunction &F);
73 bool doInitialization(Module &M);
74 bool doFinalization(Module &M);
76 } // end of anonymous namespace
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.
83 FunctionPass *llvm::createSparcV8CodePrinterPass (std::ostream &o,
85 return new V8Printer(o, tm);
88 /// toOctal - Convert the low order bits of X into an octal digit.
90 static inline char toOctal(int X) {
94 /// getAsCString - Return the specified array as a C compatible
95 /// string, only if the predicate isStringCompatible is true.
97 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
98 assert(CVA->isString() && "Array is not string compatible!");
101 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
102 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
106 } else if (C == '\\') {
108 } else if (isprint(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;
119 O << toOctal(C >> 6);
120 O << toOctal(C >> 3);
121 O << toOctal(C >> 0);
129 // Print out the specified constant, without a storage class. Only the
130 // constants valid in constant expressions can occur here.
131 void V8Printer::emitConstantValueOnly(const Constant *CV) {
132 if (CV->isNullValue())
134 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
135 assert(CB == ConstantBool::True);
137 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
138 if (((CI->getValue() << 32) >> 32) == CI->getValue())
141 O << (unsigned long long)CI->getValue();
142 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
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)) {
157 emitConstantValueOnly(ptrVal);
158 O << ") + " << Offset;
160 emitConstantValueOnly(ptrVal);
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();
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");
183 emitConstantValueOnly(Op);
187 case Instruction::Add:
189 emitConstantValueOnly(CE->getOperand(0));
191 emitConstantValueOnly(CE->getOperand(1));
195 assert(0 && "Unsupported operator!");
198 assert(0 && "Unknown constant value!");
202 // Print a constant value or values, with the appropriate storage class as a
204 void V8Printer::emitGlobalConstant(const Constant *CV) {
205 const TargetData &TD = TM.getTargetData();
207 if (CV->isNullValue()) {
208 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
210 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
211 if (CVA->isString()) {
213 printAsCString(O, CVA);
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()));
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());
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;
236 // Now print the actual field value
237 emitGlobalConstant(field);
239 // Insert the field padding unless it's zero bytes...
241 O << "\t.zero\t " << padSize << "\n";
243 assert(sizeSoFar == cvsLayout->StructSize &&
244 "Layout of constant struct may be incorrect!");
246 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
247 // FP Constants are printed as integer constants to avoid losing
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
258 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
261 case Type::DoubleTyID: {
262 union DU { // Abide by C TBAA rules
267 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
273 const Type *type = CV->getType();
275 switch (type->getPrimitiveID()) {
276 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
279 case Type::UShortTyID: case Type::ShortTyID:
282 case Type::FloatTyID: case Type::PointerTyID:
283 case Type::UIntTyID: case Type::IntTyID:
286 case Type::DoubleTyID:
287 case Type::ULongTyID: case Type::LongTyID:
291 assert (0 && "Can't handle printing this type of thing");
295 emitConstantValueOnly(CV);
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.
304 void V8Printer::printConstantPool(MachineConstantPool *MCP) {
305 const std::vector<Constant*> &CP = MCP->getConstants();
306 const TargetData &TD = TM.getTargetData();
308 if (CP.empty()) return;
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())
314 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
316 emitGlobalConstant(CP[i]);
320 /// runOnMachineFunction - This uses the printMachineInstruction()
321 /// method to print assembly for each instruction.
323 bool 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;
329 // What's my mangled name?
330 CurrentFnName = Mang->getValueName(MF.getFunction());
332 // Print out constants referenced by the function
333 printConstantPool(MF.getConstantPool());
335 // Print out labels for the function.
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";
342 // Number each basic block so that we can consistently refer to them
343 // in PC-relative references.
345 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
347 NumberForBB[I->getBasicBlock()] = BBNumber++;
350 // Print out code for the function.
351 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
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();
358 // Print the assembly for the instruction.
360 printMachineInstruction(II);
364 // We didn't modify anything.
368 void 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() << ">";
377 case MachineOperand::MO_MachineRegister:
378 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
379 O << "%" << RI.get(MO.getReg()).Name;
381 O << "%reg" << MO.getReg();
384 case MachineOperand::MO_SignExtendedImmed:
385 case MachineOperand::MO_UnextendedImmed:
386 O << (int)MO.getImmedValue();
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();
395 case MachineOperand::MO_GlobalAddress:
396 O << Mang->getValueName(MO.getGlobal());
398 case MachineOperand::MO_ExternalSymbol:
399 O << MO.getSymbolName();
402 O << "<unknown operand type>"; return;
406 /// printMachineInstruction -- Print out a single SparcV8 LLVM instruction
407 /// MI in GAS syntax to the current output stream.
409 void V8Printer::printMachineInstruction(const MachineInstr *MI) {
410 unsigned Opcode = MI->getOpcode();
411 const TargetInstrInfo &TII = TM.getInstrInfo();
412 const TargetInstrDescriptor &Desc = TII.get(Opcode);
413 O << Desc.Name << " ";
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))
438 bool V8Printer::doInitialization(Module &M) {
439 Mang = new Mangler(M);
440 return false; // success
443 // SwitchSection - Switch to the specified section of the executable if we are
444 // not already in it!
446 static 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";
455 bool V8Printer::doFinalization(Module &M) {
456 const TargetData &TD = TM.getTargetData();
457 std::string CurSection;
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
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());
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";
475 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
476 << "," << (unsigned)TD.getTypeAlignment(C->getType());
478 WriteAsOperand(O, I, true, true, &M);
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";
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";
497 case GlobalValue::InternalLinkage:
498 if (C->isNullValue())
499 SwitchSection(O, CurSection, ".bss");
501 SwitchSection(O, CurSection, ".data");
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);
511 WriteAsOperand(O, C, false, false, &M);
513 emitGlobalConstant(C);
518 return false; // success