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/MachineCodeForMethod.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/BasicBlock.h"
21 #include "llvm/Function.h"
22 #include "llvm/Module.h"
23 #include "llvm/SlotCalculator.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "Support/StringExtras.h"
32 class GlobalIdTable: public Annotation {
33 static AnnotationID AnnotId;
34 friend class AsmPrinter; // give access to AnnotId
36 typedef std::hash_map<const Value*, int> ValIdMap;
37 typedef ValIdMap::const_iterator ValIdMapConstIterator;
38 typedef ValIdMap:: iterator ValIdMapIterator;
40 SlotCalculator Table; // map anonymous values to unique integer IDs
41 ValIdMap valToIdMap; // used for values not handled by SlotCalculator
43 GlobalIdTable(Module* M) : Annotation(AnnotId), Table(M, true) {}
46 AnnotationID GlobalIdTable::AnnotId =
47 AnnotationManager::getID("ASM PRINTER GLOBAL TABLE ANNOT");
49 //===---------------------------------------------------------------------===//
50 // Code Shared By the two printer passes, as a mixin
51 //===---------------------------------------------------------------------===//
54 GlobalIdTable* idTable;
57 const TargetMachine &Target;
67 AsmPrinter(std::ostream &os, const TargetMachine &T)
68 : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
70 // (start|end)(Module|Function) - Callback methods to be invoked by subclasses
71 void startModule(Module *M) {
72 // Create the global id table if it does not already exist
73 idTable = (GlobalIdTable*) M->getAnnotation(GlobalIdTable::AnnotId);
74 if (idTable == NULL) {
75 idTable = new GlobalIdTable(M);
76 M->addAnnotation(idTable);
79 void startFunction(Function *F) {
80 // Make sure the slot table has information about this function...
81 idTable->Table.incorporateFunction(F);
83 void endFunction(Function *F) {
84 idTable->Table.purgeFunction(); // Forget all about F
89 // Check if a name is external or accessible from external code.
90 // Only functions can currently be external. "main" is the only name
91 // that is visible externally.
92 bool isExternal(const Value* V) {
93 const Function *F = dyn_cast<Function>(V);
94 return F && (F->isExternal() || F->getName() == "main");
97 // enterSection - Use this method to enter a different section of the output
98 // executable. This is used to only output neccesary section transitions.
100 void enterSection(enum Sections S) {
101 if (S == CurSection) return; // Only switch section if neccesary
104 toAsm << "\n\t.section ";
107 default: assert(0 && "Bad section name!");
108 case Text: toAsm << "\".text\""; break;
109 case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
110 case InitRWData: toAsm << "\".data\",#alloc,#write"; break;
111 case UninitRWData: toAsm << "\".bss\",#alloc,#write\nBbss.bss:"; break;
116 static std::string getValidSymbolName(const string &S) {
119 // Symbol names in Sparc assembly language have these rules:
120 // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
121 // (b) A name beginning in "." is treated as a local name.
122 // (c) Names beginning with "_" are reserved by ANSI C and shd not be used.
124 if (S[0] == '_' || isdigit(S[0]))
127 for (unsigned i = 0; i < S.size(); ++i)
130 if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
135 Result += char('0' + ((unsigned char)C >> 4));
136 Result += char('0' + (C & 0xF));
142 // getID - Return a valid identifier for the specified value. Base it on
143 // the name of the identifier if possible (qualified by the type), and
144 // use a numbered value based on prefix otherwise.
145 // FPrefix is always prepended to the output identifier.
147 string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
148 string Result = FPrefix ? FPrefix : ""; // "Forced prefix"
150 Result = Result + (V->hasName()? V->getName() : string(Prefix));
152 // Qualify all internal names with a unique id.
153 if (!isExternal(V)) {
154 int valId = idTable->Table.getValSlot(V);
156 GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
157 if (I == idTable->valToIdMap.end())
158 valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
162 Result = Result + "_" + itostr(valId);
165 return getValidSymbolName(Result);
168 // getID Wrappers - Ensure consistent usage...
169 string getID(const Function *F) {
170 return getID(F, "LLVMFunction_");
172 string getID(const BasicBlock *BB) {
173 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
175 string getID(const GlobalVariable *GV) {
176 return getID(GV, "LLVMGlobal_", ".G_");
178 string getID(const Constant *CV) {
179 return getID(CV, "LLVMConst_", ".C_");
185 //===----------------------------------------------------------------------===//
186 // SparcFunctionAsmPrinter Code
187 //===----------------------------------------------------------------------===//
189 struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
190 inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
191 : AsmPrinter(os, t) {}
193 const char *getPassName() const {
194 return "Output Sparc Assembly for Functions";
197 virtual bool doInitialization(Module *M) {
202 virtual bool runOnFunction(Function *F) {
209 virtual bool doFinalization(Module *M) {
214 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
215 AU.setPreservesAll();
218 void emitFunction(const Function *F);
220 void emitBasicBlock(const BasicBlock *BB);
221 void emitMachineInst(const MachineInstr *MI);
223 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
224 void printOneOperand(const MachineOperand &Op);
226 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
227 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
229 unsigned getOperandMask(unsigned Opcode) {
231 case SUBcc: return 1 << 3; // Remove CC argument
232 case BA: return 1 << 0; // Remove Arg #0, which is always null or xcc
233 default: return 0; // By default, don't hack operands...
239 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
240 unsigned int opNum) {
241 switch (MI->getOpCode()) {
243 case JMPLRET: return (opNum == 0);
244 default: return false;
250 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
251 unsigned int opNum) {
252 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
254 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
261 #define PrintOp1PlusOp2(Op1, Op2) \
262 printOneOperand(Op1); \
264 printOneOperand(Op2);
267 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
270 const MachineOperand& Op = MI->getOperand(opNum);
272 if (OpIsBranchTargetLabel(MI, opNum))
274 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
277 else if (OpIsMemoryAddressBase(MI, opNum))
280 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
293 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &op)
295 switch (op.getOperandType())
297 case MachineOperand::MO_VirtualRegister:
298 case MachineOperand::MO_CCRegister:
299 case MachineOperand::MO_MachineRegister:
301 int RegNum = (int)op.getAllocatedRegNum();
303 // better to print code with NULL registers than to die
304 if (RegNum == Target.getRegInfo().getInvalidRegNum()) {
305 toAsm << "<NULL VALUE>";
307 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
312 case MachineOperand::MO_PCRelativeDisp:
314 const Value *Val = op.getVRegValue();
315 assert(Val && "\tNULL Value in SparcFunctionAsmPrinter");
317 if (const BasicBlock *BB = dyn_cast<const BasicBlock>(Val))
319 else if (const Function *M = dyn_cast<Function>(Val))
321 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
323 else if (const Constant *CV = dyn_cast<Constant>(Val))
326 assert(0 && "Unrecognized value in SparcFunctionAsmPrinter");
330 case MachineOperand::MO_SignExtendedImmed:
331 toAsm << op.getImmedValue();
334 case MachineOperand::MO_UnextendedImmed:
335 toAsm << (uint64_t) op.getImmedValue();
339 toAsm << op; // use dump field
346 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
348 unsigned Opcode = MI->getOpCode();
350 if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
351 return; // IGNORE PHI NODES
353 toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
355 unsigned Mask = getOperandMask(Opcode);
357 bool NeedComma = false;
359 for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
360 if (! ((1 << OpNum) & Mask)) { // Ignore this operand?
361 if (NeedComma) toAsm << ", "; // Handle comma outputing
363 N = printOperands(MI, OpNum);
372 SparcFunctionAsmPrinter::emitBasicBlock(const BasicBlock *BB)
374 // Emit a label for the basic block
375 toAsm << getID(BB) << ":\n";
377 // Get the vector of machine instructions corresponding to this bb.
378 const MachineCodeForBasicBlock &MIs = BB->getMachineInstrVec();
379 MachineCodeForBasicBlock::const_iterator MII = MIs.begin(), MIE = MIs.end();
381 // Loop over all of the instructions in the basic block...
382 for (; MII != MIE; ++MII)
383 emitMachineInst(*MII);
384 toAsm << "\n"; // Seperate BB's with newlines
388 SparcFunctionAsmPrinter::emitFunction(const Function *M)
390 string methName = getID(M);
391 toAsm << "!****** Outputing Function: " << methName << " ******\n";
392 enterSection(AsmPrinter::Text);
393 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
394 //toAsm << "\t.type\t" << methName << ",#function\n";
395 toAsm << "\t.type\t" << methName << ", 2\n";
396 toAsm << methName << ":\n";
398 // Output code for all of the basic blocks in the function...
399 for (Function::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
402 // Output a .size directive so the debugger knows the extents of the function
403 toAsm << ".EndOf_" << methName << ":\n\t.size "
404 << methName << ", .EndOf_"
405 << methName << "-" << methName << "\n";
407 // Put some spaces between the functions
411 } // End anonymous namespace
413 Pass *UltraSparc::getFunctionAsmPrinterPass(PassManager &PM, std::ostream &Out){
414 return new SparcFunctionAsmPrinter(Out, *this);
421 //===----------------------------------------------------------------------===//
422 // SparcFunctionAsmPrinter Code
423 //===----------------------------------------------------------------------===//
427 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
429 SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
430 : AsmPrinter(os, t) {}
432 const char *getPassName() const { return "Output Sparc Assembly for Module"; }
434 virtual bool run(Module *M) {
436 emitGlobalsAndConstants(M);
441 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
442 AU.setPreservesAll();
446 void emitGlobalsAndConstants(const Module *M);
448 void printGlobalVariable(const GlobalVariable *GV);
449 void printSingleConstant( const Constant* CV);
450 void printConstantValueOnly(const Constant* CV);
451 void printConstant( const Constant* CV, std::string valID = "");
453 static void FoldConstants(const Module *M,
454 std::hash_set<const Constant*> &moduleConstants);
458 // Can we treat the specified array as a string? Only if it is an array of
459 // ubytes or non-negative sbytes.
461 static bool isStringCompatible(ConstantArray *CPA) {
462 const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
463 if (ETy == Type::UByteTy) return true;
464 if (ETy != Type::SByteTy) return false;
466 for (unsigned i = 0; i < CPA->getNumOperands(); ++i)
467 if (cast<ConstantSInt>(CPA->getOperand(i))->getValue() < 0)
473 // toOctal - Convert the low order bits of X into an octal letter
474 static inline char toOctal(int X) {
478 // getAsCString - Return the specified array as a C compatible string, only if
479 // the predicate isStringCompatible is true.
481 static string getAsCString(ConstantArray *CPA) {
482 assert(isStringCompatible(CPA) && "Array is not string compatible!");
485 const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
487 for (unsigned i = 0; i < CPA->getNumOperands(); ++i) {
488 unsigned char C = (ETy == Type::SByteTy) ?
489 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
490 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
494 } else if (isprint(C)) {
498 case '\a': Result += "\\a"; break;
499 case '\b': Result += "\\b"; break;
500 case '\f': Result += "\\f"; break;
501 case '\n': Result += "\\n"; break;
502 case '\r': Result += "\\r"; break;
503 case '\t': Result += "\\t"; break;
504 case '\v': Result += "\\v"; break;
507 Result += toOctal(C >> 6);
508 Result += toOctal(C >> 3);
509 Result += toOctal(C >> 0);
520 ArrayTypeIsString(ArrayType* arrayType)
522 return (arrayType->getElementType() == Type::UByteTy ||
523 arrayType->getElementType() == Type::SByteTy);
527 TypeToDataDirective(const Type* type)
529 switch(type->getPrimitiveID())
531 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
533 case Type::UShortTyID: case Type::ShortTyID:
535 case Type::UIntTyID: case Type::IntTyID:
537 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
539 case Type::FloatTyID:
541 case Type::DoubleTyID:
543 case Type::ArrayTyID:
544 if (ArrayTypeIsString((ArrayType*) type))
547 return "<InvaliDataTypeForPrinting>";
549 return "<InvaliDataTypeForPrinting>";
553 // Get the size of the constant for the given target.
554 // If this is an unsized array, return 0.
557 ConstantToSize(const Constant* CV, const TargetMachine& target)
559 if (ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
561 ArrayType *aty = cast<ArrayType>(CPA->getType());
562 if (ArrayTypeIsString(aty))
563 return 1 + CPA->getNumOperands();
566 return target.findOptimalStorageSize(CV->getType());
571 // Align data larger than one L1 cache line on L1 cache line boundaries.
572 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
575 SizeToAlignment(unsigned int size, const TargetMachine& target)
577 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
578 if (size > (unsigned) cacheLineSize / 2)
579 return cacheLineSize;
581 for (unsigned sz=1; /*no condition*/; sz *= 2)
586 // Get the size of the type and then use SizeToAlignment.
589 TypeToAlignment(const Type* type, const TargetMachine& target)
591 return SizeToAlignment(target.findOptimalStorageSize(type), target);
594 // Get the size of the constant and then use SizeToAlignment.
595 // Handles strings as a special case;
597 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
599 if (ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
600 if (ArrayTypeIsString(cast<ArrayType>(CPA->getType())))
601 return SizeToAlignment(1 + CPA->getNumOperands(), target);
603 return TypeToAlignment(CV->getType(), target);
607 // Print a single constant value.
609 SparcModuleAsmPrinter::printSingleConstant(const Constant* CV)
611 assert(CV->getType() != Type::VoidTy &&
612 CV->getType() != Type::TypeTy &&
613 CV->getType() != Type::LabelTy &&
614 "Unexpected type for Constant");
616 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
617 && "Aggregate types should be handled outside this function");
619 toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
621 if (CV->getType()->isPrimitiveType())
623 if (CV->getType()->isFloatingPoint()) {
624 // FP Constants are printed as integer constants to avoid losing
626 double Val = cast<ConstantFP>(CV)->getValue();
627 if (CV->getType() == Type::FloatTy) {
628 float FVal = (float)Val;
629 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
630 toAsm << *(unsigned int*)ProxyPtr;
631 } else if (CV->getType() == Type::DoubleTy) {
632 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
633 toAsm << *(uint64_t*)ProxyPtr;
635 assert(0 && "Unknown floating point type!");
638 toAsm << "\t! " << CV->getType()->getDescription()
639 << " value: " << Val << "\n";
641 WriteAsOperand(toAsm, CV, false, false) << "\n";
644 else if (ConstantPointer* CPP = dyn_cast<ConstantPointer>(CV))
646 assert(CPP->isNullValue() &&
647 "Cannot yet print non-null pointer constants to assembly");
650 else if (isa<ConstantPointerRef>(CV))
652 assert(0 && "Cannot yet initialize pointer refs in assembly");
656 assert(0 && "Unknown elementary type for constant");
660 // Print a constant value or values (it may be an aggregate).
661 // Uses printSingleConstant() to print each individual value.
663 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV)
665 ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
667 if (CPA && isStringCompatible(CPA))
668 { // print the string alone and return
669 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
672 { // Not a string. Print the values in successive locations
673 const std::vector<Use> &constValues = CPA->getValues();
674 for (unsigned i=0; i < constValues.size(); i++)
675 this->printConstantValueOnly(cast<Constant>(constValues[i].get()));
677 else if (ConstantStruct *CPS = dyn_cast<ConstantStruct>(CV))
678 { // Print the fields in successive locations
679 const std::vector<Use>& constValues = CPS->getValues();
680 for (unsigned i=0; i < constValues.size(); i++)
681 this->printConstantValueOnly(cast<Constant>(constValues[i].get()));
684 this->printSingleConstant(CV);
687 // Print a constant (which may be an aggregate) prefixed by all the
688 // appropriate directives. Uses printConstantValueOnly() to print the
691 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
693 if (valID.length() == 0)
696 toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
698 // Print .size and .type only if it is not a string.
699 ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
700 if (CPA && isStringCompatible(CPA))
701 { // print it as a string and return
702 toAsm << valID << ":\n";
703 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
707 toAsm << "\t.type" << "\t" << valID << ",#object\n";
709 unsigned int constSize = ConstantToSize(CV, Target);
711 toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
713 toAsm << valID << ":\n";
715 printConstantValueOnly(CV);
719 void SparcModuleAsmPrinter::FoldConstants(const Module *M,
720 std::hash_set<const Constant*> &MC) {
721 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
722 if (!(*I)->isExternal()) {
723 const std::hash_set<const Constant*> &pool =
724 MachineCodeForMethod::get(*I).getConstantPoolValues();
725 MC.insert(pool.begin(), pool.end());
729 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
731 toAsm << "\t.global\t" << getID(GV) << "\n";
733 if (GV->hasInitializer())
734 printConstant(GV->getInitializer(), getID(GV));
736 toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
738 toAsm << "\t.type\t" << getID(GV) << ",#object\n";
739 toAsm << "\t.reserve\t" << getID(GV) << ","
740 << Target.findOptimalStorageSize(GV->getType()->getElementType())
746 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module *M) {
747 // First, get the constants there were marked by the code generator for
748 // inclusion in the assembly code data area and fold them all into a
749 // single constant pool since there may be lots of duplicates. Also,
750 // lets force these constants into the slot table so that we can get
751 // unique names for unnamed constants also.
753 std::hash_set<const Constant*> moduleConstants;
754 FoldConstants(M, moduleConstants);
756 // Now, emit the three data sections separately; the cost of I/O should
757 // make up for the cost of extra passes over the globals list!
759 // Section 1 : Read-only data section (implies initialized)
760 enterSection(AsmPrinter::ReadOnlyData);
761 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
762 if ((*GI)->hasInitializer() && (*GI)->isConstant())
763 printGlobalVariable(*GI);
765 for (std::hash_set<const Constant*>::const_iterator
766 I = moduleConstants.begin(),
767 E = moduleConstants.end(); I != E; ++I)
770 // Section 2 : Initialized read-write data section
771 enterSection(AsmPrinter::InitRWData);
772 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
773 if ((*GI)->hasInitializer() && ! (*GI)->isConstant())
774 printGlobalVariable(*GI);
776 // Section 3 : Uninitialized read-write data section
777 enterSection(AsmPrinter::UninitRWData);
778 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
779 if (! (*GI)->hasInitializer())
780 printGlobalVariable(*GI);
785 } // End anonymous namespace
787 Pass *UltraSparc::getModuleAsmPrinterPass(PassManager &PM, std::ostream &Out) {
788 return new SparcModuleAsmPrinter(Out, *this);