1 //===-- EmitAssembly.cpp - Emit Sparc Specific .s File ---------------------==//
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 implements all of the stuff necessary to output a .s file from
11 // LLVM. The code in this file assumes that the specified module has already
12 // been compiled into the internal data structures of the Module.
14 // This code largely consists of two LLVM Pass's: a FunctionPass and a Pass.
15 // The FunctionPass is pipelined together with all of the rest of the code
16 // generation stages, and the Pass runs at the end to emit code for global
17 // variables and such.
19 //===----------------------------------------------------------------------===//
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFunctionInfo.h"
25 #include "llvm/Constants.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/Module.h"
28 #include "llvm/SlotCalculator.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Assembly/Writer.h"
31 #include "Support/StringExtras.h"
32 #include "Support/Statistic.h"
33 #include "SparcInternals.h"
38 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
40 class GlobalIdTable: public Annotation {
41 static AnnotationID AnnotId;
42 friend class AsmPrinter; // give access to AnnotId
44 typedef hash_map<const Value*, int> ValIdMap;
45 typedef ValIdMap::const_iterator ValIdMapConstIterator;
46 typedef ValIdMap:: iterator ValIdMapIterator;
48 SlotCalculator Table; // map anonymous values to unique integer IDs
49 ValIdMap valToIdMap; // used for values not handled by SlotCalculator
51 GlobalIdTable(Module* M) : Annotation(AnnotId), Table(M, true) {}
54 AnnotationID GlobalIdTable::AnnotId =
55 AnnotationManager::getID("ASM PRINTER GLOBAL TABLE ANNOT");
57 // Can we treat the specified array as a string? Only if it is an array of
58 // ubytes or non-negative sbytes.
60 static bool isStringCompatible(const ConstantArray *CVA) {
61 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
62 if (ETy == Type::UByteTy) return true;
63 if (ETy != Type::SByteTy) return false;
65 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
66 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
72 // toOctal - Convert the low order bits of X into an octal letter
73 static inline char toOctal(int X) {
77 // getAsCString - Return the specified array as a C compatible string, only if
78 // the predicate isStringCompatible is true.
80 static std::string getAsCString(const ConstantArray *CVA) {
81 assert(isStringCompatible(CVA) && "Array is not string compatible!");
84 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
86 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
87 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
91 } else if (C == '\\') {
93 } else if (isprint(C)) {
96 Result += '\\'; // print all other chars as octal value
97 Result += toOctal(C >> 6);
98 Result += toOctal(C >> 3);
99 Result += toOctal(C >> 0);
108 ArrayTypeIsString(const ArrayType* arrayType)
110 return (arrayType->getElementType() == Type::UByteTy ||
111 arrayType->getElementType() == Type::SByteTy);
115 inline const std::string
116 TypeToDataDirective(const Type* type)
118 switch(type->getPrimitiveID())
120 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
122 case Type::UShortTyID: case Type::ShortTyID:
124 case Type::UIntTyID: case Type::IntTyID:
126 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
128 case Type::FloatTyID:
130 case Type::DoubleTyID:
132 case Type::ArrayTyID:
133 if (ArrayTypeIsString((ArrayType*) type))
136 return "<InvaliDataTypeForPrinting>";
138 return "<InvaliDataTypeForPrinting>";
142 // Get the size of the type
145 TypeToSize(const Type* type, const TargetMachine& target)
147 return target.findOptimalStorageSize(type);
150 // Get the size of the constant for the given target.
151 // If this is an unsized array, return 0.
154 ConstantToSize(const Constant* CV, const TargetMachine& target)
156 if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
158 const ArrayType *aty = cast<ArrayType>(CVA->getType());
159 if (ArrayTypeIsString(aty))
160 return 1 + CVA->getNumOperands();
163 return TypeToSize(CV->getType(), target);
166 // Align data larger than one L1 cache line on L1 cache line boundaries.
167 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
170 SizeToAlignment(unsigned int size, const TargetMachine& target)
172 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
173 if (size > (unsigned) cacheLineSize / 2)
174 return cacheLineSize;
176 for (unsigned sz=1; /*no condition*/; sz *= 2)
181 // Get the size of the type and then use SizeToAlignment.
184 TypeToAlignment(const Type* type, const TargetMachine& target)
186 return SizeToAlignment(TypeToSize(type, target), target);
189 // Get the size of the constant and then use SizeToAlignment.
190 // Handles strings as a special case;
192 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
194 if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
195 if (ArrayTypeIsString(cast<ArrayType>(CVA->getType())))
196 return SizeToAlignment(1 + CVA->getNumOperands(), target);
198 return TypeToAlignment(CV->getType(), target);
201 //===---------------------------------------------------------------------===//
202 // Code Shared By the two printer passes, as a mixin
203 //===---------------------------------------------------------------------===//
206 GlobalIdTable* idTable;
209 const TargetMachine &Target;
219 AsmPrinter(std::ostream &os, const TargetMachine &T)
220 : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
222 // (start|end)(Module|Function) - Callback methods to be invoked by subclasses
223 void startModule(Module &M) {
224 // Create the global id table if it does not already exist
225 idTable = (GlobalIdTable*)M.getAnnotation(GlobalIdTable::AnnotId);
226 if (idTable == NULL) {
227 idTable = new GlobalIdTable(&M);
228 M.addAnnotation(idTable);
233 PrintZeroBytesToPad(int numBytes)
235 for ( ; numBytes >= 8; numBytes -= 8)
236 printSingleConstantValue(Constant::getNullValue(Type::ULongTy));
240 printSingleConstantValue(Constant::getNullValue(Type::UIntTy));
245 printSingleConstantValue(Constant::getNullValue(Type::UByteTy));
248 // Print a single constant value.
249 void printSingleConstantValue(const Constant* CV)
251 assert(CV->getType() != Type::VoidTy &&
252 CV->getType() != Type::TypeTy &&
253 CV->getType() != Type::LabelTy &&
254 "Unexpected type for Constant");
256 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
257 && "Aggregate types should be handled outside this function");
259 toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
261 if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
262 { // This is a constant address for a global variable or method.
263 // Use the name of the variable or method as the address value.
264 assert(isa<GlobalValue>(CPR->getValue()) && "Unexpected non-global");
265 toAsm << getID(CPR->getValue()) << "\n";
267 else if (isa<ConstantPointerNull>(CV))
268 { // Null pointer value
271 else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
272 { // Constant expression built from operators, constants, and symbolic addrs
273 toAsm << ConstantExprToString(CE, Target) << "\n";
275 else if (CV->getType()->isPrimitiveType()) // Check primitive types last
277 if (CV->getType()->isFloatingPoint()) {
278 // FP Constants are printed as integer constants to avoid losing
280 double Val = cast<ConstantFP>(CV)->getValue();
281 if (CV->getType() == Type::FloatTy) {
282 float FVal = (float)Val;
283 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
284 toAsm << *(unsigned int*)ProxyPtr;
285 } else if (CV->getType() == Type::DoubleTy) {
286 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
287 toAsm << *(uint64_t*)ProxyPtr;
289 assert(0 && "Unknown floating point type!");
292 toAsm << "\t! " << CV->getType()->getDescription()
293 << " value: " << Val << "\n";
295 WriteAsOperand(toAsm, CV, false, false) << "\n";
300 assert(0 && "Unknown elementary type for constant");
304 // Print a constant value or values (it may be an aggregate).
305 // Uses printSingleConstantValue() to print each individual value.
307 printConstantValueOnly(const Constant* CV,
308 int numPadBytesAfter = 0)
310 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
312 if (CVA && isStringCompatible(CVA))
313 { // print the string alone and return
314 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
317 { // Not a string. Print the values in successive locations
318 const std::vector<Use> &constValues = CVA->getValues();
319 for (unsigned i=0; i < constValues.size(); i++)
320 printConstantValueOnly(cast<Constant>(constValues[i].get()));
322 else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
323 { // Print the fields in successive locations. Pad to align if needed!
324 const StructLayout *cvsLayout =
325 Target.getTargetData().getStructLayout(CVS->getType());
326 const std::vector<Use>& constValues = CVS->getValues();
327 unsigned sizeSoFar = 0;
328 for (unsigned i=0, N = constValues.size(); i < N; i++)
330 const Constant* field = cast<Constant>(constValues[i].get());
332 // Check if padding is needed and insert one or more 0s.
334 Target.getTargetData().getTypeSize(field->getType());
335 int padSize = ((i == N-1? cvsLayout->StructSize
336 : cvsLayout->MemberOffsets[i+1])
337 - cvsLayout->MemberOffsets[i]) - fieldSize;
338 sizeSoFar += (fieldSize + padSize);
340 // Now print the actual field value
341 printConstantValueOnly(field, padSize);
343 assert(sizeSoFar == cvsLayout->StructSize &&
344 "Layout of constant struct may be incorrect!");
347 printSingleConstantValue(CV);
349 if (numPadBytesAfter)
350 PrintZeroBytesToPad(numPadBytesAfter);
353 // Print a constant (which may be an aggregate) prefixed by all the
354 // appropriate directives. Uses printConstantValueOnly() to print the
356 void printConstant(const Constant* CV, std::string valID = "")
358 if (valID.length() == 0)
361 toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
363 // Print .size and .type only if it is not a string.
364 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
365 if (CVA && isStringCompatible(CVA))
366 { // print it as a string and return
367 toAsm << valID << ":\n";
368 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
372 toAsm << "\t.type" << "\t" << valID << ",#object\n";
374 unsigned int constSize = ConstantToSize(CV, Target);
376 toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
378 toAsm << valID << ":\n";
380 printConstantValueOnly(CV);
383 void startFunction(Function &F) {
384 // Make sure the slot table has information about this function...
385 idTable->Table.incorporateFunction(&F);
387 void endFunction(Function &) {
388 idTable->Table.purgeFunction(); // Forget all about F
393 // Check if a value is external or accessible from external code.
394 bool isExternal(const Value* V) {
395 const GlobalValue *GV = dyn_cast<GlobalValue>(V);
396 return GV && GV->hasExternalLinkage();
399 // enterSection - Use this method to enter a different section of the output
400 // executable. This is used to only output necessary section transitions.
402 void enterSection(enum Sections S) {
403 if (S == CurSection) return; // Only switch section if necessary
406 toAsm << "\n\t.section ";
409 default: assert(0 && "Bad section name!");
410 case Text: toAsm << "\".text\""; break;
411 case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
412 case InitRWData: toAsm << "\".data\",#alloc,#write"; break;
413 case ZeroInitRWData: toAsm << "\".bss\",#alloc,#write"; break;
418 static std::string getValidSymbolName(const std::string &S) {
421 // Symbol names in Sparc assembly language have these rules:
422 // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
423 // (b) A name beginning in "." is treated as a local name.
428 for (unsigned i = 0; i < S.size(); ++i)
431 if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
436 Result += char('0' + ((unsigned char)C >> 4));
437 Result += char('0' + (C & 0xF));
443 // getID - Return a valid identifier for the specified value. Base it on
444 // the name of the identifier if possible (qualified by the type), and
445 // use a numbered value based on prefix otherwise.
446 // FPrefix is always prepended to the output identifier.
448 std::string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
449 std::string Result = FPrefix ? FPrefix : ""; // "Forced prefix"
451 Result += V->hasName() ? V->getName() : std::string(Prefix);
453 // Qualify all internal names with a unique id.
454 if (!isExternal(V)) {
455 int valId = idTable->Table.getSlot(V);
457 GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
458 if (I == idTable->valToIdMap.end())
459 valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
463 Result = Result + "_" + itostr(valId);
465 // Replace or prefix problem characters in the name
466 Result = getValidSymbolName(Result);
472 // getID Wrappers - Ensure consistent usage...
473 std::string getID(const Function *F) {
474 return getID(F, "LLVMFunction_");
476 std::string getID(const BasicBlock *BB) {
477 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
479 std::string getID(const GlobalVariable *GV) {
480 return getID(GV, "LLVMGlobal_");
482 std::string getID(const Constant *CV) {
483 return getID(CV, "LLVMConst_", ".C_");
485 std::string getID(const GlobalValue *GV) {
486 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
488 else if (const Function *F = dyn_cast<Function>(GV))
490 assert(0 && "Unexpected type of GlobalValue!");
494 // Combines expressions
495 inline std::string ConstantArithExprToString(const ConstantExpr* CE,
496 const TargetMachine &TM,
497 const std::string &op) {
498 return "(" + valToExprString(CE->getOperand(0), TM) + op
499 + valToExprString(CE->getOperand(1), TM) + ")";
502 // ConstantExprToString() - Convert a ConstantExpr to an asm expression
503 // and return this as a string.
504 std::string ConstantExprToString(const ConstantExpr* CE,
505 const TargetMachine& target) {
507 switch(CE->getOpcode()) {
508 case Instruction::GetElementPtr:
509 { // generate a symbolic expression for the byte address
510 const Value* ptrVal = CE->getOperand(0);
511 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
512 const TargetData &TD = target.getTargetData();
513 S += "(" + valToExprString(ptrVal, target) + ") + ("
514 + utostr(TD.getIndexedOffset(ptrVal->getType(),idxVec)) + ")";
518 case Instruction::Cast:
519 // Support only non-converting casts for now, i.e., a no-op.
520 // This assertion is not a complete check.
521 assert(target.getTargetData().getTypeSize(CE->getType()) ==
522 target.getTargetData().getTypeSize(CE->getOperand(0)->getType()));
523 S += "(" + valToExprString(CE->getOperand(0), target) + ")";
526 case Instruction::Add:
527 S += ConstantArithExprToString(CE, target, ") + (");
530 case Instruction::Sub:
531 S += ConstantArithExprToString(CE, target, ") - (");
534 case Instruction::Mul:
535 S += ConstantArithExprToString(CE, target, ") * (");
538 case Instruction::Div:
539 S += ConstantArithExprToString(CE, target, ") / (");
542 case Instruction::Rem:
543 S += ConstantArithExprToString(CE, target, ") % (");
546 case Instruction::And:
547 // Logical && for booleans; bitwise & otherwise
548 S += ConstantArithExprToString(CE, target,
549 ((CE->getType() == Type::BoolTy)? ") && (" : ") & ("));
552 case Instruction::Or:
553 // Logical || for booleans; bitwise | otherwise
554 S += ConstantArithExprToString(CE, target,
555 ((CE->getType() == Type::BoolTy)? ") || (" : ") | ("));
558 case Instruction::Xor:
559 // Bitwise ^ for all types
560 S += ConstantArithExprToString(CE, target, ") ^ (");
564 assert(0 && "Unsupported operator in ConstantExprToString()");
571 // valToExprString - Helper function for ConstantExprToString().
572 // Appends result to argument string S.
574 std::string valToExprString(const Value* V, const TargetMachine& target) {
577 if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
579 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
580 S += std::string(CB == ConstantBool::True ? "1" : "0");
581 else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
582 S += itostr(CI->getValue());
583 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
584 S += utostr(CI->getValue());
585 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
586 S += ftostr(CFP->getValue());
587 else if (isa<ConstantPointerNull>(CV))
589 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
590 S += valToExprString(CPR->getValue(), target);
591 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
592 S += ConstantExprToString(CE, target);
596 } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
603 assert(0 && "Cannot convert value to string");
604 S += "<illegal-value>";
613 //===----------------------------------------------------------------------===//
614 // SparcFunctionAsmPrinter Code
615 //===----------------------------------------------------------------------===//
617 struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
618 inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
619 : AsmPrinter(os, t) {}
621 const Function *currFunction;
623 const char *getPassName() const {
624 return "Output Sparc Assembly for Functions";
627 virtual bool doInitialization(Module &M) {
632 virtual bool runOnFunction(Function &F) {
640 virtual bool doFinalization(Module &M) {
645 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
646 AU.setPreservesAll();
649 void emitFunction(const Function &F);
651 void emitBasicBlock(const MachineBasicBlock &MBB);
652 void emitMachineInst(const MachineInstr *MI);
654 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
655 void printOneOperand(const MachineOperand &Op, MachineOpCode opCode);
657 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
658 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
660 unsigned getOperandMask(unsigned Opcode) {
663 case V9::SUBcci: return 1 << 3; // Remove CC argument
664 //case BA: return 1 << 0; // Remove Arg #0, which is always null or xcc
665 default: return 0; // By default, don't hack operands...
671 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
672 unsigned int opNum) {
673 switch (MI->getOpCode()) {
686 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
687 unsigned int opNum) {
688 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
690 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
697 #define PrintOp1PlusOp2(mop1, mop2, opCode) \
698 printOneOperand(mop1, opCode); \
700 printOneOperand(mop2, opCode);
703 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
706 const MachineOperand& mop = MI->getOperand(opNum);
708 if (OpIsBranchTargetLabel(MI, opNum))
710 PrintOp1PlusOp2(mop, MI->getOperand(opNum+1), MI->getOpCode());
713 else if (OpIsMemoryAddressBase(MI, opNum))
716 PrintOp1PlusOp2(mop, MI->getOperand(opNum+1), MI->getOpCode());
722 printOneOperand(mop, MI->getOpCode());
728 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &mop,
729 MachineOpCode opCode)
731 bool needBitsFlag = true;
733 if (mop.opHiBits32())
735 else if (mop.opLoBits32())
737 else if (mop.opHiBits64())
739 else if (mop.opLoBits64())
742 needBitsFlag = false;
744 switch (mop.getType())
746 case MachineOperand::MO_VirtualRegister:
747 case MachineOperand::MO_CCRegister:
748 case MachineOperand::MO_MachineRegister:
750 int regNum = (int)mop.getAllocatedRegNum();
752 if (regNum == Target.getRegInfo().getInvalidRegNum()) {
753 // better to print code with NULL registers than to die
754 toAsm << "<NULL VALUE>";
756 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(regNum);
761 case MachineOperand::MO_ConstantPoolIndex:
763 toAsm << ".CPI_" << currFunction->getName()
764 << "_" << mop.getConstantPoolIndex();
768 case MachineOperand::MO_PCRelativeDisp:
770 const Value *Val = mop.getVRegValue();
771 assert(Val && "\tNULL Value in SparcFunctionAsmPrinter");
773 if (const BasicBlock *BB = dyn_cast<BasicBlock>(Val))
775 else if (const Function *M = dyn_cast<Function>(Val))
777 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
779 else if (const Constant *CV = dyn_cast<Constant>(Val))
782 assert(0 && "Unrecognized value in SparcFunctionAsmPrinter");
786 case MachineOperand::MO_SignExtendedImmed:
787 toAsm << mop.getImmedValue();
790 case MachineOperand::MO_UnextendedImmed:
791 toAsm << (uint64_t) mop.getImmedValue();
795 toAsm << mop; // use dump field
804 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
806 unsigned Opcode = MI->getOpCode();
808 if (Target.getInstrInfo().isDummyPhiInstr(Opcode))
809 return; // IGNORE PHI NODES
811 toAsm << "\t" << Target.getInstrInfo().getName(Opcode) << "\t";
813 unsigned Mask = getOperandMask(Opcode);
815 bool NeedComma = false;
817 for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
818 if (! ((1 << OpNum) & Mask)) { // Ignore this operand?
819 if (NeedComma) toAsm << ", "; // Handle comma outputting
821 N = printOperands(MI, OpNum);
830 SparcFunctionAsmPrinter::emitBasicBlock(const MachineBasicBlock &MBB)
832 // Emit a label for the basic block
833 toAsm << getID(MBB.getBasicBlock()) << ":\n";
835 // Loop over all of the instructions in the basic block...
836 for (MachineBasicBlock::const_iterator MII = MBB.begin(), MIE = MBB.end();
838 emitMachineInst(*MII);
839 toAsm << "\n"; // Separate BB's with newlines
843 SparcFunctionAsmPrinter::emitFunction(const Function &F)
845 std::string methName = getID(&F);
846 toAsm << "!****** Outputing Function: " << methName << " ******\n";
848 // Emit constant pool for this function
849 const MachineConstantPool *MCP = MachineFunction::get(&F).getConstantPool();
850 const std::vector<Constant*> &CP = MCP->getConstants();
852 enterSection(AsmPrinter::ReadOnlyData);
853 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
854 std::string cpiName = ".CPI_" + F.getName() + "_" + utostr(i);
855 printConstant(CP[i], cpiName);
858 enterSection(AsmPrinter::Text);
859 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
860 //toAsm << "\t.type\t" << methName << ",#function\n";
861 toAsm << "\t.type\t" << methName << ", 2\n";
862 toAsm << methName << ":\n";
864 // Output code for all of the basic blocks in the function...
865 MachineFunction &MF = MachineFunction::get(&F);
866 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); I != E;++I)
869 // Output a .size directive so the debugger knows the extents of the function
870 toAsm << ".EndOf_" << methName << ":\n\t.size "
871 << methName << ", .EndOf_"
872 << methName << "-" << methName << "\n";
874 // Put some spaces between the functions
878 } // End anonymous namespace
880 Pass *UltraSparc::getFunctionAsmPrinterPass(std::ostream &Out) {
881 return new SparcFunctionAsmPrinter(Out, *this);
888 //===----------------------------------------------------------------------===//
889 // SparcFunctionAsmPrinter Code
890 //===----------------------------------------------------------------------===//
894 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
896 SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
897 : AsmPrinter(os, t) {}
899 const char *getPassName() const { return "Output Sparc Assembly for Module"; }
901 virtual bool run(Module &M) {
908 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
909 AU.setPreservesAll();
913 void emitGlobals(const Module &M);
914 void printGlobalVariable(const GlobalVariable *GV);
917 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
919 if (GV->hasExternalLinkage())
920 toAsm << "\t.global\t" << getID(GV) << "\n";
922 if (GV->hasInitializer() && ! GV->getInitializer()->isNullValue())
923 printConstant(GV->getInitializer(), getID(GV));
925 toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
927 toAsm << "\t.type\t" << getID(GV) << ",#object\n";
928 toAsm << "\t.reserve\t" << getID(GV) << ","
929 << TypeToSize(GV->getType()->getElementType(), Target)
934 void SparcModuleAsmPrinter::emitGlobals(const Module &M) {
935 // Output global variables...
936 for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
937 if (! GI->isExternal()) {
938 assert(GI->hasInitializer());
939 if (GI->isConstant())
940 enterSection(AsmPrinter::ReadOnlyData); // read-only, initialized data
941 else if (GI->getInitializer()->isNullValue())
942 enterSection(AsmPrinter::ZeroInitRWData); // read-write zero data
944 enterSection(AsmPrinter::InitRWData); // read-write non-zero data
946 printGlobalVariable(GI);
952 } // End anonymous namespace
954 Pass *UltraSparc::getModuleAsmPrinterPass(std::ostream &Out) {
955 return new SparcModuleAsmPrinter(Out, *this);