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/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/SlotCalculator.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Assembly/Writer.h"
23 #include "Support/StringExtras.h"
28 class GlobalIdTable: public Annotation {
29 static AnnotationID AnnotId;
30 friend class AsmPrinter; // give access to AnnotId
32 typedef hash_map<const Value*, int> ValIdMap;
33 typedef ValIdMap::const_iterator ValIdMapConstIterator;
34 typedef ValIdMap:: iterator ValIdMapIterator;
36 SlotCalculator Table; // map anonymous values to unique integer IDs
37 ValIdMap valToIdMap; // used for values not handled by SlotCalculator
39 GlobalIdTable(Module* M) : Annotation(AnnotId), Table(M, true) {}
42 AnnotationID GlobalIdTable::AnnotId =
43 AnnotationManager::getID("ASM PRINTER GLOBAL TABLE ANNOT");
45 //===---------------------------------------------------------------------===//
46 // Code Shared By the two printer passes, as a mixin
47 //===---------------------------------------------------------------------===//
50 GlobalIdTable* idTable;
53 const TargetMachine &Target;
63 AsmPrinter(std::ostream &os, const TargetMachine &T)
64 : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
66 // (start|end)(Module|Function) - Callback methods to be invoked by subclasses
67 void startModule(Module &M) {
68 // Create the global id table if it does not already exist
69 idTable = (GlobalIdTable*)M.getAnnotation(GlobalIdTable::AnnotId);
70 if (idTable == NULL) {
71 idTable = new GlobalIdTable(&M);
72 M.addAnnotation(idTable);
75 void startFunction(Function &F) {
76 // Make sure the slot table has information about this function...
77 idTable->Table.incorporateFunction(&F);
79 void endFunction(Function &) {
80 idTable->Table.purgeFunction(); // Forget all about F
85 // Check if a value is external or accessible from external code.
86 bool isExternal(const Value* V) {
87 const GlobalValue *GV = dyn_cast<GlobalValue>(V);
88 return GV && GV->hasExternalLinkage();
91 // enterSection - Use this method to enter a different section of the output
92 // executable. This is used to only output neccesary section transitions.
94 void enterSection(enum Sections S) {
95 if (S == CurSection) return; // Only switch section if neccesary
98 toAsm << "\n\t.section ";
101 default: assert(0 && "Bad section name!");
102 case Text: toAsm << "\".text\""; break;
103 case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
104 case InitRWData: toAsm << "\".data\",#alloc,#write"; break;
105 case ZeroInitRWData: toAsm << "\".bss\",#alloc,#write"; break;
110 static string getValidSymbolName(const string &S) {
113 // Symbol names in Sparc assembly language have these rules:
114 // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
115 // (b) A name beginning in "." is treated as a local name.
120 for (unsigned i = 0; i < S.size(); ++i)
123 if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
128 Result += char('0' + ((unsigned char)C >> 4));
129 Result += char('0' + (C & 0xF));
135 // getID - Return a valid identifier for the specified value. Base it on
136 // the name of the identifier if possible (qualified by the type), and
137 // use a numbered value based on prefix otherwise.
138 // FPrefix is always prepended to the output identifier.
140 string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
141 string Result = FPrefix ? FPrefix : ""; // "Forced prefix"
143 Result += V->hasName() ? V->getName() : string(Prefix);
145 // Qualify all internal names with a unique id.
146 if (!isExternal(V)) {
147 int valId = idTable->Table.getValSlot(V);
149 GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
150 if (I == idTable->valToIdMap.end())
151 valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
155 Result = Result + "_" + itostr(valId);
157 // Replace or prefix problem characters in the name
158 Result = getValidSymbolName(Result);
164 // getID Wrappers - Ensure consistent usage...
165 string getID(const Function *F) {
166 return getID(F, "LLVMFunction_");
168 string getID(const BasicBlock *BB) {
169 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
171 string getID(const GlobalVariable *GV) {
172 return getID(GV, "LLVMGlobal_");
174 string getID(const Constant *CV) {
175 return getID(CV, "LLVMConst_", ".C_");
177 string getID(const GlobalValue *GV) {
178 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
180 else if (const Function *F = dyn_cast<Function>(GV))
182 assert(0 && "Unexpected type of GlobalValue!");
186 // ConstantExprToString() - Convert a ConstantExpr to an asm expression
187 // and return this as a string.
188 string ConstantExprToString(const ConstantExpr* CE,
189 const TargetMachine& target) {
191 switch(CE->getOpcode()) {
192 case Instruction::GetElementPtr:
193 { // generate a symbolic expression for the byte address
194 const Value* ptrVal = CE->getOperand(0);
195 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
196 S += "(" + valToExprString(ptrVal, target) + ") + ("
197 + utostr(target.DataLayout.getIndexedOffset(ptrVal->getType(),idxVec))
202 case Instruction::Cast:
203 // Support only non-converting casts for now, i.e., a no-op.
204 // This assertion is not a complete check.
205 assert(target.DataLayout.getTypeSize(CE->getType()) ==
206 target.DataLayout.getTypeSize(CE->getOperand(0)->getType()));
207 S += "(" + valToExprString(CE->getOperand(0), target) + ")";
210 case Instruction::Add:
211 S += "(" + valToExprString(CE->getOperand(0), target) + ") + ("
212 + valToExprString(CE->getOperand(1), target) + ")";
216 assert(0 && "Unsupported operator in ConstantExprToString()");
223 // valToExprString - Helper function for ConstantExprToString().
224 // Appends result to argument string S.
226 string valToExprString(const Value* V, const TargetMachine& target) {
229 if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
231 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
232 S += string(CB == ConstantBool::True ? "1" : "0");
233 else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
234 S += itostr(CI->getValue());
235 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
236 S += utostr(CI->getValue());
237 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
238 S += ftostr(CFP->getValue());
239 else if (isa<ConstantPointerNull>(CV))
241 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
242 S += valToExprString(CPR->getValue(), target);
243 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
244 S += ConstantExprToString(CE, target);
248 } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
255 assert(0 && "Cannot convert value to string");
256 S += "<illegal-value>";
265 //===----------------------------------------------------------------------===//
266 // SparcFunctionAsmPrinter Code
267 //===----------------------------------------------------------------------===//
269 struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
270 inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
271 : AsmPrinter(os, t) {}
273 const char *getPassName() const {
274 return "Output Sparc Assembly for Functions";
277 virtual bool doInitialization(Module &M) {
282 virtual bool runOnFunction(Function &F) {
289 virtual bool doFinalization(Module &M) {
294 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
295 AU.setPreservesAll();
298 void emitFunction(const Function &F);
300 void emitBasicBlock(const MachineBasicBlock &MBB);
301 void emitMachineInst(const MachineInstr *MI);
303 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
304 void printOneOperand(const MachineOperand &Op);
306 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
307 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
309 unsigned getOperandMask(unsigned Opcode) {
311 case SUBcc: return 1 << 3; // Remove CC argument
312 //case BA: return 1 << 0; // Remove Arg #0, which is always null or xcc
313 default: return 0; // By default, don't hack operands...
319 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
320 unsigned int opNum) {
321 switch (MI->getOpCode()) {
323 case JMPLRET: return (opNum == 0);
324 default: return false;
330 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
331 unsigned int opNum) {
332 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
334 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
341 #define PrintOp1PlusOp2(mop1, mop2) \
342 printOneOperand(mop1); \
344 printOneOperand(mop2);
347 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
350 const MachineOperand& mop = MI->getOperand(opNum);
352 if (OpIsBranchTargetLabel(MI, opNum))
354 PrintOp1PlusOp2(mop, MI->getOperand(opNum+1));
357 else if (OpIsMemoryAddressBase(MI, opNum))
360 PrintOp1PlusOp2(mop, MI->getOperand(opNum+1));
366 printOneOperand(mop);
373 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &mop)
375 bool needBitsFlag = true;
377 if (mop.opHiBits32())
379 else if (mop.opLoBits32())
381 else if (mop.opHiBits64())
383 else if (mop.opLoBits64())
386 needBitsFlag = false;
388 switch (mop.getType())
390 case MachineOperand::MO_VirtualRegister:
391 case MachineOperand::MO_CCRegister:
392 case MachineOperand::MO_MachineRegister:
394 int RegNum = (int)mop.getAllocatedRegNum();
396 // better to print code with NULL registers than to die
397 if (RegNum == Target.getRegInfo().getInvalidRegNum()) {
398 toAsm << "<NULL VALUE>";
400 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
405 case MachineOperand::MO_PCRelativeDisp:
407 const Value *Val = mop.getVRegValue();
408 assert(Val && "\tNULL Value in SparcFunctionAsmPrinter");
410 if (const BasicBlock *BB = dyn_cast<const BasicBlock>(Val))
412 else if (const Function *M = dyn_cast<Function>(Val))
414 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
416 else if (const Constant *CV = dyn_cast<Constant>(Val))
419 assert(0 && "Unrecognized value in SparcFunctionAsmPrinter");
423 case MachineOperand::MO_SignExtendedImmed:
424 toAsm << mop.getImmedValue();
427 case MachineOperand::MO_UnextendedImmed:
428 toAsm << (uint64_t) mop.getImmedValue();
432 toAsm << mop; // use dump field
442 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
444 unsigned Opcode = MI->getOpCode();
446 if (Target.getInstrInfo().isDummyPhiInstr(Opcode));
447 return; // IGNORE PHI NODES
449 toAsm << "\t" << Target.getInstrInfo().getName(Opcode) << "\t";
451 unsigned Mask = getOperandMask(Opcode);
453 bool NeedComma = false;
455 for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
456 if (! ((1 << OpNum) & Mask)) { // Ignore this operand?
457 if (NeedComma) toAsm << ", "; // Handle comma outputing
459 N = printOperands(MI, OpNum);
468 SparcFunctionAsmPrinter::emitBasicBlock(const MachineBasicBlock &MBB)
470 // Emit a label for the basic block
471 toAsm << getID(MBB.getBasicBlock()) << ":\n";
473 // Loop over all of the instructions in the basic block...
474 for (MachineBasicBlock::const_iterator MII = MBB.begin(), MIE = MBB.end();
476 emitMachineInst(*MII);
477 toAsm << "\n"; // Seperate BB's with newlines
481 SparcFunctionAsmPrinter::emitFunction(const Function &F)
483 string methName = getID(&F);
484 toAsm << "!****** Outputing Function: " << methName << " ******\n";
485 enterSection(AsmPrinter::Text);
486 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
487 //toAsm << "\t.type\t" << methName << ",#function\n";
488 toAsm << "\t.type\t" << methName << ", 2\n";
489 toAsm << methName << ":\n";
491 // Output code for all of the basic blocks in the function...
492 MachineFunction &MF = MachineFunction::get(&F);
493 for (MachineFunction::const_iterator I = MF.begin(), E = MF.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 (C == '\\') {
591 } else if (isprint(C)) {
595 case '\a': Result += "\\a"; break;
596 case '\b': Result += "\\b"; break;
597 case '\f': Result += "\\f"; break;
598 case '\n': Result += "\\n"; break;
599 case '\r': Result += "\\r"; break;
600 case '\t': Result += "\\t"; break;
601 case '\v': Result += "\\v"; break;
604 Result += toOctal(C >> 6);
605 Result += toOctal(C >> 3);
606 Result += toOctal(C >> 0);
617 ArrayTypeIsString(const ArrayType* arrayType)
619 return (arrayType->getElementType() == Type::UByteTy ||
620 arrayType->getElementType() == Type::SByteTy);
625 TypeToDataDirective(const Type* type)
627 switch(type->getPrimitiveID())
629 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
631 case Type::UShortTyID: case Type::ShortTyID:
633 case Type::UIntTyID: case Type::IntTyID:
635 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
637 case Type::FloatTyID:
639 case Type::DoubleTyID:
641 case Type::ArrayTyID:
642 if (ArrayTypeIsString((ArrayType*) type))
645 return "<InvaliDataTypeForPrinting>";
647 return "<InvaliDataTypeForPrinting>";
651 // Get the size of the type
654 TypeToSize(const Type* type, const TargetMachine& target)
656 return target.findOptimalStorageSize(type);
659 // Get the size of the constant for the given target.
660 // If this is an unsized array, return 0.
663 ConstantToSize(const Constant* CV, const TargetMachine& target)
665 if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
667 const ArrayType *aty = cast<ArrayType>(CVA->getType());
668 if (ArrayTypeIsString(aty))
669 return 1 + CVA->getNumOperands();
672 return TypeToSize(CV->getType(), target);
675 // Align data larger than one L1 cache line on L1 cache line boundaries.
676 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
679 SizeToAlignment(unsigned int size, const TargetMachine& target)
681 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
682 if (size > (unsigned) cacheLineSize / 2)
683 return cacheLineSize;
685 for (unsigned sz=1; /*no condition*/; sz *= 2)
690 // Get the size of the type and then use SizeToAlignment.
693 TypeToAlignment(const Type* type, const TargetMachine& target)
695 return SizeToAlignment(TypeToSize(type, target), target);
698 // Get the size of the constant and then use SizeToAlignment.
699 // Handles strings as a special case;
701 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
703 if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
704 if (ArrayTypeIsString(cast<ArrayType>(CVA->getType())))
705 return SizeToAlignment(1 + CVA->getNumOperands(), target);
707 return TypeToAlignment(CV->getType(), target);
711 // Print a single constant value.
713 SparcModuleAsmPrinter::printSingleConstantValue(const Constant* CV)
715 assert(CV->getType() != Type::VoidTy &&
716 CV->getType() != Type::TypeTy &&
717 CV->getType() != Type::LabelTy &&
718 "Unexpected type for Constant");
720 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
721 && "Aggregate types should be handled outside this function");
723 toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
725 if (CV->getType()->isPrimitiveType())
727 if (CV->getType()->isFloatingPoint()) {
728 // FP Constants are printed as integer constants to avoid losing
730 double Val = cast<ConstantFP>(CV)->getValue();
731 if (CV->getType() == Type::FloatTy) {
732 float FVal = (float)Val;
733 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
734 toAsm << *(unsigned int*)ProxyPtr;
735 } else if (CV->getType() == Type::DoubleTy) {
736 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
737 toAsm << *(uint64_t*)ProxyPtr;
739 assert(0 && "Unknown floating point type!");
742 toAsm << "\t! " << CV->getType()->getDescription()
743 << " value: " << Val << "\n";
745 WriteAsOperand(toAsm, CV, false, false) << "\n";
748 else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
749 { // This is a constant address for a global variable or method.
750 // Use the name of the variable or method as the address value.
751 toAsm << getID(CPR->getValue()) << "\n";
753 else if (isa<ConstantPointerNull>(CV))
754 { // Null pointer value
757 else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
758 { // Constant expression built from operators, constants, and symbolic addrs
759 toAsm << ConstantExprToString(CE, Target) << "\n";
763 assert(0 && "Unknown elementary type for constant");
768 SparcModuleAsmPrinter::PrintZeroBytesToPad(int numBytes)
770 for ( ; numBytes >= 8; numBytes -= 8)
771 printSingleConstantValue(Constant::getNullValue(Type::ULongTy));
775 printSingleConstantValue(Constant::getNullValue(Type::UIntTy));
780 printSingleConstantValue(Constant::getNullValue(Type::UByteTy));
783 // Print a constant value or values (it may be an aggregate).
784 // Uses printSingleConstantValue() to print each individual value.
786 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV,
787 int numPadBytes /* = 0*/)
789 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
792 PrintZeroBytesToPad(numPadBytes);
794 if (CVA && isStringCompatible(CVA))
795 { // print the string alone and return
796 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
799 { // Not a string. Print the values in successive locations
800 const std::vector<Use> &constValues = CVA->getValues();
801 for (unsigned i=0; i < constValues.size(); i++)
802 printConstantValueOnly(cast<Constant>(constValues[i].get()));
804 else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
805 { // Print the fields in successive locations. Pad to align if needed!
806 const StructLayout *cvsLayout =
807 Target.DataLayout.getStructLayout(CVS->getType());
808 const std::vector<Use>& constValues = CVS->getValues();
809 unsigned sizeSoFar = 0;
810 for (unsigned i=0, N = constValues.size(); i < N; i++)
812 const Constant* field = cast<Constant>(constValues[i].get());
814 // Check if padding is needed and insert one or more 0s.
815 unsigned fieldSize = Target.DataLayout.getTypeSize(field->getType());
816 int padSize = ((i == N-1? cvsLayout->StructSize
817 : cvsLayout->MemberOffsets[i+1])
818 - cvsLayout->MemberOffsets[i]) - fieldSize;
819 sizeSoFar += (fieldSize + padSize);
821 // Now print the actual field value
822 printConstantValueOnly(field, padSize);
824 assert(sizeSoFar == cvsLayout->StructSize &&
825 "Layout of constant struct may be incorrect!");
828 printSingleConstantValue(CV);
831 // Print a constant (which may be an aggregate) prefixed by all the
832 // appropriate directives. Uses printConstantValueOnly() to print the
835 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
837 if (valID.length() == 0)
840 toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
842 // Print .size and .type only if it is not a string.
843 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
844 if (CVA && isStringCompatible(CVA))
845 { // print it as a string and return
846 toAsm << valID << ":\n";
847 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
851 toAsm << "\t.type" << "\t" << valID << ",#object\n";
853 unsigned int constSize = ConstantToSize(CV, Target);
855 toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
857 toAsm << valID << ":\n";
859 printConstantValueOnly(CV);
863 void SparcModuleAsmPrinter::FoldConstants(const Module &M,
864 hash_set<const Constant*> &MC) {
865 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
866 if (!I->isExternal()) {
867 const hash_set<const Constant*> &pool =
868 MachineFunction::get(I).getConstantPoolValues();
869 MC.insert(pool.begin(), pool.end());
873 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
875 if (GV->hasExternalLinkage())
876 toAsm << "\t.global\t" << getID(GV) << "\n";
878 if (GV->hasInitializer() && ! GV->getInitializer()->isNullValue())
879 printConstant(GV->getInitializer(), getID(GV));
881 toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
883 toAsm << "\t.type\t" << getID(GV) << ",#object\n";
884 toAsm << "\t.reserve\t" << getID(GV) << ","
885 << TypeToSize(GV->getType()->getElementType(), Target)
891 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module &M) {
892 // First, get the constants there were marked by the code generator for
893 // inclusion in the assembly code data area and fold them all into a
894 // single constant pool since there may be lots of duplicates. Also,
895 // lets force these constants into the slot table so that we can get
896 // unique names for unnamed constants also.
898 hash_set<const Constant*> moduleConstants;
899 FoldConstants(M, moduleConstants);
901 // Output constants spilled to memory
902 enterSection(AsmPrinter::ReadOnlyData);
903 for (hash_set<const Constant*>::const_iterator I = moduleConstants.begin(),
904 E = moduleConstants.end(); I != E; ++I)
907 // Output global variables...
908 for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
909 if (! GI->isExternal()) {
910 assert(GI->hasInitializer());
911 if (GI->isConstant())
912 enterSection(AsmPrinter::ReadOnlyData); // read-only, initialized data
913 else if (GI->getInitializer()->isNullValue())
914 enterSection(AsmPrinter::ZeroInitRWData); // read-write zero data
916 enterSection(AsmPrinter::InitRWData); // read-write non-zero data
918 printGlobalVariable(GI);
924 } // End anonymous namespace
926 Pass *UltraSparc::getModuleAsmPrinterPass(std::ostream &Out) {
927 return new SparcModuleAsmPrinter(Out, *this);