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/ConstantVals.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Annotation.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/Function.h"
23 #include "llvm/Module.h"
24 #include "llvm/SlotCalculator.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "Support/StringExtras.h"
27 #include "Support/HashExtras.h"
33 class GlobalIdTable: public Annotation {
34 static AnnotationID AnnotId;
35 friend class AsmPrinter; // give access to AnnotId
37 typedef std::hash_map<const Value*, int> ValIdMap;
38 typedef ValIdMap::const_iterator ValIdMapConstIterator;
39 typedef ValIdMap:: iterator ValIdMapIterator;
41 SlotCalculator *Table; // map anonymous values to unique integer IDs
42 ValIdMap valToIdMap; // used for values not handled by SlotCalculator
44 GlobalIdTable(Module* M) : Annotation(AnnotId) {
45 Table = new SlotCalculator(M, true);
54 AnnotationID GlobalIdTable::AnnotId =
55 AnnotationManager::getID("ASM PRINTER GLOBAL TABLE ANNOT");
57 //===---------------------------------------------------------------------===//
58 // Code Shared By the two printer passes, as a mixin
59 //===---------------------------------------------------------------------===//
62 GlobalIdTable* idTable;
65 const TargetMachine &Target;
75 AsmPrinter(std::ostream &os, const TargetMachine &T)
76 : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
78 // (start|end)(Module|Function) - Callback methods to be invoked by subclasses
79 void startModule(Module *M) {
80 // Create the global id table if it does not already exist
81 idTable = (GlobalIdTable*) M->getAnnotation(GlobalIdTable::AnnotId);
82 if (idTable == NULL) {
83 idTable = new GlobalIdTable(M);
84 M->addAnnotation(idTable);
87 void startFunction(Function *F) {
88 // Make sure the slot table has information about this function...
89 idTable->Table->incorporateFunction(F);
91 void endFunction(Function *F) {
92 idTable->Table->purgeFunction(); // Forget all about F
97 // Check if a name is external or accessible from external code.
98 // Only functions can currently be external. "main" is the only name
99 // that is visible externally.
100 bool isExternal(const Value* V) {
101 const Function *F = dyn_cast<Function>(V);
102 return F && (F->isExternal() || F->getName() == "main");
105 // enterSection - Use this method to enter a different section of the output
106 // executable. This is used to only output neccesary section transitions.
108 void enterSection(enum Sections S) {
109 if (S == CurSection) return; // Only switch section if neccesary
112 toAsm << "\n\t.section ";
115 default: assert(0 && "Bad section name!");
116 case Text: toAsm << "\".text\""; break;
117 case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
118 case InitRWData: toAsm << "\".data\",#alloc,#write"; break;
119 case UninitRWData: toAsm << "\".bss\",#alloc,#write\nBbss.bss:"; break;
124 static std::string getValidSymbolName(const string &S) {
127 // Symbol names in Sparc assembly language have these rules:
128 // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
129 // (b) A name beginning in "." is treated as a local name.
130 // (c) Names beginning with "_" are reserved by ANSI C and shd not be used.
132 if (S[0] == '_' || isdigit(S[0]))
135 for (unsigned i = 0; i < S.size(); ++i)
138 if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
143 Result += char('0' + ((unsigned char)C >> 4));
144 Result += char('0' + (C & 0xF));
150 // getID - Return a valid identifier for the specified value. Base it on
151 // the name of the identifier if possible (qualified by the type), and
152 // use a numbered value based on prefix otherwise.
153 // FPrefix is always prepended to the output identifier.
155 string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
156 string Result = FPrefix ? FPrefix : ""; // "Forced prefix"
158 Result = Result + (V->hasName()? V->getName() : string(Prefix));
160 // Qualify all internal names with a unique id.
161 if (!isExternal(V)) {
162 int valId = idTable->Table->getValSlot(V);
164 GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
165 if (I == idTable->valToIdMap.end())
166 valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
170 Result = Result + "_" + itostr(valId);
173 return getValidSymbolName(Result);
176 // getID Wrappers - Ensure consistent usage...
177 string getID(const Module *M) {
178 return getID(M, "LLVMModule_");
180 string getID(const Function *F) {
181 return getID(F, "LLVMFunction_");
183 string getID(const BasicBlock *BB) {
184 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
186 string getID(const GlobalVariable *GV) {
187 return getID(GV, "LLVMGlobal_", ".G_");
189 string getID(const Constant *CV) {
190 return getID(CV, "LLVMConst_", ".C_");
196 //===----------------------------------------------------------------------===//
197 // SparcFunctionAsmPrinter Code
198 //===----------------------------------------------------------------------===//
200 struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
201 inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
202 : AsmPrinter(os, t) {}
204 virtual bool doInitialization(Module *M) {
209 virtual bool runOnFunction(Function *F) {
216 virtual bool doFinalization(Module *M) {
221 void emitFunction(const Function *F);
223 void emitBasicBlock(const BasicBlock *BB);
224 void emitMachineInst(const MachineInstr *MI);
226 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
227 void printOneOperand(const MachineOperand &Op);
229 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
230 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
232 unsigned getOperandMask(unsigned Opcode) {
234 case SUBcc: return 1 << 3; // Remove CC argument
235 case BA: return 1 << 0; // Remove Arg #0, which is always null or xcc
236 default: return 0; // By default, don't hack operands...
242 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
243 unsigned int opNum) {
244 switch (MI->getOpCode()) {
246 case JMPLRET: return (opNum == 0);
247 default: return false;
253 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
254 unsigned int opNum) {
255 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
257 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
264 #define PrintOp1PlusOp2(Op1, Op2) \
265 printOneOperand(Op1); \
267 printOneOperand(Op2);
270 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
273 const MachineOperand& Op = MI->getOperand(opNum);
275 if (OpIsBranchTargetLabel(MI, opNum))
277 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
280 else if (OpIsMemoryAddressBase(MI, opNum))
283 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
296 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &op)
298 switch (op.getOperandType())
300 case MachineOperand::MO_VirtualRegister:
301 case MachineOperand::MO_CCRegister:
302 case MachineOperand::MO_MachineRegister:
304 int RegNum = (int)op.getAllocatedRegNum();
306 // better to print code with NULL registers than to die
307 if (RegNum == Target.getRegInfo().getInvalidRegNum()) {
308 toAsm << "<NULL VALUE>";
310 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
315 case MachineOperand::MO_PCRelativeDisp:
317 const Value *Val = op.getVRegValue();
319 toAsm << "\t<*NULL Value*>";
320 else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(Val))
322 else if (const Function *M = dyn_cast<const Function>(Val))
324 else if (const GlobalVariable *GV=dyn_cast<const GlobalVariable>(Val))
326 else if (const Constant *CV = dyn_cast<const Constant>(Val))
329 toAsm << "<unknown value=" << Val << ">";
333 case MachineOperand::MO_SignExtendedImmed:
334 case MachineOperand::MO_UnextendedImmed:
335 toAsm << (long)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 virtual bool run(Module *M) {
434 emitGlobalsAndConstants(M);
439 void emitGlobalsAndConstants(const Module *M);
441 void printGlobalVariable(const GlobalVariable *GV);
442 void printSingleConstant( const Constant* CV);
443 void printConstantValueOnly(const Constant* CV);
444 void printConstant( const Constant* CV, std::string valID = "");
446 static void FoldConstants(const Module *M,
447 std::hash_set<const Constant*> &moduleConstants);
452 // Can we treat the specified array as a string? Only if it is an array of
453 // ubytes or non-negative sbytes.
455 static bool isStringCompatible(ConstantArray *CPA) {
456 const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
457 if (ETy == Type::UByteTy) return true;
458 if (ETy != Type::SByteTy) return false;
460 for (unsigned i = 0; i < CPA->getNumOperands(); ++i)
461 if (cast<ConstantSInt>(CPA->getOperand(i))->getValue() < 0)
467 // toOctal - Convert the low order bits of X into an octal letter
468 static inline char toOctal(int X) {
472 // getAsCString - Return the specified array as a C compatible string, only if
473 // the predicate isStringCompatible is true.
475 static string getAsCString(ConstantArray *CPA) {
476 assert(isStringCompatible(CPA) && "Array is not string compatible!");
479 const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
481 for (unsigned i = 0; i < CPA->getNumOperands(); ++i) {
482 unsigned char C = (ETy == Type::SByteTy) ?
483 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
484 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
490 case '\a': Result += "\\a"; break;
491 case '\b': Result += "\\b"; break;
492 case '\f': Result += "\\f"; break;
493 case '\n': Result += "\\n"; break;
494 case '\r': Result += "\\r"; break;
495 case '\t': Result += "\\t"; break;
496 case '\v': Result += "\\v"; break;
499 Result += toOctal(C >> 6);
500 Result += toOctal(C >> 3);
501 Result += toOctal(C >> 0);
512 ArrayTypeIsString(ArrayType* arrayType)
514 return (arrayType->getElementType() == Type::UByteTy ||
515 arrayType->getElementType() == Type::SByteTy);
519 TypeToDataDirective(const Type* type)
521 switch(type->getPrimitiveID())
523 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
525 case Type::UShortTyID: case Type::ShortTyID:
527 case Type::UIntTyID: case Type::IntTyID:
529 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
531 case Type::FloatTyID:
533 case Type::DoubleTyID:
535 case Type::ArrayTyID:
536 if (ArrayTypeIsString((ArrayType*) type))
539 return "<InvaliDataTypeForPrinting>";
541 return "<InvaliDataTypeForPrinting>";
545 // Get the size of the constant for the given target.
546 // If this is an unsized array, return 0.
549 ConstantToSize(const Constant* CV, const TargetMachine& target)
551 if (ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
553 ArrayType *aty = cast<ArrayType>(CPA->getType());
554 if (ArrayTypeIsString(aty))
555 return 1 + CPA->getNumOperands();
558 return target.findOptimalStorageSize(CV->getType());
563 // Align data larger than one L1 cache line on L1 cache line boundaries.
564 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
567 SizeToAlignment(unsigned int size, const TargetMachine& target)
569 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
570 if (size > (unsigned) cacheLineSize / 2)
571 return cacheLineSize;
573 for (unsigned sz=1; /*no condition*/; sz *= 2)
578 // Get the size of the type and then use SizeToAlignment.
581 TypeToAlignment(const Type* type, const TargetMachine& target)
583 return SizeToAlignment(target.findOptimalStorageSize(type), target);
586 // Get the size of the constant and then use SizeToAlignment.
587 // Handles strings as a special case;
589 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
591 if (ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
592 if (ArrayTypeIsString(cast<ArrayType>(CPA->getType())))
593 return SizeToAlignment(1 + CPA->getNumOperands(), target);
595 return TypeToAlignment(CV->getType(), target);
599 // Print a single constant value.
601 SparcModuleAsmPrinter::printSingleConstant(const Constant* CV)
603 assert(CV->getType() != Type::VoidTy &&
604 CV->getType() != Type::TypeTy &&
605 CV->getType() != Type::LabelTy &&
606 "Unexpected type for Constant");
608 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
609 && "Aggregate types should be handled outside this function");
611 toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
613 if (CV->getType()->isPrimitiveType())
615 if (CV->getType()->isFloatingPoint()) {
616 // FP Constants are printed as integer constants to avoid losing
618 double Val = cast<ConstantFP>(CV)->getValue();
619 if (CV->getType() == Type::FloatTy) {
620 float FVal = (float)Val;
621 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
622 toAsm << *(unsigned int*)ProxyPtr;
623 } else if (CV->getType() == Type::DoubleTy) {
624 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
625 toAsm << *(uint64_t*)ProxyPtr;
627 assert(0 && "Unknown floating point type!");
630 toAsm << "\t! " << CV->getType()->getDescription()
631 << " value: " << Val << "\n";
633 WriteAsOperand(toAsm, CV, false, false) << "\n";
636 else if (ConstantPointer* CPP = dyn_cast<ConstantPointer>(CV))
638 assert(CPP->isNullValue() &&
639 "Cannot yet print non-null pointer constants to assembly");
642 else if (isa<ConstantPointerRef>(CV))
644 assert(0 && "Cannot yet initialize pointer refs in assembly");
648 assert(0 && "Unknown elementary type for constant");
652 // Print a constant value or values (it may be an aggregate).
653 // Uses printSingleConstant() to print each individual value.
655 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV)
657 ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
659 if (CPA && isStringCompatible(CPA))
660 { // print the string alone and return
661 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
664 { // Not a string. Print the values in successive locations
665 const std::vector<Use> &constValues = CPA->getValues();
666 for (unsigned i=1; i < constValues.size(); i++)
667 this->printConstantValueOnly(cast<Constant>(constValues[i].get()));
669 else if (ConstantStruct *CPS = dyn_cast<ConstantStruct>(CV))
670 { // Print the fields in successive locations
671 const std::vector<Use>& constValues = CPS->getValues();
672 for (unsigned i=1; i < constValues.size(); i++)
673 this->printConstantValueOnly(cast<Constant>(constValues[i].get()));
676 this->printSingleConstant(CV);
679 // Print a constant (which may be an aggregate) prefixed by all the
680 // appropriate directives. Uses printConstantValueOnly() to print the
683 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
685 if (valID.length() == 0)
688 toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
690 // Print .size and .type only if it is not a string.
691 ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
692 if (CPA && isStringCompatible(CPA))
693 { // print it as a string and return
694 toAsm << valID << ":\n";
695 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
699 toAsm << "\t.type" << "\t" << valID << ",#object\n";
701 unsigned int constSize = ConstantToSize(CV, Target);
703 toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
705 toAsm << valID << ":\n";
707 printConstantValueOnly(CV);
711 void SparcModuleAsmPrinter::FoldConstants(const Module *M,
712 std::hash_set<const Constant*> &MC) {
713 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
714 if (!(*I)->isExternal()) {
715 const std::hash_set<const Constant*> &pool =
716 MachineCodeForMethod::get(*I).getConstantPoolValues();
717 MC.insert(pool.begin(), pool.end());
721 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
723 toAsm << "\t.global\t" << getID(GV) << "\n";
725 if (GV->hasInitializer())
726 printConstant(GV->getInitializer(), getID(GV));
728 toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
730 toAsm << "\t.type\t" << getID(GV) << ",#object\n";
731 toAsm << "\t.reserve\t" << getID(GV) << ","
732 << Target.findOptimalStorageSize(GV->getType()->getElementType())
738 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module *M) {
739 // First, get the constants there were marked by the code generator for
740 // inclusion in the assembly code data area and fold them all into a
741 // single constant pool since there may be lots of duplicates. Also,
742 // lets force these constants into the slot table so that we can get
743 // unique names for unnamed constants also.
745 std::hash_set<const Constant*> moduleConstants;
746 FoldConstants(M, moduleConstants);
748 // Now, emit the three data sections separately; the cost of I/O should
749 // make up for the cost of extra passes over the globals list!
751 // Section 1 : Read-only data section (implies initialized)
752 enterSection(AsmPrinter::ReadOnlyData);
753 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
754 if ((*GI)->hasInitializer() && (*GI)->isConstant())
755 printGlobalVariable(*GI);
757 for (std::hash_set<const Constant*>::const_iterator
758 I = moduleConstants.begin(),
759 E = moduleConstants.end(); I != E; ++I)
762 // Section 2 : Initialized read-write data section
763 enterSection(AsmPrinter::InitRWData);
764 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
765 if ((*GI)->hasInitializer() && ! (*GI)->isConstant())
766 printGlobalVariable(*GI);
768 // Section 3 : Uninitialized read-write data section
769 enterSection(AsmPrinter::UninitRWData);
770 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
771 if (! (*GI)->hasInitializer())
772 printGlobalVariable(*GI);
777 } // End anonymous namespace
779 Pass *UltraSparc::getModuleAsmPrinterPass(PassManager &PM, std::ostream &Out) {
780 return new SparcModuleAsmPrinter(Out, *this);