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 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 const std::vector<Use> &constValues = CVA->getValues();
216 for (unsigned i=0; i < constValues.size(); i++)
217 emitGlobalConstant(cast<Constant>(constValues[i].get()));
220 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
221 // Print the fields in successive locations. Pad to align if needed!
222 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
223 const std::vector<Use>& constValues = CVS->getValues();
224 unsigned sizeSoFar = 0;
225 for (unsigned i=0, N = constValues.size(); i < N; i++) {
226 const Constant* field = cast<Constant>(constValues[i].get());
228 // Check if padding is needed and insert one or more 0s.
229 unsigned fieldSize = TD.getTypeSize(field->getType());
230 unsigned padSize = ((i == N-1? cvsLayout->StructSize
231 : cvsLayout->MemberOffsets[i+1])
232 - cvsLayout->MemberOffsets[i]) - fieldSize;
233 sizeSoFar += fieldSize + padSize;
235 // Now print the actual field value
236 emitGlobalConstant(field);
238 // Insert the field padding unless it's zero bytes...
240 O << "\t.skip\t " << padSize << "\n";
242 assert(sizeSoFar == cvsLayout->StructSize &&
243 "Layout of constant struct may be incorrect!");
245 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
246 // FP Constants are printed as integer constants to avoid losing
248 double Val = CFP->getValue();
249 switch (CFP->getType()->getTypeID()) {
250 default: assert(0 && "Unknown floating point type!");
251 case Type::FloatTyID: {
252 union FU { // Abide by C TBAA rules
257 O << ".long\t" << U.UVal << "\t! float " << Val << "\n";
260 case Type::DoubleTyID: {
261 union DU { // Abide by C TBAA rules
266 O << ".quad\t" << U.UVal << "\t! double " << Val << "\n";
272 const Type *type = CV->getType();
274 switch (type->getTypeID()) {
275 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
278 case Type::UShortTyID: case Type::ShortTyID:
281 case Type::FloatTyID: case Type::PointerTyID:
282 case Type::UIntTyID: case Type::IntTyID:
285 case Type::DoubleTyID:
286 case Type::ULongTyID: case Type::LongTyID:
290 assert (0 && "Can't handle printing this type of thing");
294 emitConstantValueOnly(CV);
298 /// printConstantPool - Print to the current output stream assembly
299 /// representations of the constants in the constant pool MCP. This is
300 /// used to print out constants which have been "spilled to memory" by
301 /// the code generator.
303 void V8Printer::printConstantPool(MachineConstantPool *MCP) {
304 const std::vector<Constant*> &CP = MCP->getConstants();
305 const TargetData &TD = TM.getTargetData();
307 if (CP.empty()) return;
309 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
310 O << "\t.section .rodata\n";
311 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
313 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t!"
315 emitGlobalConstant(CP[i]);
319 /// runOnMachineFunction - This uses the printMachineInstruction()
320 /// method to print assembly for each instruction.
322 bool V8Printer::runOnMachineFunction(MachineFunction &MF) {
323 // BBNumber is used here so that a given Printer will never give two
324 // BBs the same name. (If you have a better way, please let me know!)
325 static unsigned BBNumber = 0;
328 // What's my mangled name?
329 CurrentFnName = Mang->getValueName(MF.getFunction());
331 // Print out constants referenced by the function
332 printConstantPool(MF.getConstantPool());
334 // Print out labels for the function.
336 O << "\t.align 16\n";
337 O << "\t.globl\t" << CurrentFnName << "\n";
338 O << "\t.type\t" << CurrentFnName << ", #function\n";
339 O << CurrentFnName << ":\n";
341 // Number each basic block so that we can consistently refer to them
342 // in PC-relative references.
344 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
346 NumberForBB[I->getBasicBlock()] = BBNumber++;
349 // Print out code for the function.
350 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
352 // Print a label for the basic block.
353 O << ".LBB" << Mang->getValueName(MF.getFunction ())
354 << "_" << I->getNumber () << ":\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 MachineInstr *MI, int opNum) {
369 const MachineOperand &MO = MI->getOperand (opNum);
370 const MRegisterInfo &RI = *TM.getRegisterInfo();
371 bool CloseParen = false;
372 if (MI->getOpcode() == V8::SETHIi && !MO.isRegister() && !MO.isImmediate()) {
375 } else if (MI->getOpcode() ==V8::ORri &&!MO.isRegister() &&!MO.isImmediate())
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_MachineBasicBlock: {
399 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
400 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
401 << "_" << MBBOp->getNumber () << "\t! "
402 << MBBOp->getBasicBlock ()->getName ();
405 case MachineOperand::MO_PCRelativeDisp:
406 std::cerr << "Shouldn't use addPCDisp() when building SparcV8 MachineInstrs";
409 case MachineOperand::MO_GlobalAddress:
410 O << Mang->getValueName(MO.getGlobal());
412 case MachineOperand::MO_ExternalSymbol:
413 O << MO.getSymbolName();
415 case MachineOperand::MO_ConstantPoolIndex:
416 O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
419 O << "<unknown operand type>"; abort (); break;
421 if (CloseParen) O << ")";
424 static bool isLoadInstruction (const MachineInstr *MI) {
425 switch (MI->getOpcode ()) {
442 static bool isStoreInstruction (const MachineInstr *MI) {
443 switch (MI->getOpcode ()) {
458 static bool isPseudoInstruction (const MachineInstr *MI) {
459 switch (MI->getOpcode ()) {
461 case V8::ADJCALLSTACKUP:
462 case V8::ADJCALLSTACKDOWN:
463 case V8::IMPLICIT_USE:
464 case V8::IMPLICIT_DEF:
471 /// printBaseOffsetPair - Print two consecutive operands of MI, starting at #i,
472 /// which form a base + offset pair (which may have brackets around it, if
473 /// brackets is true, or may be in the form base - constant, if offset is a
474 /// negative constant).
476 void V8Printer::printBaseOffsetPair (const MachineInstr *MI, int i,
478 if (brackets) O << "[";
479 printOperand (MI, i);
480 if (MI->getOperand (i + 1).isImmediate()) {
481 int Val = (int) MI->getOperand (i + 1).getImmedValue ();
483 O << ((Val >= 0) ? " + " : " - ");
484 O << ((Val >= 0) ? Val : -Val);
488 printOperand (MI, i + 1);
490 if (brackets) O << "]";
493 /// printMachineInstruction -- Print out a single SparcV8 LLVM instruction
494 /// MI in GAS syntax to the current output stream.
496 void V8Printer::printMachineInstruction(const MachineInstr *MI) {
497 unsigned Opcode = MI->getOpcode();
498 const TargetInstrInfo &TII = *TM.getInstrInfo();
499 const TargetInstrDescriptor &Desc = TII.get(Opcode);
501 // If it's a pseudo-instruction, comment it out.
502 if (isPseudoInstruction (MI))
505 O << Desc.Name << " ";
507 // Printing memory instructions is a special case.
508 // for loads: %dest = op %base, offset --> op [%base + offset], %dest
509 // for stores: op %base, offset, %src --> op %src, [%base + offset]
510 if (isLoadInstruction (MI)) {
511 printBaseOffsetPair (MI, 1);
513 printOperand (MI, 0);
516 } else if (isStoreInstruction (MI)) {
517 printOperand (MI, 2);
519 printBaseOffsetPair (MI, 0);
522 } else if (Opcode == V8::JMPLrr) {
523 printBaseOffsetPair (MI, 1, false);
525 printOperand (MI, 0);
530 // print non-immediate, non-register-def operands
531 // then print immediate operands
532 // then print register-def operands.
533 std::vector<int> print_order;
534 for (unsigned i = 0; i < MI->getNumOperands (); ++i)
535 if (!(MI->getOperand (i).isImmediate ()
536 || (MI->getOperand (i).isRegister ()
537 && MI->getOperand (i).isDef ())))
538 print_order.push_back (i);
539 for (unsigned i = 0; i < MI->getNumOperands (); ++i)
540 if (MI->getOperand (i).isImmediate ())
541 print_order.push_back (i);
542 for (unsigned i = 0; i < MI->getNumOperands (); ++i)
543 if (MI->getOperand (i).isRegister () && MI->getOperand (i).isDef ())
544 print_order.push_back (i);
545 for (unsigned i = 0, e = print_order.size (); i != e; ++i) {
546 printOperand (MI, print_order[i]);
547 if (i != (print_order.size () - 1))
553 bool V8Printer::doInitialization(Module &M) {
554 Mang = new Mangler(M);
555 return false; // success
558 // SwitchSection - Switch to the specified section of the executable if we are
559 // not already in it!
561 static void SwitchSection(std::ostream &OS, std::string &CurSection,
562 const char *NewSection) {
563 if (CurSection != NewSection) {
564 CurSection = NewSection;
565 if (!CurSection.empty())
566 OS << "\t.section " << NewSection << "\n";
570 bool V8Printer::doFinalization(Module &M) {
571 const TargetData &TD = TM.getTargetData();
572 std::string CurSection;
574 // Print out module-level global variables here.
575 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
576 if (I->hasInitializer()) { // External global require no code
578 std::string name = Mang->getValueName(I);
579 Constant *C = I->getInitializer();
580 unsigned Size = TD.getTypeSize(C->getType());
581 unsigned Align = TD.getTypeAlignment(C->getType());
583 if (C->isNullValue() &&
584 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
585 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
586 SwitchSection(O, CurSection, ".data");
587 if (I->hasInternalLinkage())
588 O << "\t.local " << name << "\n";
590 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
591 << "," << (unsigned)TD.getTypeAlignment(C->getType());
593 WriteAsOperand(O, I, true, true, &M);
596 switch (I->getLinkage()) {
597 case GlobalValue::LinkOnceLinkage:
598 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
599 // Nonnull linkonce -> weak
600 O << "\t.weak " << name << "\n";
601 SwitchSection(O, CurSection, "");
602 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
605 case GlobalValue::AppendingLinkage:
606 // FIXME: appending linkage variables should go into a section of
607 // their name or something. For now, just emit them as external.
608 case GlobalValue::ExternalLinkage:
609 // If external or appending, declare as a global symbol
610 O << "\t.globl " << name << "\n";
612 case GlobalValue::InternalLinkage:
613 if (C->isNullValue())
614 SwitchSection(O, CurSection, ".bss");
616 SwitchSection(O, CurSection, ".data");
620 O << "\t.align " << Align << "\n";
621 O << "\t.type " << name << ",#object\n";
622 O << "\t.size " << name << "," << Size << "\n";
623 O << name << ":\t\t\t\t! ";
624 WriteAsOperand(O, I, true, true, &M);
626 WriteAsOperand(O, C, false, false, &M);
628 emitGlobalConstant(C);
633 return false; // success