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 "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/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 MachineInstr *MI, int opNum);
72 void printBaseOffsetPair (const MachineInstr *MI, int i, bool brackets=true);
73 void printMachineInstruction(const MachineInstr *MI);
74 bool runOnMachineFunction(MachineFunction &F);
75 bool doInitialization(Module &M);
76 bool doFinalization(Module &M);
78 } // end of anonymous namespace
80 /// createSparcV8CodePrinterPass - Returns a pass that prints the SparcV8
81 /// assembly code for a MachineFunction to the given output stream,
82 /// using the given target machine description. This should work
83 /// regardless of whether the function is in SSA form.
85 FunctionPass *llvm::createSparcV8CodePrinterPass (std::ostream &o,
87 return new V8Printer(o, tm);
90 /// toOctal - Convert the low order bits of X into an octal digit.
92 static inline char toOctal(int X) {
96 /// getAsCString - Return the specified array as a C compatible
97 /// string, only if the predicate isStringCompatible is true.
99 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
100 assert(CVA->isString() && "Array is not string compatible!");
103 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
104 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
108 } else if (C == '\\') {
110 } else if (isprint(C)) {
114 case '\b': O << "\\b"; break;
115 case '\f': O << "\\f"; break;
116 case '\n': O << "\\n"; break;
117 case '\r': O << "\\r"; break;
118 case '\t': O << "\\t"; break;
121 O << toOctal(C >> 6);
122 O << toOctal(C >> 3);
123 O << toOctal(C >> 0);
131 // Print out the specified constant, without a storage class. Only the
132 // constants valid in constant expressions can occur here.
133 void V8Printer::emitConstantValueOnly(const Constant *CV) {
134 if (CV->isNullValue())
136 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
137 assert(CB == ConstantBool::True);
139 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
140 if (((CI->getValue() << 32) >> 32) == CI->getValue())
143 O << (unsigned long long)CI->getValue();
144 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
146 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
147 // This is a constant address for a global variable or function. Use the
148 // name of the variable or function as the address value.
149 O << Mang->getValueName(GV);
150 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
151 const TargetData &TD = TM.getTargetData();
152 switch(CE->getOpcode()) {
153 case Instruction::GetElementPtr: {
154 // generate a symbolic expression for the byte address
155 const Constant *ptrVal = CE->getOperand(0);
156 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
157 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
159 emitConstantValueOnly(ptrVal);
160 O << ") + " << Offset;
162 emitConstantValueOnly(ptrVal);
166 case Instruction::Cast: {
167 // Support only non-converting or widening casts for now, that is, ones
168 // that do not involve a change in value. This assertion is really gross,
169 // and may not even be a complete check.
170 Constant *Op = CE->getOperand(0);
171 const Type *OpTy = Op->getType(), *Ty = CE->getType();
173 // Pointers on ILP32 machines can be losslessly converted back and
174 // forth into 32-bit or wider integers, regardless of signedness.
175 assert(((isa<PointerType>(OpTy)
176 && (Ty == Type::LongTy || Ty == Type::ULongTy
177 || Ty == Type::IntTy || Ty == Type::UIntTy))
178 || (isa<PointerType>(Ty)
179 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
180 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
181 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
182 && OpTy->isLosslesslyConvertibleTo(Ty))))
183 && "FIXME: Don't yet support this kind of constant cast expr");
185 emitConstantValueOnly(Op);
189 case Instruction::Add:
191 emitConstantValueOnly(CE->getOperand(0));
193 emitConstantValueOnly(CE->getOperand(1));
197 assert(0 && "Unsupported operator!");
200 assert(0 && "Unknown constant value!");
204 // Print a constant value or values, with the appropriate storage class as a
206 void V8Printer::emitGlobalConstant(const Constant *CV) {
207 const TargetData &TD = TM.getTargetData();
209 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
210 if (CVA->isString()) {
212 printAsCString(O, CVA);
214 } else { // Not a string. Print the values in successive locations
215 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; i++)
216 emitGlobalConstant(CVA->getOperand(i));
219 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
220 // Print the fields in successive locations. Pad to align if needed!
221 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
222 unsigned sizeSoFar = 0;
223 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; i++) {
224 const Constant* field = CVS->getOperand(i);
226 // Check if padding is needed and insert one or more 0s.
227 unsigned fieldSize = TD.getTypeSize(field->getType());
228 unsigned padSize = ((i == e-1? cvsLayout->StructSize
229 : cvsLayout->MemberOffsets[i+1])
230 - cvsLayout->MemberOffsets[i]) - fieldSize;
231 sizeSoFar += fieldSize + padSize;
233 // Now print the actual field value
234 emitGlobalConstant(field);
236 // Insert the field padding unless it's zero bytes...
238 O << "\t.skip\t " << padSize << "\n";
240 assert(sizeSoFar == cvsLayout->StructSize &&
241 "Layout of constant struct may be incorrect!");
243 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
244 // FP Constants are printed as integer constants to avoid losing
246 double Val = CFP->getValue();
247 switch (CFP->getType()->getTypeID()) {
248 default: assert(0 && "Unknown floating point type!");
249 case Type::FloatTyID: {
250 union FU { // Abide by C TBAA rules
255 O << ".long\t" << U.UVal << "\t! float " << Val << "\n";
258 case Type::DoubleTyID: {
259 union DU { // Abide by C TBAA rules
264 O << ".word\t0x" << std::hex << (U.UVal >> 32) << std::dec << "\t! double " << Val << "\n";
265 O << ".word\t0x" << std::hex << (U.UVal & 0xffffffffUL) << std::dec << "\t! double " << Val << "\n";
271 const Type *type = CV->getType();
273 switch (type->getTypeID()) {
274 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
277 case Type::UShortTyID: case Type::ShortTyID:
280 case Type::FloatTyID: case Type::PointerTyID:
281 case Type::UIntTyID: case Type::IntTyID:
284 case Type::DoubleTyID:
285 case Type::ULongTyID: case Type::LongTyID:
289 assert (0 && "Can't handle printing this type of thing");
293 emitConstantValueOnly(CV);
297 /// printConstantPool - Print to the current output stream assembly
298 /// representations of the constants in the constant pool MCP. This is
299 /// used to print out constants which have been "spilled to memory" by
300 /// the code generator.
302 void V8Printer::printConstantPool(MachineConstantPool *MCP) {
303 const std::vector<Constant*> &CP = MCP->getConstants();
304 const TargetData &TD = TM.getTargetData();
306 if (CP.empty()) return;
308 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
309 O << "\t.section \".rodata\"\n";
310 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
312 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t!"
314 emitGlobalConstant(CP[i]);
318 /// runOnMachineFunction - This uses the printMachineInstruction()
319 /// method to print assembly for each instruction.
321 bool V8Printer::runOnMachineFunction(MachineFunction &MF) {
322 // BBNumber is used here so that a given Printer will never give two
323 // BBs the same name. (If you have a better way, please let me know!)
324 static unsigned BBNumber = 0;
327 // What's my mangled name?
328 CurrentFnName = Mang->getValueName(MF.getFunction());
330 // Print out constants referenced by the function
331 printConstantPool(MF.getConstantPool());
333 // Print out labels for the function.
335 O << "\t.align 16\n";
336 O << "\t.globl\t" << CurrentFnName << "\n";
337 O << "\t.type\t" << CurrentFnName << ", #function\n";
338 O << CurrentFnName << ":\n";
340 // Number each basic block so that we can consistently refer to them
341 // in PC-relative references.
343 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
345 NumberForBB[I->getBasicBlock()] = BBNumber++;
348 // Print out code for the function.
349 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
351 // Print a label for the basic block.
352 O << ".LBB" << Mang->getValueName(MF.getFunction ())
353 << "_" << I->getNumber () << ":\t! "
354 << I->getBasicBlock ()->getName () << "\n";
355 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
357 // Print the assembly for the instruction.
359 printMachineInstruction(II);
363 // We didn't modify anything.
367 void V8Printer::printOperand(const MachineInstr *MI, int opNum) {
368 const MachineOperand &MO = MI->getOperand (opNum);
369 const MRegisterInfo &RI = *TM.getRegisterInfo();
370 bool CloseParen = false;
371 if (MI->getOpcode() == V8::SETHIi && !MO.isRegister() && !MO.isImmediate()) {
374 } else if (MI->getOpcode() ==V8::ORri &&!MO.isRegister() &&!MO.isImmediate())
379 switch (MO.getType()) {
380 case MachineOperand::MO_VirtualRegister:
381 if (Value *V = MO.getVRegValueOrNull()) {
382 O << "<" << V->getName() << ">";
386 case MachineOperand::MO_MachineRegister:
387 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
388 O << "%" << LowercaseString (RI.get(MO.getReg()).Name);
390 O << "%reg" << MO.getReg();
393 case MachineOperand::MO_SignExtendedImmed:
394 case MachineOperand::MO_UnextendedImmed:
395 O << (int)MO.getImmedValue();
397 case MachineOperand::MO_MachineBasicBlock: {
398 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
399 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
400 << "_" << MBBOp->getNumber () << "\t! "
401 << MBBOp->getBasicBlock ()->getName ();
404 case MachineOperand::MO_PCRelativeDisp:
405 std::cerr << "Shouldn't use addPCDisp() when building SparcV8 MachineInstrs";
408 case MachineOperand::MO_GlobalAddress:
409 O << Mang->getValueName(MO.getGlobal());
411 case MachineOperand::MO_ExternalSymbol:
412 O << MO.getSymbolName();
414 case MachineOperand::MO_ConstantPoolIndex:
415 O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
418 O << "<unknown operand type>"; abort (); break;
420 if (CloseParen) O << ")";
423 static bool isLoadInstruction (const MachineInstr *MI) {
424 switch (MI->getOpcode ()) {
441 static bool isStoreInstruction (const MachineInstr *MI) {
442 switch (MI->getOpcode ()) {
457 static bool isPseudoInstruction (const MachineInstr *MI) {
458 switch (MI->getOpcode ()) {
460 case V8::ADJCALLSTACKUP:
461 case V8::ADJCALLSTACKDOWN:
462 case V8::IMPLICIT_USE:
463 case V8::IMPLICIT_DEF:
470 /// printBaseOffsetPair - Print two consecutive operands of MI, starting at #i,
471 /// which form a base + offset pair (which may have brackets around it, if
472 /// brackets is true, or may be in the form base - constant, if offset is a
473 /// negative constant).
475 void V8Printer::printBaseOffsetPair (const MachineInstr *MI, int i,
477 if (brackets) O << "[";
478 printOperand (MI, i);
479 if (MI->getOperand (i + 1).isImmediate()) {
480 int Val = (int) MI->getOperand (i + 1).getImmedValue ();
482 O << ((Val >= 0) ? " + " : " - ");
483 O << ((Val >= 0) ? Val : -Val);
487 printOperand (MI, i + 1);
489 if (brackets) O << "]";
492 /// printMachineInstruction -- Print out a single SparcV8 LLVM instruction
493 /// MI in GAS syntax to the current output stream.
495 void V8Printer::printMachineInstruction(const MachineInstr *MI) {
496 unsigned Opcode = MI->getOpcode();
497 const TargetInstrInfo &TII = *TM.getInstrInfo();
498 const TargetInstrDescriptor &Desc = TII.get(Opcode);
500 // If it's a pseudo-instruction, comment it out.
501 if (isPseudoInstruction (MI))
504 O << Desc.Name << " ";
506 // Printing memory instructions is a special case.
507 // for loads: %dest = op %base, offset --> op [%base + offset], %dest
508 // for stores: op %base, offset, %src --> op %src, [%base + offset]
509 if (isLoadInstruction (MI)) {
510 printBaseOffsetPair (MI, 1);
512 printOperand (MI, 0);
515 } else if (isStoreInstruction (MI)) {
516 printOperand (MI, 2);
518 printBaseOffsetPair (MI, 0);
521 } else if (Opcode == V8::JMPLrr) {
522 printBaseOffsetPair (MI, 1, false);
524 printOperand (MI, 0);
529 // print non-immediate, non-register-def operands
530 // then print immediate operands
531 // then print register-def operands.
532 std::vector<int> print_order;
533 for (unsigned i = 0; i < MI->getNumOperands (); ++i)
534 if (!(MI->getOperand (i).isImmediate ()
535 || (MI->getOperand (i).isRegister ()
536 && MI->getOperand (i).isDef ())))
537 print_order.push_back (i);
538 for (unsigned i = 0; i < MI->getNumOperands (); ++i)
539 if (MI->getOperand (i).isImmediate ())
540 print_order.push_back (i);
541 for (unsigned i = 0; i < MI->getNumOperands (); ++i)
542 if (MI->getOperand (i).isRegister () && MI->getOperand (i).isDef ())
543 print_order.push_back (i);
544 for (unsigned i = 0, e = print_order.size (); i != e; ++i) {
545 printOperand (MI, print_order[i]);
546 if (i != (print_order.size () - 1))
552 bool V8Printer::doInitialization(Module &M) {
553 Mang = new Mangler(M);
554 return false; // success
557 // SwitchSection - Switch to the specified section of the executable if we are
558 // not already in it!
560 static void SwitchSection(std::ostream &OS, std::string &CurSection,
561 const char *NewSection) {
562 if (CurSection != NewSection) {
563 CurSection = NewSection;
564 if (!CurSection.empty())
565 OS << "\t.section \"" << NewSection << "\"\n";
569 bool V8Printer::doFinalization(Module &M) {
570 const TargetData &TD = TM.getTargetData();
571 std::string CurSection;
573 // Print out module-level global variables here.
574 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
575 if (I->hasInitializer()) { // External global require no code
577 std::string name = Mang->getValueName(I);
578 Constant *C = I->getInitializer();
579 unsigned Size = TD.getTypeSize(C->getType());
580 unsigned Align = TD.getTypeAlignment(C->getType());
582 if (C->isNullValue() &&
583 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
584 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
585 SwitchSection(O, CurSection, ".data");
586 if (I->hasInternalLinkage())
587 O << "\t.local " << name << "\n";
589 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
590 << "," << (unsigned)TD.getTypeAlignment(C->getType());
592 WriteAsOperand(O, I, true, true, &M);
595 switch (I->getLinkage()) {
596 case GlobalValue::LinkOnceLinkage:
597 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
598 // Nonnull linkonce -> weak
599 O << "\t.weak " << name << "\n";
600 SwitchSection(O, CurSection, "");
601 O << "\t.section\t\".llvm.linkonce.d." << name << "\",\"aw\",@progbits\n";
604 case GlobalValue::AppendingLinkage:
605 // FIXME: appending linkage variables should go into a section of
606 // their name or something. For now, just emit them as external.
607 case GlobalValue::ExternalLinkage:
608 // If external or appending, declare as a global symbol
609 O << "\t.globl " << name << "\n";
611 case GlobalValue::InternalLinkage:
612 if (C->isNullValue())
613 SwitchSection(O, CurSection, ".bss");
615 SwitchSection(O, CurSection, ".data");
619 O << "\t.align " << Align << "\n";
620 O << "\t.type " << name << ",#object\n";
621 O << "\t.size " << name << "," << Size << "\n";
622 O << name << ":\t\t\t\t! ";
623 WriteAsOperand(O, I, true, true, &M);
625 WriteAsOperand(O, C, false, false, &M);
627 emitGlobalConstant(C);
632 return false; // success