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 const char *getPassName() const {
196 return "Output Sparc Assembly for Functions";
199 virtual bool doInitialization(Module *M) {
204 virtual bool runOnFunction(Function *F) {
211 virtual bool doFinalization(Module *M) {
216 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
217 AU.setPreservesAll();
220 void emitFunction(const Function *F);
222 void emitBasicBlock(const BasicBlock *BB);
223 void emitMachineInst(const MachineInstr *MI);
225 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
226 void printOneOperand(const MachineOperand &Op);
228 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
229 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
231 unsigned getOperandMask(unsigned Opcode) {
233 case SUBcc: return 1 << 3; // Remove CC argument
234 case BA: return 1 << 0; // Remove Arg #0, which is always null or xcc
235 default: return 0; // By default, don't hack operands...
241 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
242 unsigned int opNum) {
243 switch (MI->getOpCode()) {
245 case JMPLRET: return (opNum == 0);
246 default: return false;
252 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
253 unsigned int opNum) {
254 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
256 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
263 #define PrintOp1PlusOp2(Op1, Op2) \
264 printOneOperand(Op1); \
266 printOneOperand(Op2);
269 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
272 const MachineOperand& Op = MI->getOperand(opNum);
274 if (OpIsBranchTargetLabel(MI, opNum))
276 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
279 else if (OpIsMemoryAddressBase(MI, opNum))
282 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
295 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &op)
297 switch (op.getOperandType())
299 case MachineOperand::MO_VirtualRegister:
300 case MachineOperand::MO_CCRegister:
301 case MachineOperand::MO_MachineRegister:
303 int RegNum = (int)op.getAllocatedRegNum();
305 // better to print code with NULL registers than to die
306 if (RegNum == Target.getRegInfo().getInvalidRegNum()) {
307 toAsm << "<NULL VALUE>";
309 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
314 case MachineOperand::MO_PCRelativeDisp:
316 const Value *Val = op.getVRegValue();
318 toAsm << "\t<*NULL Value*>";
319 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(Val))
321 else if (const Function *M = dyn_cast<Function>(Val))
323 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
325 else if (const Constant *CV = dyn_cast<Constant>(Val))
328 toAsm << "<unknown value=" << Val << ">";
332 case MachineOperand::MO_SignExtendedImmed:
333 case MachineOperand::MO_UnextendedImmed:
334 toAsm << (long)op.getImmedValue();
338 toAsm << op; // use dump field
345 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
347 unsigned Opcode = MI->getOpCode();
349 if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
350 return; // IGNORE PHI NODES
352 toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
354 unsigned Mask = getOperandMask(Opcode);
356 bool NeedComma = false;
358 for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
359 if (! ((1 << OpNum) & Mask)) { // Ignore this operand?
360 if (NeedComma) toAsm << ", "; // Handle comma outputing
362 N = printOperands(MI, OpNum);
371 SparcFunctionAsmPrinter::emitBasicBlock(const BasicBlock *BB)
373 // Emit a label for the basic block
374 toAsm << getID(BB) << ":\n";
376 // Get the vector of machine instructions corresponding to this bb.
377 const MachineCodeForBasicBlock &MIs = BB->getMachineInstrVec();
378 MachineCodeForBasicBlock::const_iterator MII = MIs.begin(), MIE = MIs.end();
380 // Loop over all of the instructions in the basic block...
381 for (; MII != MIE; ++MII)
382 emitMachineInst(*MII);
383 toAsm << "\n"; // Seperate BB's with newlines
387 SparcFunctionAsmPrinter::emitFunction(const Function *M)
389 string methName = getID(M);
390 toAsm << "!****** Outputing Function: " << methName << " ******\n";
391 enterSection(AsmPrinter::Text);
392 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
393 //toAsm << "\t.type\t" << methName << ",#function\n";
394 toAsm << "\t.type\t" << methName << ", 2\n";
395 toAsm << methName << ":\n";
397 // Output code for all of the basic blocks in the function...
398 for (Function::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
401 // Output a .size directive so the debugger knows the extents of the function
402 toAsm << ".EndOf_" << methName << ":\n\t.size "
403 << methName << ", .EndOf_"
404 << methName << "-" << methName << "\n";
406 // Put some spaces between the functions
410 } // End anonymous namespace
412 Pass *UltraSparc::getFunctionAsmPrinterPass(PassManager &PM, std::ostream &Out){
413 return new SparcFunctionAsmPrinter(Out, *this);
420 //===----------------------------------------------------------------------===//
421 // SparcFunctionAsmPrinter Code
422 //===----------------------------------------------------------------------===//
426 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
428 SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
429 : AsmPrinter(os, t) {}
431 const char *getPassName() const { return "Output Sparc Assembly for Module"; }
433 virtual bool run(Module *M) {
435 emitGlobalsAndConstants(M);
440 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
441 AU.setPreservesAll();
445 void emitGlobalsAndConstants(const Module *M);
447 void printGlobalVariable(const GlobalVariable *GV);
448 void printSingleConstant( const Constant* CV);
449 void printConstantValueOnly(const Constant* CV);
450 void printConstant( const Constant* CV, std::string valID = "");
452 static void FoldConstants(const Module *M,
453 std::hash_set<const Constant*> &moduleConstants);
457 // Can we treat the specified array as a string? Only if it is an array of
458 // ubytes or non-negative sbytes.
460 static bool isStringCompatible(ConstantArray *CPA) {
461 const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
462 if (ETy == Type::UByteTy) return true;
463 if (ETy != Type::SByteTy) return false;
465 for (unsigned i = 0; i < CPA->getNumOperands(); ++i)
466 if (cast<ConstantSInt>(CPA->getOperand(i))->getValue() < 0)
472 // toOctal - Convert the low order bits of X into an octal letter
473 static inline char toOctal(int X) {
477 // getAsCString - Return the specified array as a C compatible string, only if
478 // the predicate isStringCompatible is true.
480 static string getAsCString(ConstantArray *CPA) {
481 assert(isStringCompatible(CPA) && "Array is not string compatible!");
484 const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
486 for (unsigned i = 0; i < CPA->getNumOperands(); ++i) {
487 unsigned char C = (ETy == Type::SByteTy) ?
488 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
489 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
495 case '\a': Result += "\\a"; break;
496 case '\b': Result += "\\b"; break;
497 case '\f': Result += "\\f"; break;
498 case '\n': Result += "\\n"; break;
499 case '\r': Result += "\\r"; break;
500 case '\t': Result += "\\t"; break;
501 case '\v': Result += "\\v"; break;
504 Result += toOctal(C >> 6);
505 Result += toOctal(C >> 3);
506 Result += toOctal(C >> 0);
517 ArrayTypeIsString(ArrayType* arrayType)
519 return (arrayType->getElementType() == Type::UByteTy ||
520 arrayType->getElementType() == Type::SByteTy);
524 TypeToDataDirective(const Type* type)
526 switch(type->getPrimitiveID())
528 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
530 case Type::UShortTyID: case Type::ShortTyID:
532 case Type::UIntTyID: case Type::IntTyID:
534 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
536 case Type::FloatTyID:
538 case Type::DoubleTyID:
540 case Type::ArrayTyID:
541 if (ArrayTypeIsString((ArrayType*) type))
544 return "<InvaliDataTypeForPrinting>";
546 return "<InvaliDataTypeForPrinting>";
550 // Get the size of the constant for the given target.
551 // If this is an unsized array, return 0.
554 ConstantToSize(const Constant* CV, const TargetMachine& target)
556 if (ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
558 ArrayType *aty = cast<ArrayType>(CPA->getType());
559 if (ArrayTypeIsString(aty))
560 return 1 + CPA->getNumOperands();
563 return target.findOptimalStorageSize(CV->getType());
568 // Align data larger than one L1 cache line on L1 cache line boundaries.
569 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
572 SizeToAlignment(unsigned int size, const TargetMachine& target)
574 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
575 if (size > (unsigned) cacheLineSize / 2)
576 return cacheLineSize;
578 for (unsigned sz=1; /*no condition*/; sz *= 2)
583 // Get the size of the type and then use SizeToAlignment.
586 TypeToAlignment(const Type* type, const TargetMachine& target)
588 return SizeToAlignment(target.findOptimalStorageSize(type), target);
591 // Get the size of the constant and then use SizeToAlignment.
592 // Handles strings as a special case;
594 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
596 if (ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
597 if (ArrayTypeIsString(cast<ArrayType>(CPA->getType())))
598 return SizeToAlignment(1 + CPA->getNumOperands(), target);
600 return TypeToAlignment(CV->getType(), target);
604 // Print a single constant value.
606 SparcModuleAsmPrinter::printSingleConstant(const Constant* CV)
608 assert(CV->getType() != Type::VoidTy &&
609 CV->getType() != Type::TypeTy &&
610 CV->getType() != Type::LabelTy &&
611 "Unexpected type for Constant");
613 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
614 && "Aggregate types should be handled outside this function");
616 toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
618 if (CV->getType()->isPrimitiveType())
620 if (CV->getType()->isFloatingPoint()) {
621 // FP Constants are printed as integer constants to avoid losing
623 double Val = cast<ConstantFP>(CV)->getValue();
624 if (CV->getType() == Type::FloatTy) {
625 float FVal = (float)Val;
626 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
627 toAsm << *(unsigned int*)ProxyPtr;
628 } else if (CV->getType() == Type::DoubleTy) {
629 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
630 toAsm << *(uint64_t*)ProxyPtr;
632 assert(0 && "Unknown floating point type!");
635 toAsm << "\t! " << CV->getType()->getDescription()
636 << " value: " << Val << "\n";
638 WriteAsOperand(toAsm, CV, false, false) << "\n";
641 else if (ConstantPointer* CPP = dyn_cast<ConstantPointer>(CV))
643 assert(CPP->isNullValue() &&
644 "Cannot yet print non-null pointer constants to assembly");
647 else if (isa<ConstantPointerRef>(CV))
649 assert(0 && "Cannot yet initialize pointer refs in assembly");
653 assert(0 && "Unknown elementary type for constant");
657 // Print a constant value or values (it may be an aggregate).
658 // Uses printSingleConstant() to print each individual value.
660 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV)
662 ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
664 if (CPA && isStringCompatible(CPA))
665 { // print the string alone and return
666 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
669 { // Not a string. Print the values in successive locations
670 const std::vector<Use> &constValues = CPA->getValues();
671 for (unsigned i=1; i < constValues.size(); i++)
672 this->printConstantValueOnly(cast<Constant>(constValues[i].get()));
674 else if (ConstantStruct *CPS = dyn_cast<ConstantStruct>(CV))
675 { // Print the fields in successive locations
676 const std::vector<Use>& constValues = CPS->getValues();
677 for (unsigned i=1; i < constValues.size(); i++)
678 this->printConstantValueOnly(cast<Constant>(constValues[i].get()));
681 this->printSingleConstant(CV);
684 // Print a constant (which may be an aggregate) prefixed by all the
685 // appropriate directives. Uses printConstantValueOnly() to print the
688 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
690 if (valID.length() == 0)
693 toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
695 // Print .size and .type only if it is not a string.
696 ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
697 if (CPA && isStringCompatible(CPA))
698 { // print it as a string and return
699 toAsm << valID << ":\n";
700 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
704 toAsm << "\t.type" << "\t" << valID << ",#object\n";
706 unsigned int constSize = ConstantToSize(CV, Target);
708 toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
710 toAsm << valID << ":\n";
712 printConstantValueOnly(CV);
716 void SparcModuleAsmPrinter::FoldConstants(const Module *M,
717 std::hash_set<const Constant*> &MC) {
718 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
719 if (!(*I)->isExternal()) {
720 const std::hash_set<const Constant*> &pool =
721 MachineCodeForMethod::get(*I).getConstantPoolValues();
722 MC.insert(pool.begin(), pool.end());
726 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
728 toAsm << "\t.global\t" << getID(GV) << "\n";
730 if (GV->hasInitializer())
731 printConstant(GV->getInitializer(), getID(GV));
733 toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
735 toAsm << "\t.type\t" << getID(GV) << ",#object\n";
736 toAsm << "\t.reserve\t" << getID(GV) << ","
737 << Target.findOptimalStorageSize(GV->getType()->getElementType())
743 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module *M) {
744 // First, get the constants there were marked by the code generator for
745 // inclusion in the assembly code data area and fold them all into a
746 // single constant pool since there may be lots of duplicates. Also,
747 // lets force these constants into the slot table so that we can get
748 // unique names for unnamed constants also.
750 std::hash_set<const Constant*> moduleConstants;
751 FoldConstants(M, moduleConstants);
753 // Now, emit the three data sections separately; the cost of I/O should
754 // make up for the cost of extra passes over the globals list!
756 // Section 1 : Read-only data section (implies initialized)
757 enterSection(AsmPrinter::ReadOnlyData);
758 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
759 if ((*GI)->hasInitializer() && (*GI)->isConstant())
760 printGlobalVariable(*GI);
762 for (std::hash_set<const Constant*>::const_iterator
763 I = moduleConstants.begin(),
764 E = moduleConstants.end(); I != E; ++I)
767 // Section 2 : Initialized read-write data section
768 enterSection(AsmPrinter::InitRWData);
769 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
770 if ((*GI)->hasInitializer() && ! (*GI)->isConstant())
771 printGlobalVariable(*GI);
773 // Section 3 : Uninitialized read-write data section
774 enterSection(AsmPrinter::UninitRWData);
775 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
776 if (! (*GI)->hasInitializer())
777 printGlobalVariable(*GI);
782 } // End anonymous namespace
784 Pass *UltraSparc::getModuleAsmPrinterPass(PassManager &PM, std::ostream &Out) {
785 return new SparcModuleAsmPrinter(Out, *this);