1 //===-- EmitAssembly.cpp - Emit Sparc Specific .s File ---------------------==//
3 // This file implements all of the stuff neccesary to output a .s file from
4 // LLVM. The code in this file assumes that the specified module has already
5 // been compiled into the internal data structures of the Module.
7 // This code largely consists of two LLVM Pass's: a FunctionPass and a Pass.
8 // The FunctionPass is pipelined together with all of the rest of the code
9 // generation stages, and the Pass runs at the end to emit code for global
10 // variables and such.
12 //===----------------------------------------------------------------------===//
14 #include "SparcInternals.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineFunctionInfo.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Module.h"
21 #include "llvm/SlotCalculator.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "Support/StringExtras.h"
29 class GlobalIdTable: public Annotation {
30 static AnnotationID AnnotId;
31 friend class AsmPrinter; // give access to AnnotId
33 typedef hash_map<const Value*, int> ValIdMap;
34 typedef ValIdMap::const_iterator ValIdMapConstIterator;
35 typedef ValIdMap:: iterator ValIdMapIterator;
37 SlotCalculator Table; // map anonymous values to unique integer IDs
38 ValIdMap valToIdMap; // used for values not handled by SlotCalculator
40 GlobalIdTable(Module* M) : Annotation(AnnotId), Table(M, true) {}
43 AnnotationID GlobalIdTable::AnnotId =
44 AnnotationManager::getID("ASM PRINTER GLOBAL TABLE ANNOT");
46 //===---------------------------------------------------------------------===//
47 // Code Shared By the two printer passes, as a mixin
48 //===---------------------------------------------------------------------===//
51 GlobalIdTable* idTable;
54 const TargetMachine &Target;
64 AsmPrinter(std::ostream &os, const TargetMachine &T)
65 : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
67 // (start|end)(Module|Function) - Callback methods to be invoked by subclasses
68 void startModule(Module &M) {
69 // Create the global id table if it does not already exist
70 idTable = (GlobalIdTable*)M.getAnnotation(GlobalIdTable::AnnotId);
71 if (idTable == NULL) {
72 idTable = new GlobalIdTable(&M);
73 M.addAnnotation(idTable);
76 void startFunction(Function &F) {
77 // Make sure the slot table has information about this function...
78 idTable->Table.incorporateFunction(&F);
80 void endFunction(Function &) {
81 idTable->Table.purgeFunction(); // Forget all about F
86 // Check if a value is external or accessible from external code.
87 bool isExternal(const Value* V) {
88 const GlobalValue *GV = dyn_cast<GlobalValue>(V);
89 return GV && GV->hasExternalLinkage();
92 // enterSection - Use this method to enter a different section of the output
93 // executable. This is used to only output neccesary section transitions.
95 void enterSection(enum Sections S) {
96 if (S == CurSection) return; // Only switch section if neccesary
99 toAsm << "\n\t.section ";
102 default: assert(0 && "Bad section name!");
103 case Text: toAsm << "\".text\""; break;
104 case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
105 case InitRWData: toAsm << "\".data\",#alloc,#write"; break;
106 case ZeroInitRWData: toAsm << "\".bss\",#alloc,#write"; break;
111 static string getValidSymbolName(const string &S) {
114 // Symbol names in Sparc assembly language have these rules:
115 // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
116 // (b) A name beginning in "." is treated as a local name.
121 for (unsigned i = 0; i < S.size(); ++i)
124 if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
129 Result += char('0' + ((unsigned char)C >> 4));
130 Result += char('0' + (C & 0xF));
136 // getID - Return a valid identifier for the specified value. Base it on
137 // the name of the identifier if possible (qualified by the type), and
138 // use a numbered value based on prefix otherwise.
139 // FPrefix is always prepended to the output identifier.
141 string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
142 string Result = FPrefix ? FPrefix : ""; // "Forced prefix"
144 Result += V->hasName() ? V->getName() : string(Prefix);
146 // Qualify all internal names with a unique id.
147 if (!isExternal(V)) {
148 int valId = idTable->Table.getValSlot(V);
150 GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
151 if (I == idTable->valToIdMap.end())
152 valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
156 Result = Result + "_" + itostr(valId);
158 // Replace or prefix problem characters in the name
159 Result = getValidSymbolName(Result);
165 // getID Wrappers - Ensure consistent usage...
166 string getID(const Function *F) {
167 return getID(F, "LLVMFunction_");
169 string getID(const BasicBlock *BB) {
170 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
172 string getID(const GlobalVariable *GV) {
173 return getID(GV, "LLVMGlobal_");
175 string getID(const Constant *CV) {
176 return getID(CV, "LLVMConst_", ".C_");
178 string getID(const GlobalValue *GV) {
179 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
181 else if (const Function *F = dyn_cast<Function>(GV))
183 assert(0 && "Unexpected type of GlobalValue!");
187 // ConstantExprToString() - Convert a ConstantExpr to an asm expression
188 // and return this as a string.
189 string ConstantExprToString(const ConstantExpr* CE,
190 const TargetMachine& target) {
192 switch(CE->getOpcode()) {
193 case Instruction::GetElementPtr:
194 { // generate a symbolic expression for the byte address
195 const Value* ptrVal = CE->getOperand(0);
196 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
197 const TargetData &TD = target.getTargetData();
198 S += "(" + valToExprString(ptrVal, target) + ") + ("
199 + utostr(TD.getIndexedOffset(ptrVal->getType(),idxVec)) + ")";
203 case Instruction::Cast:
204 // Support only non-converting casts for now, i.e., a no-op.
205 // This assertion is not a complete check.
206 assert(target.getTargetData().getTypeSize(CE->getType()) ==
207 target.getTargetData().getTypeSize(CE->getOperand(0)->getType()));
208 S += "(" + valToExprString(CE->getOperand(0), target) + ")";
211 case Instruction::Add:
212 S += "(" + valToExprString(CE->getOperand(0), target) + ") + ("
213 + valToExprString(CE->getOperand(1), target) + ")";
217 assert(0 && "Unsupported operator in ConstantExprToString()");
224 // valToExprString - Helper function for ConstantExprToString().
225 // Appends result to argument string S.
227 string valToExprString(const Value* V, const TargetMachine& target) {
230 if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
232 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
233 S += string(CB == ConstantBool::True ? "1" : "0");
234 else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
235 S += itostr(CI->getValue());
236 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
237 S += utostr(CI->getValue());
238 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
239 S += ftostr(CFP->getValue());
240 else if (isa<ConstantPointerNull>(CV))
242 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
243 S += valToExprString(CPR->getValue(), target);
244 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
245 S += ConstantExprToString(CE, target);
249 } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
256 assert(0 && "Cannot convert value to string");
257 S += "<illegal-value>";
266 //===----------------------------------------------------------------------===//
267 // SparcFunctionAsmPrinter Code
268 //===----------------------------------------------------------------------===//
270 struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
271 inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
272 : AsmPrinter(os, t) {}
274 const char *getPassName() const {
275 return "Output Sparc Assembly for Functions";
278 virtual bool doInitialization(Module &M) {
283 virtual bool runOnFunction(Function &F) {
290 virtual bool doFinalization(Module &M) {
295 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
296 AU.setPreservesAll();
299 void emitFunction(const Function &F);
301 void emitBasicBlock(const MachineBasicBlock &MBB);
302 void emitMachineInst(const MachineInstr *MI);
304 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
305 void printOneOperand(const MachineOperand &Op, MachineOpCode opCode);
307 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
308 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
310 unsigned getOperandMask(unsigned Opcode) {
313 case V9::SUBcci: return 1 << 3; // Remove CC argument
314 //case BA: return 1 << 0; // Remove Arg #0, which is always null or xcc
315 default: return 0; // By default, don't hack operands...
321 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
322 unsigned int opNum) {
323 switch (MI->getOpCode()) {
336 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
337 unsigned int opNum) {
338 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
340 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
347 #define PrintOp1PlusOp2(mop1, mop2, opCode) \
348 printOneOperand(mop1, opCode); \
350 printOneOperand(mop2, opCode);
353 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
356 const MachineOperand& mop = MI->getOperand(opNum);
358 if (OpIsBranchTargetLabel(MI, opNum))
360 PrintOp1PlusOp2(mop, MI->getOperand(opNum+1), MI->getOpCode());
363 else if (OpIsMemoryAddressBase(MI, opNum))
366 PrintOp1PlusOp2(mop, MI->getOperand(opNum+1), MI->getOpCode());
372 printOneOperand(mop, MI->getOpCode());
378 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &mop,
379 MachineOpCode opCode)
381 bool needBitsFlag = true;
383 if (mop.opHiBits32())
385 else if (mop.opLoBits32())
387 else if (mop.opHiBits64())
389 else if (mop.opLoBits64())
392 needBitsFlag = false;
394 switch (mop.getType())
396 case MachineOperand::MO_CCRegister:
398 // We need to print %icc or %xcc as %ccr for certain opcodes.
399 int regNum = (int)mop.getAllocatedRegNum();
400 if (regNum != Target.getRegInfo().getInvalidRegNum() &&
401 Target.getRegInfo().getRegClassIDOfReg(regNum)
402 == UltraSparcRegInfo::IntCCRegClassID)
404 if (opCode == V9::RDCCR || opCode == V9::WRCCRi || opCode == V9::WRCCRr)
406 toAsm << "%" << Target.getRegInfo().getMachineRegClass(UltraSparcRegInfo::IntCCRegClassID)->getRegName(SparcIntCCRegClass::ccr);
410 // all other cases can be handled like any other register
413 case MachineOperand::MO_VirtualRegister:
414 case MachineOperand::MO_MachineRegister:
416 int regNum = (int)mop.getAllocatedRegNum();
417 if (regNum == Target.getRegInfo().getInvalidRegNum()) {
418 // better to print code with NULL registers than to die
419 toAsm << "<NULL VALUE>";
421 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(regNum);
426 case MachineOperand::MO_PCRelativeDisp:
428 const Value *Val = mop.getVRegValue();
429 assert(Val && "\tNULL Value in SparcFunctionAsmPrinter");
431 if (const BasicBlock *BB = dyn_cast<const BasicBlock>(Val))
433 else if (const Function *M = dyn_cast<Function>(Val))
435 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
437 else if (const Constant *CV = dyn_cast<Constant>(Val))
440 assert(0 && "Unrecognized value in SparcFunctionAsmPrinter");
444 case MachineOperand::MO_SignExtendedImmed:
445 toAsm << mop.getImmedValue();
448 case MachineOperand::MO_UnextendedImmed:
449 toAsm << (uint64_t) mop.getImmedValue();
453 toAsm << mop; // use dump field
463 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
465 unsigned Opcode = MI->getOpCode();
467 if (Target.getInstrInfo().isDummyPhiInstr(Opcode))
468 return; // IGNORE PHI NODES
470 toAsm << "\t" << Target.getInstrInfo().getName(Opcode) << "\t";
472 unsigned Mask = getOperandMask(Opcode);
474 bool NeedComma = false;
476 for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
477 if (! ((1 << OpNum) & Mask)) { // Ignore this operand?
478 if (NeedComma) toAsm << ", "; // Handle comma outputing
480 N = printOperands(MI, OpNum);
488 SparcFunctionAsmPrinter::emitBasicBlock(const MachineBasicBlock &MBB)
490 // Emit a label for the basic block
491 toAsm << getID(MBB.getBasicBlock()) << ":\n";
493 // Loop over all of the instructions in the basic block...
494 for (MachineBasicBlock::const_iterator MII = MBB.begin(), MIE = MBB.end();
496 emitMachineInst(*MII);
497 toAsm << "\n"; // Seperate BB's with newlines
501 SparcFunctionAsmPrinter::emitFunction(const Function &F)
503 string methName = getID(&F);
504 toAsm << "!****** Outputing Function: " << methName << " ******\n";
505 enterSection(AsmPrinter::Text);
506 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
507 //toAsm << "\t.type\t" << methName << ",#function\n";
508 toAsm << "\t.type\t" << methName << ", 2\n";
509 toAsm << methName << ":\n";
511 // Output code for all of the basic blocks in the function...
512 MachineFunction &MF = MachineFunction::get(&F);
513 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); I != E;++I)
516 // Output a .size directive so the debugger knows the extents of the function
517 toAsm << ".EndOf_" << methName << ":\n\t.size "
518 << methName << ", .EndOf_"
519 << methName << "-" << methName << "\n";
521 // Put some spaces between the functions
525 } // End anonymous namespace
527 Pass *UltraSparc::getFunctionAsmPrinterPass(std::ostream &Out) {
528 return new SparcFunctionAsmPrinter(Out, *this);
535 //===----------------------------------------------------------------------===//
536 // SparcFunctionAsmPrinter Code
537 //===----------------------------------------------------------------------===//
541 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
543 SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
544 : AsmPrinter(os, t) {}
546 const char *getPassName() const { return "Output Sparc Assembly for Module"; }
548 virtual bool run(Module &M) {
550 emitGlobalsAndConstants(M);
555 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
556 AU.setPreservesAll();
560 void emitGlobalsAndConstants (const Module &M);
562 void printGlobalVariable (const GlobalVariable *GV);
563 void PrintZeroBytesToPad (int numBytes);
564 void printSingleConstantValue (const Constant* CV);
565 void printConstantValueOnly (const Constant* CV, int numPadBytesAfter = 0);
566 void printConstant (const Constant* CV, string valID = "");
568 static void FoldConstants (const Module &M,
569 hash_set<const Constant*> &moduleConstants);
573 // Can we treat the specified array as a string? Only if it is an array of
574 // ubytes or non-negative sbytes.
576 static bool isStringCompatible(const ConstantArray *CVA) {
577 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
578 if (ETy == Type::UByteTy) return true;
579 if (ETy != Type::SByteTy) return false;
581 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
582 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
588 // toOctal - Convert the low order bits of X into an octal letter
589 static inline char toOctal(int X) {
593 // getAsCString - Return the specified array as a C compatible string, only if
594 // the predicate isStringCompatible is true.
596 static string getAsCString(const ConstantArray *CVA) {
597 assert(isStringCompatible(CVA) && "Array is not string compatible!");
600 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
602 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
603 unsigned char C = (ETy == Type::SByteTy) ?
604 (unsigned char)cast<ConstantSInt>(CVA->getOperand(i))->getValue() :
605 (unsigned char)cast<ConstantUInt>(CVA->getOperand(i))->getValue();
609 } else if (C == '\\') {
611 } else if (isprint(C)) {
615 case '\a': Result += "\\a"; break;
616 case '\b': Result += "\\b"; break;
617 case '\f': Result += "\\f"; break;
618 case '\n': Result += "\\n"; break;
619 case '\r': Result += "\\r"; break;
620 case '\t': Result += "\\t"; break;
621 case '\v': Result += "\\v"; break;
624 Result += toOctal(C >> 6);
625 Result += toOctal(C >> 3);
626 Result += toOctal(C >> 0);
637 ArrayTypeIsString(const ArrayType* arrayType)
639 return (arrayType->getElementType() == Type::UByteTy ||
640 arrayType->getElementType() == Type::SByteTy);
645 TypeToDataDirective(const Type* type)
647 switch(type->getPrimitiveID())
649 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
651 case Type::UShortTyID: case Type::ShortTyID:
653 case Type::UIntTyID: case Type::IntTyID:
655 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
657 case Type::FloatTyID:
659 case Type::DoubleTyID:
661 case Type::ArrayTyID:
662 if (ArrayTypeIsString((ArrayType*) type))
665 return "<InvaliDataTypeForPrinting>";
667 return "<InvaliDataTypeForPrinting>";
671 // Get the size of the type
674 TypeToSize(const Type* type, const TargetMachine& target)
676 return target.findOptimalStorageSize(type);
679 // Get the size of the constant for the given target.
680 // If this is an unsized array, return 0.
683 ConstantToSize(const Constant* CV, const TargetMachine& target)
685 if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
687 const ArrayType *aty = cast<ArrayType>(CVA->getType());
688 if (ArrayTypeIsString(aty))
689 return 1 + CVA->getNumOperands();
692 return TypeToSize(CV->getType(), target);
695 // Align data larger than one L1 cache line on L1 cache line boundaries.
696 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
699 SizeToAlignment(unsigned int size, const TargetMachine& target)
701 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
702 if (size > (unsigned) cacheLineSize / 2)
703 return cacheLineSize;
705 for (unsigned sz=1; /*no condition*/; sz *= 2)
710 // Get the size of the type and then use SizeToAlignment.
713 TypeToAlignment(const Type* type, const TargetMachine& target)
715 return SizeToAlignment(TypeToSize(type, target), target);
718 // Get the size of the constant and then use SizeToAlignment.
719 // Handles strings as a special case;
721 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
723 if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
724 if (ArrayTypeIsString(cast<ArrayType>(CVA->getType())))
725 return SizeToAlignment(1 + CVA->getNumOperands(), target);
727 return TypeToAlignment(CV->getType(), target);
731 // Print a single constant value.
733 SparcModuleAsmPrinter::printSingleConstantValue(const Constant* CV)
735 assert(CV->getType() != Type::VoidTy &&
736 CV->getType() != Type::TypeTy &&
737 CV->getType() != Type::LabelTy &&
738 "Unexpected type for Constant");
740 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
741 && "Aggregate types should be handled outside this function");
743 toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
745 if (CV->getType()->isPrimitiveType())
747 if (CV->getType()->isFloatingPoint()) {
748 // FP Constants are printed as integer constants to avoid losing
750 double Val = cast<ConstantFP>(CV)->getValue();
751 if (CV->getType() == Type::FloatTy) {
752 float FVal = (float)Val;
753 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
754 toAsm << *(unsigned int*)ProxyPtr;
755 } else if (CV->getType() == Type::DoubleTy) {
756 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
757 toAsm << *(uint64_t*)ProxyPtr;
759 assert(0 && "Unknown floating point type!");
762 toAsm << "\t! " << CV->getType()->getDescription()
763 << " value: " << Val << "\n";
765 WriteAsOperand(toAsm, CV, false, false) << "\n";
768 else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
769 { // This is a constant address for a global variable or method.
770 // Use the name of the variable or method as the address value.
771 toAsm << getID(CPR->getValue()) << "\n";
773 else if (isa<ConstantPointerNull>(CV))
774 { // Null pointer value
777 else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
778 { // Constant expression built from operators, constants, and symbolic addrs
779 toAsm << ConstantExprToString(CE, Target) << "\n";
783 assert(0 && "Unknown elementary type for constant");
788 SparcModuleAsmPrinter::PrintZeroBytesToPad(int numBytes)
790 for ( ; numBytes >= 8; numBytes -= 8)
791 printSingleConstantValue(Constant::getNullValue(Type::ULongTy));
795 printSingleConstantValue(Constant::getNullValue(Type::UIntTy));
800 printSingleConstantValue(Constant::getNullValue(Type::UByteTy));
803 // Print a constant value or values (it may be an aggregate).
804 // Uses printSingleConstantValue() to print each individual value.
806 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV,
807 int numPadBytesAfter /* = 0*/)
809 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
811 if (CVA && isStringCompatible(CVA))
812 { // print the string alone and return
813 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
816 { // Not a string. Print the values in successive locations
817 const std::vector<Use> &constValues = CVA->getValues();
818 for (unsigned i=0; i < constValues.size(); i++)
819 printConstantValueOnly(cast<Constant>(constValues[i].get()));
821 else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
822 { // Print the fields in successive locations. Pad to align if needed!
823 const StructLayout *cvsLayout =
824 Target.getTargetData().getStructLayout(CVS->getType());
825 const std::vector<Use>& constValues = CVS->getValues();
826 unsigned sizeSoFar = 0;
827 for (unsigned i=0, N = constValues.size(); i < N; i++)
829 const Constant* field = cast<Constant>(constValues[i].get());
831 // Check if padding is needed and insert one or more 0s.
833 Target.getTargetData().getTypeSize(field->getType());
834 int padSize = ((i == N-1? cvsLayout->StructSize
835 : cvsLayout->MemberOffsets[i+1])
836 - cvsLayout->MemberOffsets[i]) - fieldSize;
837 sizeSoFar += (fieldSize + padSize);
839 // Now print the actual field value
840 printConstantValueOnly(field, padSize);
842 assert(sizeSoFar == cvsLayout->StructSize &&
843 "Layout of constant struct may be incorrect!");
846 printSingleConstantValue(CV);
848 if (numPadBytesAfter)
849 PrintZeroBytesToPad(numPadBytesAfter);
852 // Print a constant (which may be an aggregate) prefixed by all the
853 // appropriate directives. Uses printConstantValueOnly() to print the
856 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
858 if (valID.length() == 0)
861 toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
863 // Print .size and .type only if it is not a string.
864 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
865 if (CVA && isStringCompatible(CVA))
866 { // print it as a string and return
867 toAsm << valID << ":\n";
868 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
872 toAsm << "\t.type" << "\t" << valID << ",#object\n";
874 unsigned int constSize = ConstantToSize(CV, Target);
876 toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
878 toAsm << valID << ":\n";
880 printConstantValueOnly(CV);
884 void SparcModuleAsmPrinter::FoldConstants(const Module &M,
885 hash_set<const Constant*> &MC) {
886 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
887 if (!I->isExternal()) {
888 const hash_set<const Constant*> &pool =
889 MachineFunction::get(I).getInfo()->getConstantPoolValues();
890 MC.insert(pool.begin(), pool.end());
894 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
896 if (GV->hasExternalLinkage())
897 toAsm << "\t.global\t" << getID(GV) << "\n";
899 if (GV->hasInitializer() && ! GV->getInitializer()->isNullValue())
900 printConstant(GV->getInitializer(), getID(GV));
902 toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
904 toAsm << "\t.type\t" << getID(GV) << ",#object\n";
905 toAsm << "\t.reserve\t" << getID(GV) << ","
906 << TypeToSize(GV->getType()->getElementType(), Target)
912 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module &M) {
913 // First, get the constants there were marked by the code generator for
914 // inclusion in the assembly code data area and fold them all into a
915 // single constant pool since there may be lots of duplicates. Also,
916 // lets force these constants into the slot table so that we can get
917 // unique names for unnamed constants also.
919 hash_set<const Constant*> moduleConstants;
920 FoldConstants(M, moduleConstants);
922 // Output constants spilled to memory
923 enterSection(AsmPrinter::ReadOnlyData);
924 for (hash_set<const Constant*>::const_iterator I = moduleConstants.begin(),
925 E = moduleConstants.end(); I != E; ++I)
928 // Output global variables...
929 for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
930 if (! GI->isExternal()) {
931 assert(GI->hasInitializer());
932 if (GI->isConstant())
933 enterSection(AsmPrinter::ReadOnlyData); // read-only, initialized data
934 else if (GI->getInitializer()->isNullValue())
935 enterSection(AsmPrinter::ZeroInitRWData); // read-write zero data
937 enterSection(AsmPrinter::InitRWData); // read-write non-zero data
939 printGlobalVariable(GI);
945 } // End anonymous namespace
947 Pass *UltraSparc::getModuleAsmPrinterPass(std::ostream &Out) {
948 return new SparcModuleAsmPrinter(Out, *this);