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/MachineCodeForBasicBlock.h"
17 #include "llvm/CodeGen/MachineCodeForMethod.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);
159 return getValidSymbolName(Result);
162 // getID Wrappers - Ensure consistent usage...
163 string getID(const Function *F) {
164 return getID(F, "LLVMFunction_");
166 string getID(const BasicBlock *BB) {
167 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
169 string getID(const GlobalVariable *GV) {
170 return getID(GV, "LLVMGlobal_");
172 string getID(const Constant *CV) {
173 return getID(CV, "LLVMConst_", ".C_");
175 string getID(const GlobalValue *GV) {
176 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
178 else if (const Function *F = dyn_cast<Function>(GV))
180 assert(0 && "Unexpected type of GlobalValue!");
184 // ConstantExprToString() - Convert a ConstantExpr to an asm expression
185 // and return this as a string.
186 string ConstantExprToString(const ConstantExpr* CE,
187 const TargetMachine& target) {
189 switch(CE->getOpcode()) {
190 case Instruction::GetElementPtr:
191 { // generate a symbolic expression for the byte address
192 const Value* ptrVal = CE->getOperand(0);
193 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
194 S += "(" + valToExprString(ptrVal, target) + ") + ("
195 + utostr(target.DataLayout.getIndexedOffset(ptrVal->getType(),idxVec))
200 case Instruction::Cast:
201 // Support only non-converting casts for now, i.e., a no-op.
202 // This assertion is not a complete check.
203 assert(target.DataLayout.getTypeSize(CE->getType()) ==
204 target.DataLayout.getTypeSize(CE->getOperand(0)->getType()));
205 S += "(" + valToExprString(CE->getOperand(0), target) + ")";
208 case Instruction::Add:
209 S += "(" + valToExprString(CE->getOperand(0), target) + ") + ("
210 + valToExprString(CE->getOperand(1), target) + ")";
214 assert(0 && "Unsupported operator in ConstantExprToString()");
221 // valToExprString - Helper function for ConstantExprToString().
222 // Appends result to argument string S.
224 string valToExprString(const Value* V, const TargetMachine& target) {
227 if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
229 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
230 S += string(CB == ConstantBool::True ? "1" : "0");
231 else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
232 S += itostr(CI->getValue());
233 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
234 S += utostr(CI->getValue());
235 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
236 S += ftostr(CFP->getValue());
237 else if (isa<ConstantPointerNull>(CV))
239 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
240 S += valToExprString(CPR->getValue(), target);
241 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
242 S += ConstantExprToString(CE, target);
246 } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
253 assert(0 && "Cannot convert value to string");
254 S += "<illegal-value>";
263 //===----------------------------------------------------------------------===//
264 // SparcFunctionAsmPrinter Code
265 //===----------------------------------------------------------------------===//
267 struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
268 inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
269 : AsmPrinter(os, t) {}
271 const char *getPassName() const {
272 return "Output Sparc Assembly for Functions";
275 virtual bool doInitialization(Module &M) {
280 virtual bool runOnFunction(Function &F) {
287 virtual bool doFinalization(Module &M) {
292 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
293 AU.setPreservesAll();
296 void emitFunction(const Function &F);
298 void emitBasicBlock(const BasicBlock *BB);
299 void emitMachineInst(const MachineInstr *MI);
301 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
302 void printOneOperand(const MachineOperand &Op);
304 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
305 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
307 unsigned getOperandMask(unsigned Opcode) {
309 case SUBcc: return 1 << 3; // Remove CC argument
310 //case BA: return 1 << 0; // Remove Arg #0, which is always null or xcc
311 default: return 0; // By default, don't hack operands...
317 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
318 unsigned int opNum) {
319 switch (MI->getOpCode()) {
321 case JMPLRET: return (opNum == 0);
322 default: return false;
328 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
329 unsigned int opNum) {
330 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
332 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
339 #define PrintOp1PlusOp2(mop1, mop2) \
340 printOneOperand(mop1); \
342 printOneOperand(mop2);
345 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
348 const MachineOperand& mop = MI->getOperand(opNum);
350 if (OpIsBranchTargetLabel(MI, opNum))
352 PrintOp1PlusOp2(mop, MI->getOperand(opNum+1));
355 else if (OpIsMemoryAddressBase(MI, opNum))
358 PrintOp1PlusOp2(mop, MI->getOperand(opNum+1));
364 printOneOperand(mop);
371 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &mop)
373 bool needBitsFlag = true;
375 if (mop.opHiBits32())
377 else if (mop.opLoBits32())
379 else if (mop.opHiBits64())
381 else if (mop.opLoBits64())
384 needBitsFlag = false;
386 switch (mop.getOperandType())
388 case MachineOperand::MO_VirtualRegister:
389 case MachineOperand::MO_CCRegister:
390 case MachineOperand::MO_MachineRegister:
392 int RegNum = (int)mop.getAllocatedRegNum();
394 // better to print code with NULL registers than to die
395 if (RegNum == Target.getRegInfo().getInvalidRegNum()) {
396 toAsm << "<NULL VALUE>";
398 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
403 case MachineOperand::MO_PCRelativeDisp:
405 const Value *Val = mop.getVRegValue();
406 assert(Val && "\tNULL Value in SparcFunctionAsmPrinter");
408 if (const BasicBlock *BB = dyn_cast<const BasicBlock>(Val))
410 else if (const Function *M = dyn_cast<Function>(Val))
412 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
414 else if (const Constant *CV = dyn_cast<Constant>(Val))
417 assert(0 && "Unrecognized value in SparcFunctionAsmPrinter");
421 case MachineOperand::MO_SignExtendedImmed:
422 toAsm << mop.getImmedValue();
425 case MachineOperand::MO_UnextendedImmed:
426 toAsm << (uint64_t) mop.getImmedValue();
430 toAsm << mop; // use dump field
440 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
442 unsigned Opcode = MI->getOpCode();
444 if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
445 return; // IGNORE PHI NODES
447 toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
449 unsigned Mask = getOperandMask(Opcode);
451 bool NeedComma = false;
453 for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
454 if (! ((1 << OpNum) & Mask)) { // Ignore this operand?
455 if (NeedComma) toAsm << ", "; // Handle comma outputing
457 N = printOperands(MI, OpNum);
466 SparcFunctionAsmPrinter::emitBasicBlock(const BasicBlock *BB)
468 // Emit a label for the basic block
469 toAsm << getID(BB) << ":\n";
471 // Get the vector of machine instructions corresponding to this bb.
472 const MachineCodeForBasicBlock &MIs = MachineCodeForBasicBlock::get(BB);
473 MachineCodeForBasicBlock::const_iterator MII = MIs.begin(), MIE = MIs.end();
475 // Loop over all of the instructions in the basic block...
476 for (; MII != MIE; ++MII)
477 emitMachineInst(*MII);
478 toAsm << "\n"; // Seperate BB's with newlines
482 SparcFunctionAsmPrinter::emitFunction(const Function &F)
484 string methName = getID(&F);
485 toAsm << "!****** Outputing Function: " << methName << " ******\n";
486 enterSection(AsmPrinter::Text);
487 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
488 //toAsm << "\t.type\t" << methName << ",#function\n";
489 toAsm << "\t.type\t" << methName << ", 2\n";
490 toAsm << methName << ":\n";
492 // Output code for all of the basic blocks in the function...
493 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I)
496 // Output a .size directive so the debugger knows the extents of the function
497 toAsm << ".EndOf_" << methName << ":\n\t.size "
498 << methName << ", .EndOf_"
499 << methName << "-" << methName << "\n";
501 // Put some spaces between the functions
505 } // End anonymous namespace
507 Pass *UltraSparc::getFunctionAsmPrinterPass(std::ostream &Out) {
508 return new SparcFunctionAsmPrinter(Out, *this);
515 //===----------------------------------------------------------------------===//
516 // SparcFunctionAsmPrinter Code
517 //===----------------------------------------------------------------------===//
521 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
523 SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
524 : AsmPrinter(os, t) {}
526 const char *getPassName() const { return "Output Sparc Assembly for Module"; }
528 virtual bool run(Module &M) {
530 emitGlobalsAndConstants(M);
535 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
536 AU.setPreservesAll();
540 void emitGlobalsAndConstants (const Module &M);
542 void printGlobalVariable (const GlobalVariable *GV);
543 void PrintZeroBytesToPad (int numBytes);
544 void printSingleConstantValue (const Constant* CV);
545 void printConstantValueOnly (const Constant* CV, int numPadBytes = 0);
546 void printConstant (const Constant* CV, string valID = "");
548 static void FoldConstants (const Module &M,
549 hash_set<const Constant*> &moduleConstants);
553 // Can we treat the specified array as a string? Only if it is an array of
554 // ubytes or non-negative sbytes.
556 static bool isStringCompatible(const ConstantArray *CVA) {
557 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
558 if (ETy == Type::UByteTy) return true;
559 if (ETy != Type::SByteTy) return false;
561 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
562 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
568 // toOctal - Convert the low order bits of X into an octal letter
569 static inline char toOctal(int X) {
573 // getAsCString - Return the specified array as a C compatible string, only if
574 // the predicate isStringCompatible is true.
576 static string getAsCString(const ConstantArray *CVA) {
577 assert(isStringCompatible(CVA) && "Array is not string compatible!");
580 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
582 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
583 unsigned char C = (ETy == Type::SByteTy) ?
584 (unsigned char)cast<ConstantSInt>(CVA->getOperand(i))->getValue() :
585 (unsigned char)cast<ConstantUInt>(CVA->getOperand(i))->getValue();
589 } else if (isprint(C)) {
593 case '\a': Result += "\\a"; break;
594 case '\b': Result += "\\b"; break;
595 case '\f': Result += "\\f"; break;
596 case '\n': Result += "\\n"; break;
597 case '\r': Result += "\\r"; break;
598 case '\t': Result += "\\t"; break;
599 case '\v': Result += "\\v"; break;
602 Result += toOctal(C >> 6);
603 Result += toOctal(C >> 3);
604 Result += toOctal(C >> 0);
615 ArrayTypeIsString(const ArrayType* arrayType)
617 return (arrayType->getElementType() == Type::UByteTy ||
618 arrayType->getElementType() == Type::SByteTy);
623 TypeToDataDirective(const Type* type)
625 switch(type->getPrimitiveID())
627 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
629 case Type::UShortTyID: case Type::ShortTyID:
631 case Type::UIntTyID: case Type::IntTyID:
633 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
635 case Type::FloatTyID:
637 case Type::DoubleTyID:
639 case Type::ArrayTyID:
640 if (ArrayTypeIsString((ArrayType*) type))
643 return "<InvaliDataTypeForPrinting>";
645 return "<InvaliDataTypeForPrinting>";
649 // Get the size of the type
652 TypeToSize(const Type* type, const TargetMachine& target)
654 return target.findOptimalStorageSize(type);
657 // Get the size of the constant for the given target.
658 // If this is an unsized array, return 0.
661 ConstantToSize(const Constant* CV, const TargetMachine& target)
663 if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
665 const ArrayType *aty = cast<ArrayType>(CVA->getType());
666 if (ArrayTypeIsString(aty))
667 return 1 + CVA->getNumOperands();
670 return TypeToSize(CV->getType(), target);
673 // Align data larger than one L1 cache line on L1 cache line boundaries.
674 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
677 SizeToAlignment(unsigned int size, const TargetMachine& target)
679 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
680 if (size > (unsigned) cacheLineSize / 2)
681 return cacheLineSize;
683 for (unsigned sz=1; /*no condition*/; sz *= 2)
688 // Get the size of the type and then use SizeToAlignment.
691 TypeToAlignment(const Type* type, const TargetMachine& target)
693 return SizeToAlignment(TypeToSize(type, target), target);
696 // Get the size of the constant and then use SizeToAlignment.
697 // Handles strings as a special case;
699 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
701 if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
702 if (ArrayTypeIsString(cast<ArrayType>(CVA->getType())))
703 return SizeToAlignment(1 + CVA->getNumOperands(), target);
705 return TypeToAlignment(CV->getType(), target);
709 // Print a single constant value.
711 SparcModuleAsmPrinter::printSingleConstantValue(const Constant* CV)
713 assert(CV->getType() != Type::VoidTy &&
714 CV->getType() != Type::TypeTy &&
715 CV->getType() != Type::LabelTy &&
716 "Unexpected type for Constant");
718 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
719 && "Aggregate types should be handled outside this function");
721 toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
723 if (CV->getType()->isPrimitiveType())
725 if (CV->getType()->isFloatingPoint()) {
726 // FP Constants are printed as integer constants to avoid losing
728 double Val = cast<ConstantFP>(CV)->getValue();
729 if (CV->getType() == Type::FloatTy) {
730 float FVal = (float)Val;
731 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
732 toAsm << *(unsigned int*)ProxyPtr;
733 } else if (CV->getType() == Type::DoubleTy) {
734 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
735 toAsm << *(uint64_t*)ProxyPtr;
737 assert(0 && "Unknown floating point type!");
740 toAsm << "\t! " << CV->getType()->getDescription()
741 << " value: " << Val << "\n";
743 WriteAsOperand(toAsm, CV, false, false) << "\n";
746 else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
747 { // This is a constant address for a global variable or method.
748 // Use the name of the variable or method as the address value.
749 toAsm << getID(CPR->getValue()) << "\n";
751 else if (isa<ConstantPointerNull>(CV))
752 { // Null pointer value
755 else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
756 { // Constant expression built from operators, constants, and symbolic addrs
757 toAsm << ConstantExprToString(CE, Target) << "\n";
761 assert(0 && "Unknown elementary type for constant");
766 SparcModuleAsmPrinter::PrintZeroBytesToPad(int numBytes)
768 for ( ; numBytes >= 8; numBytes -= 8)
769 printSingleConstantValue(Constant::getNullValue(Type::ULongTy));
773 printSingleConstantValue(Constant::getNullValue(Type::UIntTy));
778 printSingleConstantValue(Constant::getNullValue(Type::UByteTy));
781 // Print a constant value or values (it may be an aggregate).
782 // Uses printSingleConstantValue() to print each individual value.
784 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV,
785 int numPadBytes /* = 0*/)
787 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
790 PrintZeroBytesToPad(numPadBytes);
792 if (CVA && isStringCompatible(CVA))
793 { // print the string alone and return
794 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
797 { // Not a string. Print the values in successive locations
798 const std::vector<Use> &constValues = CVA->getValues();
799 for (unsigned i=0; i < constValues.size(); i++)
800 printConstantValueOnly(cast<Constant>(constValues[i].get()));
802 else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
803 { // Print the fields in successive locations. Pad to align if needed!
804 const StructLayout *cvsLayout =
805 Target.DataLayout.getStructLayout(CVS->getType());
806 const std::vector<Use>& constValues = CVS->getValues();
807 unsigned sizeSoFar = 0;
808 for (unsigned i=0, N = constValues.size(); i < N; i++)
810 const Constant* field = cast<Constant>(constValues[i].get());
812 // Check if padding is needed and insert one or more 0s.
813 unsigned fieldSize = Target.DataLayout.getTypeSize(field->getType());
814 int padSize = ((i == N-1? cvsLayout->StructSize
815 : cvsLayout->MemberOffsets[i+1])
816 - cvsLayout->MemberOffsets[i]) - fieldSize;
817 sizeSoFar += (fieldSize + padSize);
819 // Now print the actual field value
820 printConstantValueOnly(field, padSize);
822 assert(sizeSoFar == cvsLayout->StructSize &&
823 "Layout of constant struct may be incorrect!");
826 printSingleConstantValue(CV);
829 // Print a constant (which may be an aggregate) prefixed by all the
830 // appropriate directives. Uses printConstantValueOnly() to print the
833 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
835 if (valID.length() == 0)
838 toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
840 // Print .size and .type only if it is not a string.
841 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
842 if (CVA && isStringCompatible(CVA))
843 { // print it as a string and return
844 toAsm << valID << ":\n";
845 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
849 toAsm << "\t.type" << "\t" << valID << ",#object\n";
851 unsigned int constSize = ConstantToSize(CV, Target);
853 toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
855 toAsm << valID << ":\n";
857 printConstantValueOnly(CV);
861 void SparcModuleAsmPrinter::FoldConstants(const Module &M,
862 hash_set<const Constant*> &MC) {
863 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
864 if (!I->isExternal()) {
865 const hash_set<const Constant*> &pool =
866 MachineCodeForMethod::get(I).getConstantPoolValues();
867 MC.insert(pool.begin(), pool.end());
871 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
873 if (GV->hasExternalLinkage())
874 toAsm << "\t.global\t" << getID(GV) << "\n";
876 if (GV->hasInitializer() && ! GV->getInitializer()->isNullValue())
877 printConstant(GV->getInitializer(), getID(GV));
879 toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
881 toAsm << "\t.type\t" << getID(GV) << ",#object\n";
882 toAsm << "\t.reserve\t" << getID(GV) << ","
883 << TypeToSize(GV->getType()->getElementType(), Target)
889 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module &M) {
890 // First, get the constants there were marked by the code generator for
891 // inclusion in the assembly code data area and fold them all into a
892 // single constant pool since there may be lots of duplicates. Also,
893 // lets force these constants into the slot table so that we can get
894 // unique names for unnamed constants also.
896 hash_set<const Constant*> moduleConstants;
897 FoldConstants(M, moduleConstants);
899 // Output constants spilled to memory
900 enterSection(AsmPrinter::ReadOnlyData);
901 for (hash_set<const Constant*>::const_iterator I = moduleConstants.begin(),
902 E = moduleConstants.end(); I != E; ++I)
905 // Output global variables...
906 for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
907 if (! GI->isExternal()) {
908 assert(GI->hasInitializer());
909 if (GI->isConstant())
910 enterSection(AsmPrinter::ReadOnlyData); // read-only, initialized data
911 else if (GI->getInitializer()->isNullValue())
912 enterSection(AsmPrinter::ZeroInitRWData); // read-write zero data
914 enterSection(AsmPrinter::InitRWData); // read-write non-zero data
916 printGlobalVariable(GI);
922 } // End anonymous namespace
924 Pass *UltraSparc::getModuleAsmPrinterPass(std::ostream &Out) {
925 return new SparcModuleAsmPrinter(Out, *this);