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"
29 #include "llvm/Support/MathExtras.h"
34 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
36 struct SparcV8AsmPrinter : public MachineFunctionPass {
37 /// Output stream on which we're printing assembly code.
41 /// Target machine description which we query for reg. names, data
46 /// Name-mangler for global names.
50 SparcV8AsmPrinter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
52 /// We name each basic block in a Function with a unique number, so
53 /// that we can consistently refer to them later. This is cleared
54 /// at the beginning of each call to runOnMachineFunction().
56 typedef std::map<const Value *, unsigned> ValueMapTy;
57 ValueMapTy NumberForBB;
59 /// Cache of mangled name for current function. This is
60 /// recalculated at the beginning of each call to
61 /// runOnMachineFunction().
63 std::string CurrentFnName;
65 virtual const char *getPassName() const {
66 return "SparcV8 Assembly Printer";
69 void emitConstantValueOnly(const Constant *CV);
70 void emitGlobalConstant(const Constant *CV);
71 void printConstantPool(MachineConstantPool *MCP);
72 void printOperand(const MachineInstr *MI, int opNum);
73 void printMachineInstruction(const MachineInstr *MI);
74 bool printInstruction(const MachineInstr *MI); // autogenerated.
75 bool runOnMachineFunction(MachineFunction &F);
76 bool doInitialization(Module &M);
77 bool doFinalization(Module &M);
79 } // end of anonymous namespace
81 #include "SparcV8GenAsmWriter.inc"
83 /// createSparcV8CodePrinterPass - Returns a pass that prints the SparcV8
84 /// assembly code for a MachineFunction to the given output stream,
85 /// using the given target machine description. This should work
86 /// regardless of whether the function is in SSA form.
88 FunctionPass *llvm::createSparcV8CodePrinterPass (std::ostream &o,
90 return new SparcV8AsmPrinter(o, tm);
93 /// toOctal - Convert the low order bits of X into an octal digit.
95 static inline char toOctal(int X) {
99 /// getAsCString - Return the specified array as a C compatible
100 /// string, only if the predicate isStringCompatible is true.
102 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
103 assert(CVA->isString() && "Array is not string compatible!");
106 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
107 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
111 } else if (C == '\\') {
113 } else if (isprint(C)) {
117 case '\b': O << "\\b"; break;
118 case '\f': O << "\\f"; break;
119 case '\n': O << "\\n"; break;
120 case '\r': O << "\\r"; break;
121 case '\t': O << "\\t"; break;
124 O << toOctal(C >> 6);
125 O << toOctal(C >> 3);
126 O << toOctal(C >> 0);
134 // Print out the specified constant, without a storage class. Only the
135 // constants valid in constant expressions can occur here.
136 void SparcV8AsmPrinter::emitConstantValueOnly(const Constant *CV) {
137 if (CV->isNullValue() || isa<UndefValue> (CV))
139 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
140 assert(CB == ConstantBool::True);
142 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
143 if (((CI->getValue() << 32) >> 32) == CI->getValue())
146 O << (unsigned long long)CI->getValue();
147 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
149 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
150 // This is a constant address for a global variable or function. Use the
151 // name of the variable or function as the address value.
152 O << Mang->getValueName(GV);
153 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
154 const TargetData &TD = TM.getTargetData();
155 switch(CE->getOpcode()) {
156 case Instruction::GetElementPtr: {
157 // generate a symbolic expression for the byte address
158 const Constant *ptrVal = CE->getOperand(0);
159 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
160 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
162 emitConstantValueOnly(ptrVal);
163 O << ") + " << Offset;
165 emitConstantValueOnly(ptrVal);
169 case Instruction::Cast: {
170 // Support only non-converting or widening casts for now, that is, ones
171 // that do not involve a change in value. This assertion is really gross,
172 // and may not even be a complete check.
173 Constant *Op = CE->getOperand(0);
174 const Type *OpTy = Op->getType(), *Ty = CE->getType();
176 // Pointers on ILP32 machines can be losslessly converted back and
177 // forth into 32-bit or wider integers, regardless of signedness.
178 assert(((isa<PointerType>(OpTy)
179 && (Ty == Type::LongTy || Ty == Type::ULongTy
180 || Ty == Type::IntTy || Ty == Type::UIntTy))
181 || (isa<PointerType>(Ty)
182 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
183 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
184 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
185 && OpTy->isLosslesslyConvertibleTo(Ty))))
186 && "FIXME: Don't yet support this kind of constant cast expr");
188 emitConstantValueOnly(Op);
192 case Instruction::Add:
194 emitConstantValueOnly(CE->getOperand(0));
196 emitConstantValueOnly(CE->getOperand(1));
200 assert(0 && "Unsupported operator!");
203 assert(0 && "Unknown constant value!");
207 // Print a constant value or values, with the appropriate storage class as a
209 void SparcV8AsmPrinter::emitGlobalConstant(const Constant *CV) {
210 const TargetData &TD = TM.getTargetData();
212 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
213 if (CVA->isString()) {
215 printAsCString(O, CVA);
217 } else { // Not a string. Print the values in successive locations
218 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; i++)
219 emitGlobalConstant(CVA->getOperand(i));
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 unsigned sizeSoFar = 0;
226 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; i++) {
227 const Constant* field = CVS->getOperand(i);
229 // Check if padding is needed and insert one or more 0s.
230 unsigned fieldSize = TD.getTypeSize(field->getType());
231 unsigned padSize = ((i == e-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.skip\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()->getTypeID()) {
251 default: assert(0 && "Unknown floating point type!");
252 case Type::FloatTyID: {
253 O << ".long\t" << FloatToBits(Val) << "\t! float " << Val << "\n";
256 case Type::DoubleTyID: {
257 O << ".word\t0x" << std::hex << (DoubleToBits(Val) >> 32) << std::dec << "\t! double " << Val << "\n";
258 O << ".word\t0x" << std::hex << (DoubleToBits(Val) & 0xffffffffUL) << std::dec << "\t! double " << Val << "\n";
262 } else if (isa<UndefValue> (CV)) {
263 unsigned size = TD.getTypeSize (CV->getType ());
264 O << "\t.skip\t " << size << "\n";
266 } else if (isa<ConstantAggregateZero> (CV)) {
267 unsigned size = TD.getTypeSize (CV->getType ());
268 for (unsigned i = 0; i < size; ++i)
273 const Type *type = CV->getType();
275 switch (type->getTypeID()) {
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 SparcV8AsmPrinter::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 SparcV8AsmPrinter::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" << Mang->getValueName(MF.getFunction ())
355 << "_" << I->getNumber () << ":\t! "
356 << I->getBasicBlock ()->getName () << "\n";
357 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
359 // Print the assembly for the instruction.
360 printMachineInstruction(II);
364 // We didn't modify anything.
368 void SparcV8AsmPrinter::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 /// printMachineInstruction -- Print out a single SparcV8 LLVM instruction
425 /// MI in GAS syntax to the current output stream.
427 void SparcV8AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
429 if (printInstruction(MI)) return;
431 unsigned Opcode = MI->getOpcode();
432 const TargetInstrInfo &TII = *TM.getInstrInfo();
433 const TargetInstrDescriptor &Desc = TII.get(Opcode);
435 O << Desc.Name << " ";
437 // print non-immediate, non-register-def operands
438 // then print immediate operands
439 // then print register-def operands.
440 std::vector<int> print_order;
441 for (unsigned i = 0; i < MI->getNumOperands (); ++i)
442 if (!(MI->getOperand (i).isImmediate ()
443 || (MI->getOperand (i).isRegister ()
444 && MI->getOperand (i).isDef ())))
445 print_order.push_back (i);
446 for (unsigned i = 0; i < MI->getNumOperands (); ++i)
447 if (MI->getOperand (i).isImmediate ())
448 print_order.push_back (i);
449 for (unsigned i = 0; i < MI->getNumOperands (); ++i)
450 if (MI->getOperand (i).isRegister () && MI->getOperand (i).isDef ())
451 print_order.push_back (i);
452 for (unsigned i = 0, e = print_order.size (); i != e; ++i) {
453 printOperand (MI, print_order[i]);
454 if (i != (print_order.size () - 1))
460 bool SparcV8AsmPrinter::doInitialization(Module &M) {
461 Mang = new Mangler(M);
462 return false; // success
465 // SwitchSection - Switch to the specified section of the executable if we are
466 // not already in it!
468 static void SwitchSection(std::ostream &OS, std::string &CurSection,
469 const char *NewSection) {
470 if (CurSection != NewSection) {
471 CurSection = NewSection;
472 if (!CurSection.empty())
473 OS << "\t.section \"" << NewSection << "\"\n";
477 bool SparcV8AsmPrinter::doFinalization(Module &M) {
478 const TargetData &TD = TM.getTargetData();
479 std::string CurSection;
481 // Print out module-level global variables here.
482 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
483 if (I->hasInitializer()) { // External global require no code
485 std::string name = Mang->getValueName(I);
486 Constant *C = I->getInitializer();
487 unsigned Size = TD.getTypeSize(C->getType());
488 unsigned Align = TD.getTypeAlignment(C->getType());
490 if (C->isNullValue() &&
491 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
492 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
493 SwitchSection(O, CurSection, ".data");
494 if (I->hasInternalLinkage())
495 O << "\t.local " << name << "\n";
497 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
498 << "," << (unsigned)TD.getTypeAlignment(C->getType());
500 WriteAsOperand(O, I, true, true, &M);
503 switch (I->getLinkage()) {
504 case GlobalValue::LinkOnceLinkage:
505 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
506 // Nonnull linkonce -> weak
507 O << "\t.weak " << name << "\n";
508 SwitchSection(O, CurSection, "");
509 O << "\t.section\t\".llvm.linkonce.d." << name << "\",\"aw\",@progbits\n";
512 case GlobalValue::AppendingLinkage:
513 // FIXME: appending linkage variables should go into a section of
514 // their name or something. For now, just emit them as external.
515 case GlobalValue::ExternalLinkage:
516 // If external or appending, declare as a global symbol
517 O << "\t.globl " << name << "\n";
519 case GlobalValue::InternalLinkage:
520 if (C->isNullValue())
521 SwitchSection(O, CurSection, ".bss");
523 SwitchSection(O, CurSection, ".data");
525 case GlobalValue::GhostLinkage:
526 std::cerr << "Should not have any unmaterialized functions!\n";
530 O << "\t.align " << Align << "\n";
531 O << "\t.type " << name << ",#object\n";
532 O << "\t.size " << name << "," << Size << "\n";
533 O << name << ":\t\t\t\t! ";
534 WriteAsOperand(O, I, true, true, &M);
536 WriteAsOperand(O, C, false, false, &M);
538 emitGlobalConstant(C);
543 return false; // success