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"
33 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
35 struct V8Printer : public MachineFunctionPass {
36 /// Output stream on which we're printing assembly code.
40 /// Target machine description which we query for reg. names, data
45 /// Name-mangler for global names.
49 V8Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
51 /// We name each basic block in a Function with a unique number, so
52 /// that we can consistently refer to them later. This is cleared
53 /// at the beginning of each call to runOnMachineFunction().
55 typedef std::map<const Value *, unsigned> ValueMapTy;
56 ValueMapTy NumberForBB;
58 /// Cache of mangled name for current function. This is
59 /// recalculated at the beginning of each call to
60 /// runOnMachineFunction().
62 std::string CurrentFnName;
64 virtual const char *getPassName() const {
65 return "SparcV8 Assembly Printer";
68 void emitConstantValueOnly(const Constant *CV);
69 void emitGlobalConstant(const Constant *CV);
70 void printConstantPool(MachineConstantPool *MCP);
71 void printOperand(const MachineOperand &MI);
72 void printMachineInstruction(const MachineInstr *MI);
73 bool runOnMachineFunction(MachineFunction &F);
74 bool doInitialization(Module &M);
75 bool doFinalization(Module &M);
77 } // end of anonymous namespace
79 /// createSparcV8CodePrinterPass - Returns a pass that prints the SparcV8
80 /// assembly code for a MachineFunction to the given output stream,
81 /// using the given target machine description. This should work
82 /// regardless of whether the function is in SSA form.
84 FunctionPass *llvm::createSparcV8CodePrinterPass (std::ostream &o,
86 return new V8Printer(o, tm);
89 /// toOctal - Convert the low order bits of X into an octal digit.
91 static inline char toOctal(int X) {
95 /// getAsCString - Return the specified array as a C compatible
96 /// string, only if the predicate isStringCompatible is true.
98 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
99 assert(CVA->isString() && "Array is not string compatible!");
102 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
103 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
107 } else if (C == '\\') {
109 } else if (isprint(C)) {
113 case '\b': O << "\\b"; break;
114 case '\f': O << "\\f"; break;
115 case '\n': O << "\\n"; break;
116 case '\r': O << "\\r"; break;
117 case '\t': O << "\\t"; break;
120 O << toOctal(C >> 6);
121 O << toOctal(C >> 3);
122 O << toOctal(C >> 0);
130 // Print out the specified constant, without a storage class. Only the
131 // constants valid in constant expressions can occur here.
132 void V8Printer::emitConstantValueOnly(const Constant *CV) {
133 if (CV->isNullValue())
135 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
136 assert(CB == ConstantBool::True);
138 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
139 if (((CI->getValue() << 32) >> 32) == CI->getValue())
142 O << (unsigned long long)CI->getValue();
143 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
145 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
146 // This is a constant address for a global variable or function. Use the
147 // name of the variable or function as the address value.
148 O << Mang->getValueName(CPR->getValue());
149 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
150 const TargetData &TD = TM.getTargetData();
151 switch(CE->getOpcode()) {
152 case Instruction::GetElementPtr: {
153 // generate a symbolic expression for the byte address
154 const Constant *ptrVal = CE->getOperand(0);
155 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
156 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
158 emitConstantValueOnly(ptrVal);
159 O << ") + " << Offset;
161 emitConstantValueOnly(ptrVal);
165 case Instruction::Cast: {
166 // Support only non-converting or widening casts for now, that is, ones
167 // that do not involve a change in value. This assertion is really gross,
168 // and may not even be a complete check.
169 Constant *Op = CE->getOperand(0);
170 const Type *OpTy = Op->getType(), *Ty = CE->getType();
172 // Pointers on ILP32 machines can be losslessly converted back and
173 // forth into 32-bit or wider integers, regardless of signedness.
174 assert(((isa<PointerType>(OpTy)
175 && (Ty == Type::LongTy || Ty == Type::ULongTy
176 || Ty == Type::IntTy || Ty == Type::UIntTy))
177 || (isa<PointerType>(Ty)
178 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
179 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
180 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
181 && OpTy->isLosslesslyConvertibleTo(Ty))))
182 && "FIXME: Don't yet support this kind of constant cast expr");
184 emitConstantValueOnly(Op);
188 case Instruction::Add:
190 emitConstantValueOnly(CE->getOperand(0));
192 emitConstantValueOnly(CE->getOperand(1));
196 assert(0 && "Unsupported operator!");
199 assert(0 && "Unknown constant value!");
203 // Print a constant value or values, with the appropriate storage class as a
205 void V8Printer::emitGlobalConstant(const Constant *CV) {
206 const TargetData &TD = TM.getTargetData();
208 if (CV->isNullValue()) {
209 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
211 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
212 if (CVA->isString()) {
214 printAsCString(O, CVA);
216 } else { // Not a string. Print the values in successive locations
217 const std::vector<Use> &constValues = CVA->getValues();
218 for (unsigned i=0; i < constValues.size(); i++)
219 emitGlobalConstant(cast<Constant>(constValues[i].get()));
222 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
223 // Print the fields in successive locations. Pad to align if needed!
224 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
225 const std::vector<Use>& constValues = CVS->getValues();
226 unsigned sizeSoFar = 0;
227 for (unsigned i=0, N = constValues.size(); i < N; i++) {
228 const Constant* field = cast<Constant>(constValues[i].get());
230 // Check if padding is needed and insert one or more 0s.
231 unsigned fieldSize = TD.getTypeSize(field->getType());
232 unsigned padSize = ((i == N-1? cvsLayout->StructSize
233 : cvsLayout->MemberOffsets[i+1])
234 - cvsLayout->MemberOffsets[i]) - fieldSize;
235 sizeSoFar += fieldSize + padSize;
237 // Now print the actual field value
238 emitGlobalConstant(field);
240 // Insert the field padding unless it's zero bytes...
242 O << "\t.zero\t " << padSize << "\n";
244 assert(sizeSoFar == cvsLayout->StructSize &&
245 "Layout of constant struct may be incorrect!");
247 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
248 // FP Constants are printed as integer constants to avoid losing
250 double Val = CFP->getValue();
251 switch (CFP->getType()->getPrimitiveID()) {
252 default: assert(0 && "Unknown floating point type!");
253 case Type::FloatTyID: {
254 union FU { // Abide by C TBAA rules
259 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
262 case Type::DoubleTyID: {
263 union DU { // Abide by C TBAA rules
268 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
274 const Type *type = CV->getType();
276 switch (type->getPrimitiveID()) {
277 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
280 case Type::UShortTyID: case Type::ShortTyID:
283 case Type::FloatTyID: case Type::PointerTyID:
284 case Type::UIntTyID: case Type::IntTyID:
287 case Type::DoubleTyID:
288 case Type::ULongTyID: case Type::LongTyID:
292 assert (0 && "Can't handle printing this type of thing");
296 emitConstantValueOnly(CV);
300 /// printConstantPool - Print to the current output stream assembly
301 /// representations of the constants in the constant pool MCP. This is
302 /// used to print out constants which have been "spilled to memory" by
303 /// the code generator.
305 void V8Printer::printConstantPool(MachineConstantPool *MCP) {
306 const std::vector<Constant*> &CP = MCP->getConstants();
307 const TargetData &TD = TM.getTargetData();
309 if (CP.empty()) return;
311 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
312 O << "\t.section .rodata\n";
313 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
315 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
317 emitGlobalConstant(CP[i]);
321 /// runOnMachineFunction - This uses the printMachineInstruction()
322 /// method to print assembly for each instruction.
324 bool V8Printer::runOnMachineFunction(MachineFunction &MF) {
325 // BBNumber is used here so that a given Printer will never give two
326 // BBs the same name. (If you have a better way, please let me know!)
327 static unsigned BBNumber = 0;
330 // What's my mangled name?
331 CurrentFnName = Mang->getValueName(MF.getFunction());
333 // Print out constants referenced by the function
334 printConstantPool(MF.getConstantPool());
336 // Print out labels for the function.
338 O << "\t.align 16\n";
339 O << "\t.globl\t" << CurrentFnName << "\n";
340 O << "\t.type\t" << CurrentFnName << ", @function\n";
341 O << CurrentFnName << ":\n";
343 // Number each basic block so that we can consistently refer to them
344 // in PC-relative references.
346 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
348 NumberForBB[I->getBasicBlock()] = BBNumber++;
351 // Print out code for the function.
352 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
354 // Print a label for the basic block.
355 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
356 << I->getBasicBlock()->getName() << "\n";
357 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
359 // Print the assembly for the instruction.
361 printMachineInstruction(II);
365 // We didn't modify anything.
370 std::string LowercaseString (const std::string &S) {
371 std::string result (S);
372 for (unsigned i = 0; i < S.length(); ++i)
373 if (isupper (result[i]))
374 result[i] = tolower(result[i]);
378 void V8Printer::printOperand(const MachineOperand &MO) {
379 const MRegisterInfo &RI = *TM.getRegisterInfo();
380 switch (MO.getType()) {
381 case MachineOperand::MO_VirtualRegister:
382 if (Value *V = MO.getVRegValueOrNull()) {
383 O << "<" << V->getName() << ">";
387 case MachineOperand::MO_MachineRegister:
388 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
389 O << "%" << LowercaseString (RI.get(MO.getReg()).Name);
391 O << "%reg" << MO.getReg();
394 case MachineOperand::MO_SignExtendedImmed:
395 case MachineOperand::MO_UnextendedImmed:
396 O << (int)MO.getImmedValue();
398 case MachineOperand::MO_PCRelativeDisp: {
399 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
400 assert (i != NumberForBB.end()
401 && "Could not find a BB in the NumberForBB map!");
402 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
405 case MachineOperand::MO_GlobalAddress:
406 O << Mang->getValueName(MO.getGlobal());
408 case MachineOperand::MO_ExternalSymbol:
409 O << MO.getSymbolName();
412 O << "<unknown operand type>"; return;
416 /// printMachineInstruction -- Print out a single SparcV8 LLVM instruction
417 /// MI in GAS syntax to the current output stream.
419 void V8Printer::printMachineInstruction(const MachineInstr *MI) {
420 unsigned Opcode = MI->getOpcode();
421 const TargetInstrInfo &TII = TM.getInstrInfo();
422 const TargetInstrDescriptor &Desc = TII.get(Opcode);
423 O << Desc.Name << " ";
425 // print non-immediate, non-register-def operands
426 // then print immediate operands
427 // then print register-def operands.
428 std::vector<MachineOperand> print_order;
429 for (unsigned i = 0; i < MI->getNumOperands (); ++i)
430 if (!(MI->getOperand (i).isImmediate ()
431 || (MI->getOperand (i).isRegister ()
432 && MI->getOperand (i).isDef ())))
433 print_order.push_back (MI->getOperand (i));
434 for (unsigned i = 0; i < MI->getNumOperands (); ++i)
435 if (MI->getOperand (i).isImmediate ())
436 print_order.push_back (MI->getOperand (i));
437 for (unsigned i = 0; i < MI->getNumOperands (); ++i)
438 if (MI->getOperand (i).isRegister () && MI->getOperand (i).isDef ())
439 print_order.push_back (MI->getOperand (i));
440 for (unsigned i = 0, e = print_order.size (); i != e; ++i) {
441 printOperand (print_order[i]);
442 if (i != (print_order.size () - 1))
448 bool V8Printer::doInitialization(Module &M) {
449 Mang = new Mangler(M);
450 return false; // success
453 // SwitchSection - Switch to the specified section of the executable if we are
454 // not already in it!
456 static void SwitchSection(std::ostream &OS, std::string &CurSection,
457 const char *NewSection) {
458 if (CurSection != NewSection) {
459 CurSection = NewSection;
460 if (!CurSection.empty())
461 OS << "\t" << NewSection << "\n";
465 bool V8Printer::doFinalization(Module &M) {
466 const TargetData &TD = TM.getTargetData();
467 std::string CurSection;
469 // Print out module-level global variables here.
470 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
471 if (I->hasInitializer()) { // External global require no code
473 std::string name = Mang->getValueName(I);
474 Constant *C = I->getInitializer();
475 unsigned Size = TD.getTypeSize(C->getType());
476 unsigned Align = TD.getTypeAlignment(C->getType());
478 if (C->isNullValue() &&
479 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
480 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
481 SwitchSection(O, CurSection, ".data");
482 if (I->hasInternalLinkage())
483 O << "\t.local " << name << "\n";
485 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
486 << "," << (unsigned)TD.getTypeAlignment(C->getType());
488 WriteAsOperand(O, I, true, true, &M);
491 switch (I->getLinkage()) {
492 case GlobalValue::LinkOnceLinkage:
493 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
494 // Nonnull linkonce -> weak
495 O << "\t.weak " << name << "\n";
496 SwitchSection(O, CurSection, "");
497 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
500 case GlobalValue::AppendingLinkage:
501 // FIXME: appending linkage variables should go into a section of
502 // their name or something. For now, just emit them as external.
503 case GlobalValue::ExternalLinkage:
504 // If external or appending, declare as a global symbol
505 O << "\t.globl " << name << "\n";
507 case GlobalValue::InternalLinkage:
508 if (C->isNullValue())
509 SwitchSection(O, CurSection, ".bss");
511 SwitchSection(O, CurSection, ".data");
515 O << "\t.align " << Align << "\n";
516 O << "\t.type " << name << ",@object\n";
517 O << "\t.size " << name << "," << Size << "\n";
518 O << name << ":\t\t\t\t# ";
519 WriteAsOperand(O, I, true, true, &M);
521 WriteAsOperand(O, C, false, false, &M);
523 emitGlobalConstant(C);
528 return false; // success