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/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/Pass.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "Support/StringExtras.h"
28 #include "Support/HashExtras.h"
34 class GlobalIdTable: public Annotation {
35 static AnnotationID AnnotId;
36 friend class AsmPrinter; // give access to AnnotId
38 typedef std::hash_map<const Value*, int> ValIdMap;
39 typedef ValIdMap::const_iterator ValIdMapConstIterator;
40 typedef ValIdMap:: iterator ValIdMapIterator;
42 SlotCalculator Table; // map anonymous values to unique integer IDs
43 ValIdMap valToIdMap; // used for values not handled by SlotCalculator
45 GlobalIdTable(Module* M) : Annotation(AnnotId), Table(M, true) {}
48 AnnotationID GlobalIdTable::AnnotId =
49 AnnotationManager::getID("ASM PRINTER GLOBAL TABLE ANNOT");
51 //===---------------------------------------------------------------------===//
52 // Code Shared By the two printer passes, as a mixin
53 //===---------------------------------------------------------------------===//
56 GlobalIdTable* idTable;
59 const TargetMachine &Target;
69 AsmPrinter(std::ostream &os, const TargetMachine &T)
70 : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
72 // (start|end)(Module|Function) - Callback methods to be invoked by subclasses
73 void startModule(Module *M) {
74 // Create the global id table if it does not already exist
75 idTable = (GlobalIdTable*) M->getAnnotation(GlobalIdTable::AnnotId);
76 if (idTable == NULL) {
77 idTable = new GlobalIdTable(M);
78 M->addAnnotation(idTable);
81 void startFunction(Function *F) {
82 // Make sure the slot table has information about this function...
83 idTable->Table.incorporateFunction(F);
85 void endFunction(Function *F) {
86 idTable->Table.purgeFunction(); // Forget all about F
91 // Check if a name is external or accessible from external code.
92 // Only functions can currently be external. "main" is the only name
93 // that is visible externally.
94 bool isExternal(const Value* V) {
95 const Function *F = dyn_cast<Function>(V);
96 return F && (F->isExternal() || F->getName() == "main");
99 // enterSection - Use this method to enter a different section of the output
100 // executable. This is used to only output neccesary section transitions.
102 void enterSection(enum Sections S) {
103 if (S == CurSection) return; // Only switch section if neccesary
106 toAsm << "\n\t.section ";
109 default: assert(0 && "Bad section name!");
110 case Text: toAsm << "\".text\""; break;
111 case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
112 case InitRWData: toAsm << "\".data\",#alloc,#write"; break;
113 case UninitRWData: toAsm << "\".bss\",#alloc,#write\nBbss.bss:"; break;
118 static std::string getValidSymbolName(const string &S) {
121 // Symbol names in Sparc assembly language have these rules:
122 // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
123 // (b) A name beginning in "." is treated as a local name.
124 // (c) Names beginning with "_" are reserved by ANSI C and shd not be used.
126 if (S[0] == '_' || isdigit(S[0]))
129 for (unsigned i = 0; i < S.size(); ++i)
132 if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
137 Result += char('0' + ((unsigned char)C >> 4));
138 Result += char('0' + (C & 0xF));
144 // getID - Return a valid identifier for the specified value. Base it on
145 // the name of the identifier if possible (qualified by the type), and
146 // use a numbered value based on prefix otherwise.
147 // FPrefix is always prepended to the output identifier.
149 string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
150 string Result = FPrefix ? FPrefix : ""; // "Forced prefix"
152 Result = Result + (V->hasName()? V->getName() : string(Prefix));
154 // Qualify all internal names with a unique id.
155 if (!isExternal(V)) {
156 int valId = idTable->Table.getValSlot(V);
158 GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
159 if (I == idTable->valToIdMap.end())
160 valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
164 Result = Result + "_" + itostr(valId);
167 return getValidSymbolName(Result);
170 // getID Wrappers - Ensure consistent usage...
171 string getID(const Function *F) {
172 return getID(F, "LLVMFunction_");
174 string getID(const BasicBlock *BB) {
175 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
177 string getID(const GlobalVariable *GV) {
178 return getID(GV, "LLVMGlobal_", ".G_");
180 string getID(const Constant *CV) {
181 return getID(CV, "LLVMConst_", ".C_");
187 //===----------------------------------------------------------------------===//
188 // SparcFunctionAsmPrinter Code
189 //===----------------------------------------------------------------------===//
191 struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
192 inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
193 : AsmPrinter(os, t) {}
195 virtual bool doInitialization(Module *M) {
200 virtual bool runOnFunction(Function *F) {
207 virtual bool doFinalization(Module *M) {
212 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
213 AU.setPreservesAll();
216 void emitFunction(const Function *F);
218 void emitBasicBlock(const BasicBlock *BB);
219 void emitMachineInst(const MachineInstr *MI);
221 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
222 void printOneOperand(const MachineOperand &Op);
224 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
225 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
227 unsigned getOperandMask(unsigned Opcode) {
229 case SUBcc: return 1 << 3; // Remove CC argument
230 case BA: return 1 << 0; // Remove Arg #0, which is always null or xcc
231 default: return 0; // By default, don't hack operands...
237 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
238 unsigned int opNum) {
239 switch (MI->getOpCode()) {
241 case JMPLRET: return (opNum == 0);
242 default: return false;
248 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
249 unsigned int opNum) {
250 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
252 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
259 #define PrintOp1PlusOp2(Op1, Op2) \
260 printOneOperand(Op1); \
262 printOneOperand(Op2);
265 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
268 const MachineOperand& Op = MI->getOperand(opNum);
270 if (OpIsBranchTargetLabel(MI, opNum))
272 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
275 else if (OpIsMemoryAddressBase(MI, opNum))
278 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
291 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &op)
293 switch (op.getOperandType())
295 case MachineOperand::MO_VirtualRegister:
296 case MachineOperand::MO_CCRegister:
297 case MachineOperand::MO_MachineRegister:
299 int RegNum = (int)op.getAllocatedRegNum();
301 // better to print code with NULL registers than to die
302 if (RegNum == Target.getRegInfo().getInvalidRegNum()) {
303 toAsm << "<NULL VALUE>";
305 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
310 case MachineOperand::MO_PCRelativeDisp:
312 const Value *Val = op.getVRegValue();
314 toAsm << "\t<*NULL Value*>";
315 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(Val))
317 else if (const Function *M = dyn_cast<Function>(Val))
319 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
321 else if (const Constant *CV = dyn_cast<Constant>(Val))
324 toAsm << "<unknown value=" << Val << ">";
328 case MachineOperand::MO_SignExtendedImmed:
329 case MachineOperand::MO_UnextendedImmed:
330 toAsm << (long)op.getImmedValue();
334 toAsm << op; // use dump field
341 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
343 unsigned Opcode = MI->getOpCode();
345 if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
346 return; // IGNORE PHI NODES
348 toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
350 unsigned Mask = getOperandMask(Opcode);
352 bool NeedComma = false;
354 for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
355 if (! ((1 << OpNum) & Mask)) { // Ignore this operand?
356 if (NeedComma) toAsm << ", "; // Handle comma outputing
358 N = printOperands(MI, OpNum);
367 SparcFunctionAsmPrinter::emitBasicBlock(const BasicBlock *BB)
369 // Emit a label for the basic block
370 toAsm << getID(BB) << ":\n";
372 // Get the vector of machine instructions corresponding to this bb.
373 const MachineCodeForBasicBlock &MIs = BB->getMachineInstrVec();
374 MachineCodeForBasicBlock::const_iterator MII = MIs.begin(), MIE = MIs.end();
376 // Loop over all of the instructions in the basic block...
377 for (; MII != MIE; ++MII)
378 emitMachineInst(*MII);
379 toAsm << "\n"; // Seperate BB's with newlines
383 SparcFunctionAsmPrinter::emitFunction(const Function *M)
385 string methName = getID(M);
386 toAsm << "!****** Outputing Function: " << methName << " ******\n";
387 enterSection(AsmPrinter::Text);
388 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
389 //toAsm << "\t.type\t" << methName << ",#function\n";
390 toAsm << "\t.type\t" << methName << ", 2\n";
391 toAsm << methName << ":\n";
393 // Output code for all of the basic blocks in the function...
394 for (Function::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
397 // Output a .size directive so the debugger knows the extents of the function
398 toAsm << ".EndOf_" << methName << ":\n\t.size "
399 << methName << ", .EndOf_"
400 << methName << "-" << methName << "\n";
402 // Put some spaces between the functions
406 } // End anonymous namespace
408 Pass *UltraSparc::getFunctionAsmPrinterPass(PassManager &PM, std::ostream &Out){
409 return new SparcFunctionAsmPrinter(Out, *this);
416 //===----------------------------------------------------------------------===//
417 // SparcFunctionAsmPrinter Code
418 //===----------------------------------------------------------------------===//
422 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
424 SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
425 : AsmPrinter(os, t) {}
427 virtual bool run(Module *M) {
429 emitGlobalsAndConstants(M);
434 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
435 AU.setPreservesAll();
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);
451 // Can we treat the specified array as a string? Only if it is an array of
452 // ubytes or non-negative sbytes.
454 static bool isStringCompatible(ConstantArray *CPA) {
455 const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
456 if (ETy == Type::UByteTy) return true;
457 if (ETy != Type::SByteTy) return false;
459 for (unsigned i = 0; i < CPA->getNumOperands(); ++i)
460 if (cast<ConstantSInt>(CPA->getOperand(i))->getValue() < 0)
466 // toOctal - Convert the low order bits of X into an octal letter
467 static inline char toOctal(int X) {
471 // getAsCString - Return the specified array as a C compatible string, only if
472 // the predicate isStringCompatible is true.
474 static string getAsCString(ConstantArray *CPA) {
475 assert(isStringCompatible(CPA) && "Array is not string compatible!");
478 const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
480 for (unsigned i = 0; i < CPA->getNumOperands(); ++i) {
481 unsigned char C = (ETy == Type::SByteTy) ?
482 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
483 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
489 case '\a': Result += "\\a"; break;
490 case '\b': Result += "\\b"; break;
491 case '\f': Result += "\\f"; break;
492 case '\n': Result += "\\n"; break;
493 case '\r': Result += "\\r"; break;
494 case '\t': Result += "\\t"; break;
495 case '\v': Result += "\\v"; break;
498 Result += toOctal(C >> 6);
499 Result += toOctal(C >> 3);
500 Result += toOctal(C >> 0);
511 ArrayTypeIsString(ArrayType* arrayType)
513 return (arrayType->getElementType() == Type::UByteTy ||
514 arrayType->getElementType() == Type::SByteTy);
518 TypeToDataDirective(const Type* type)
520 switch(type->getPrimitiveID())
522 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
524 case Type::UShortTyID: case Type::ShortTyID:
526 case Type::UIntTyID: case Type::IntTyID:
528 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
530 case Type::FloatTyID:
532 case Type::DoubleTyID:
534 case Type::ArrayTyID:
535 if (ArrayTypeIsString((ArrayType*) type))
538 return "<InvaliDataTypeForPrinting>";
540 return "<InvaliDataTypeForPrinting>";
544 // Get the size of the constant for the given target.
545 // If this is an unsized array, return 0.
548 ConstantToSize(const Constant* CV, const TargetMachine& target)
550 if (ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
552 ArrayType *aty = cast<ArrayType>(CPA->getType());
553 if (ArrayTypeIsString(aty))
554 return 1 + CPA->getNumOperands();
557 return target.findOptimalStorageSize(CV->getType());
562 // Align data larger than one L1 cache line on L1 cache line boundaries.
563 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
566 SizeToAlignment(unsigned int size, const TargetMachine& target)
568 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
569 if (size > (unsigned) cacheLineSize / 2)
570 return cacheLineSize;
572 for (unsigned sz=1; /*no condition*/; sz *= 2)
577 // Get the size of the type and then use SizeToAlignment.
580 TypeToAlignment(const Type* type, const TargetMachine& target)
582 return SizeToAlignment(target.findOptimalStorageSize(type), target);
585 // Get the size of the constant and then use SizeToAlignment.
586 // Handles strings as a special case;
588 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
590 if (ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
591 if (ArrayTypeIsString(cast<ArrayType>(CPA->getType())))
592 return SizeToAlignment(1 + CPA->getNumOperands(), target);
594 return TypeToAlignment(CV->getType(), target);
598 // Print a single constant value.
600 SparcModuleAsmPrinter::printSingleConstant(const Constant* CV)
602 assert(CV->getType() != Type::VoidTy &&
603 CV->getType() != Type::TypeTy &&
604 CV->getType() != Type::LabelTy &&
605 "Unexpected type for Constant");
607 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
608 && "Aggregate types should be handled outside this function");
610 toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
612 if (CV->getType()->isPrimitiveType())
614 if (CV->getType()->isFloatingPoint()) {
615 // FP Constants are printed as integer constants to avoid losing
617 double Val = cast<ConstantFP>(CV)->getValue();
618 if (CV->getType() == Type::FloatTy) {
619 float FVal = (float)Val;
620 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
621 toAsm << *(unsigned int*)ProxyPtr;
622 } else if (CV->getType() == Type::DoubleTy) {
623 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
624 toAsm << *(uint64_t*)ProxyPtr;
626 assert(0 && "Unknown floating point type!");
629 toAsm << "\t! " << CV->getType()->getDescription()
630 << " value: " << Val << "\n";
632 WriteAsOperand(toAsm, CV, false, false) << "\n";
635 else if (ConstantPointer* CPP = dyn_cast<ConstantPointer>(CV))
637 assert(CPP->isNullValue() &&
638 "Cannot yet print non-null pointer constants to assembly");
641 else if (isa<ConstantPointerRef>(CV))
643 assert(0 && "Cannot yet initialize pointer refs in assembly");
647 assert(0 && "Unknown elementary type for constant");
651 // Print a constant value or values (it may be an aggregate).
652 // Uses printSingleConstant() to print each individual value.
654 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV)
656 ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
658 if (CPA && isStringCompatible(CPA))
659 { // print the string alone and return
660 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
663 { // Not a string. Print the values in successive locations
664 const std::vector<Use> &constValues = CPA->getValues();
665 for (unsigned i=1; i < constValues.size(); i++)
666 this->printConstantValueOnly(cast<Constant>(constValues[i].get()));
668 else if (ConstantStruct *CPS = dyn_cast<ConstantStruct>(CV))
669 { // Print the fields in successive locations
670 const std::vector<Use>& constValues = CPS->getValues();
671 for (unsigned i=1; i < constValues.size(); i++)
672 this->printConstantValueOnly(cast<Constant>(constValues[i].get()));
675 this->printSingleConstant(CV);
678 // Print a constant (which may be an aggregate) prefixed by all the
679 // appropriate directives. Uses printConstantValueOnly() to print the
682 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
684 if (valID.length() == 0)
687 toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
689 // Print .size and .type only if it is not a string.
690 ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
691 if (CPA && isStringCompatible(CPA))
692 { // print it as a string and return
693 toAsm << valID << ":\n";
694 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
698 toAsm << "\t.type" << "\t" << valID << ",#object\n";
700 unsigned int constSize = ConstantToSize(CV, Target);
702 toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
704 toAsm << valID << ":\n";
706 printConstantValueOnly(CV);
710 void SparcModuleAsmPrinter::FoldConstants(const Module *M,
711 std::hash_set<const Constant*> &MC) {
712 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
713 if (!(*I)->isExternal()) {
714 const std::hash_set<const Constant*> &pool =
715 MachineCodeForMethod::get(*I).getConstantPoolValues();
716 MC.insert(pool.begin(), pool.end());
720 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
722 toAsm << "\t.global\t" << getID(GV) << "\n";
724 if (GV->hasInitializer())
725 printConstant(GV->getInitializer(), getID(GV));
727 toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
729 toAsm << "\t.type\t" << getID(GV) << ",#object\n";
730 toAsm << "\t.reserve\t" << getID(GV) << ","
731 << Target.findOptimalStorageSize(GV->getType()->getElementType())
737 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module *M) {
738 // First, get the constants there were marked by the code generator for
739 // inclusion in the assembly code data area and fold them all into a
740 // single constant pool since there may be lots of duplicates. Also,
741 // lets force these constants into the slot table so that we can get
742 // unique names for unnamed constants also.
744 std::hash_set<const Constant*> moduleConstants;
745 FoldConstants(M, moduleConstants);
747 // Now, emit the three data sections separately; the cost of I/O should
748 // make up for the cost of extra passes over the globals list!
750 // Section 1 : Read-only data section (implies initialized)
751 enterSection(AsmPrinter::ReadOnlyData);
752 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
753 if ((*GI)->hasInitializer() && (*GI)->isConstant())
754 printGlobalVariable(*GI);
756 for (std::hash_set<const Constant*>::const_iterator
757 I = moduleConstants.begin(),
758 E = moduleConstants.end(); I != E; ++I)
761 // Section 2 : Initialized read-write data section
762 enterSection(AsmPrinter::InitRWData);
763 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
764 if ((*GI)->hasInitializer() && ! (*GI)->isConstant())
765 printGlobalVariable(*GI);
767 // Section 3 : Uninitialized read-write data section
768 enterSection(AsmPrinter::UninitRWData);
769 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
770 if (! (*GI)->hasInitializer())
771 printGlobalVariable(*GI);
776 } // End anonymous namespace
778 Pass *UltraSparc::getModuleAsmPrinterPass(PassManager &PM, std::ostream &Out) {
779 return new SparcModuleAsmPrinter(Out, *this);