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 MethodPass and a Pass. The
8 // MethodPass is pipelined together with all of the rest of the code generation
9 // stages, and the Pass runs at the end to emit code for global variables and
12 //===----------------------------------------------------------------------===//
14 #include "SparcInternals.h"
15 #include "llvm/Analysis/SlotCalculator.h"
16 #include "llvm/CodeGen/MachineInstr.h"
17 #include "llvm/CodeGen/MachineCodeForMethod.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/ConstantVals.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/Method.h"
23 #include "llvm/Module.h"
24 #include "Support/StringExtras.h"
25 #include "Support/HashExtras.h"
31 //===----------------------------------------------------------------------===//
32 // Code Shared By the two printer passes, as a mixin
33 //===----------------------------------------------------------------------===//
36 typedef std::hash_map<const Value*, int> ValIdMap;
37 typedef ValIdMap:: iterator ValIdMapIterator;
38 typedef ValIdMap::const_iterator ValIdMapConstIterator;
40 SlotCalculator *Table; // map anonymous values to unique integer IDs
41 ValIdMap valToIdMap; // used for values not handled by SlotCalculator
44 const TargetMachine &Target;
54 AsmPrinter(std::ostream &os, const TargetMachine &T)
55 : Table(0), toAsm(os), Target(T), CurSection(Unknown) {}
58 // (start|end)(Module|Method) - Callback methods to be invoked by subclasses
59 void startModule(Module *M) {
60 Table = new SlotCalculator(M, true);
62 void startMethod(Method *M) {
63 // Make sure the slot table has information about this method...
64 Table->incorporateMethod(M);
66 void endMethod(Method *M) {
67 Table->purgeMethod(); // Forget all about M.
70 delete Table; Table = 0;
75 // enterSection - Use this method to enter a different section of the output
76 // executable. This is used to only output neccesary section transitions.
78 void enterSection(enum Sections S) {
79 if (S == CurSection) return; // Only switch section if neccesary
82 toAsm << "\n\t.section ";
85 default: assert(0 && "Bad section name!");
86 case Text: toAsm << "\".text\""; break;
87 case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
88 case InitRWData: toAsm << "\".data\",#alloc,#write"; break;
89 case UninitRWData: toAsm << "\".bss\",#alloc,#write\nBbss.bss:"; break;
94 static std::string getValidSymbolName(const string &S) {
97 // Symbol names in Sparc assembly language have these rules:
98 // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
99 // (b) A name beginning in "." is treated as a local name.
100 // (c) Names beginning with "_" are reserved by ANSI C and shd not be used.
102 if (S[0] == '_' || isdigit(S[0]))
105 for (unsigned i = 0; i < S.size(); ++i)
108 if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
113 Result += char('0' + ((unsigned char)C >> 4));
114 Result += char('0' + (C & 0xF));
120 // getID - Return a valid identifier for the specified value. Base it on
121 // the name of the identifier if possible, use a numbered value based on
122 // prefix otherwise. FPrefix is always prepended to the output identifier.
124 string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
126 string FP(FPrefix ? FPrefix : ""); // "Forced prefix"
128 Result = FP + V->getName();
130 int valId = Table->getValSlot(V);
132 ValIdMapConstIterator I = valToIdMap.find(V);
133 if (I == valToIdMap.end())
134 valId = valToIdMap[V] = valToIdMap.size();
138 Result = FP + string(Prefix) + itostr(valId);
140 return getValidSymbolName(Result);
143 // getID Wrappers - Ensure consistent usage...
144 string getID(const Module *M) {
145 return getID(M, "LLVMModule_");
147 string getID(const Method *M) {
148 return getID(M, "LLVMMethod_");
150 string getID(const BasicBlock *BB) {
151 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
153 string getID(const GlobalVariable *GV) {
154 return getID(GV, "LLVMGlobal_", ".G_");
156 string getID(const Constant *CV) {
157 return getID(CV, "LLVMConst_", ".C_");
163 //===----------------------------------------------------------------------===//
164 // SparcMethodAsmPrinter Code
165 //===----------------------------------------------------------------------===//
167 struct SparcMethodAsmPrinter : public MethodPass, public AsmPrinter {
168 inline SparcMethodAsmPrinter(std::ostream &os, const TargetMachine &t)
169 : AsmPrinter(os, t) {}
171 virtual bool doInitialization(Module *M) {
176 virtual bool runOnMethod(Method *M) {
183 virtual bool doFinalization(Module *M) {
188 void emitMethod(const Method *M);
190 void emitBasicBlock(const BasicBlock *BB);
191 void emitMachineInst(const MachineInstr *MI);
193 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
194 void printOneOperand(const MachineOperand &Op);
196 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
197 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
199 unsigned getOperandMask(unsigned Opcode) {
201 case SUBcc: return 1 << 3; // Remove CC argument
202 case BA: return 1 << 0; // Remove Arg #0, which is always null or xcc
203 default: return 0; // By default, don't hack operands...
209 SparcMethodAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
210 unsigned int opNum) {
211 switch (MI->getOpCode()) {
213 case JMPLRET: return (opNum == 0);
214 default: return false;
220 SparcMethodAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
221 unsigned int opNum) {
222 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
224 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
231 #define PrintOp1PlusOp2(Op1, Op2) \
232 printOneOperand(Op1); \
234 printOneOperand(Op2);
237 SparcMethodAsmPrinter::printOperands(const MachineInstr *MI,
240 const MachineOperand& Op = MI->getOperand(opNum);
242 if (OpIsBranchTargetLabel(MI, opNum))
244 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
247 else if (OpIsMemoryAddressBase(MI, opNum))
250 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
263 SparcMethodAsmPrinter::printOneOperand(const MachineOperand &op)
265 switch (op.getOperandType())
267 case MachineOperand::MO_VirtualRegister:
268 case MachineOperand::MO_CCRegister:
269 case MachineOperand::MO_MachineRegister:
271 int RegNum = (int)op.getAllocatedRegNum();
273 // ****this code is temporary till NULL Values are fixed
274 if (RegNum == Target.getRegInfo().getInvalidRegNum()) {
275 toAsm << "<NULL VALUE>";
277 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
282 case MachineOperand::MO_PCRelativeDisp:
284 const Value *Val = op.getVRegValue();
286 toAsm << "\t<*NULL Value*>";
287 else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(Val))
289 else if (const Method *M = dyn_cast<const Method>(Val))
291 else if (const GlobalVariable *GV=dyn_cast<const GlobalVariable>(Val))
293 else if (const Constant *CV = dyn_cast<const Constant>(Val))
296 toAsm << "<unknown value=" << Val << ">";
300 case MachineOperand::MO_SignExtendedImmed:
301 case MachineOperand::MO_UnextendedImmed:
302 toAsm << (long)op.getImmedValue();
306 toAsm << op; // use dump field
313 SparcMethodAsmPrinter::emitMachineInst(const MachineInstr *MI)
315 unsigned Opcode = MI->getOpCode();
317 if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
318 return; // IGNORE PHI NODES
320 toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
322 unsigned Mask = getOperandMask(Opcode);
324 bool NeedComma = false;
326 for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
327 if (! ((1 << OpNum) & Mask)) { // Ignore this operand?
328 if (NeedComma) toAsm << ", "; // Handle comma outputing
330 N = printOperands(MI, OpNum);
339 SparcMethodAsmPrinter::emitBasicBlock(const BasicBlock *BB)
341 // Emit a label for the basic block
342 toAsm << getID(BB) << ":\n";
344 // Get the vector of machine instructions corresponding to this bb.
345 const MachineCodeForBasicBlock &MIs = BB->getMachineInstrVec();
346 MachineCodeForBasicBlock::const_iterator MII = MIs.begin(), MIE = MIs.end();
348 // Loop over all of the instructions in the basic block...
349 for (; MII != MIE; ++MII)
350 emitMachineInst(*MII);
351 toAsm << "\n"; // Seperate BB's with newlines
355 SparcMethodAsmPrinter::emitMethod(const Method *M)
357 string methName = getID(M);
358 toAsm << "!****** Outputing Method: " << methName << " ******\n";
359 enterSection(AsmPrinter::Text);
360 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
361 //toAsm << "\t.type\t" << methName << ",#function\n";
362 toAsm << "\t.type\t" << methName << ", 2\n";
363 toAsm << methName << ":\n";
365 // Output code for all of the basic blocks in the method...
366 for (Method::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
369 // Output a .size directive so the debugger knows the extents of the function
370 toAsm << ".EndOf_" << methName << ":\n\t.size "
371 << methName << ", .EndOf_"
372 << methName << "-" << methName << "\n";
374 // Put some spaces between the methods
378 } // End anonymous namespace
380 Pass *UltraSparc::getMethodAsmPrinterPass(PassManager &PM, std::ostream &Out) {
381 return new SparcMethodAsmPrinter(Out, *this);
388 //===----------------------------------------------------------------------===//
389 // SparcMethodAsmPrinter Code
390 //===----------------------------------------------------------------------===//
394 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
396 SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
397 : AsmPrinter(os, t) {}
399 virtual bool run(Module *M) {
401 emitGlobalsAndConstants(M);
406 void emitGlobalsAndConstants(const Module *M);
408 void printGlobalVariable(const GlobalVariable *GV);
409 void printSingleConstant( const Constant* CV);
410 void printConstantValueOnly(const Constant* CV);
411 void printConstant( const Constant* CV, std::string valID = "");
413 static void FoldConstants(const Module *M,
414 std::hash_set<const Constant*> &moduleConstants);
419 // Can we treat the specified array as a string? Only if it is an array of
420 // ubytes or non-negative sbytes.
422 static bool isStringCompatible(ConstantArray *CPA) {
423 const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
424 if (ETy == Type::UByteTy) return true;
425 if (ETy != Type::SByteTy) return false;
427 for (unsigned i = 0; i < CPA->getNumOperands(); ++i)
428 if (cast<ConstantSInt>(CPA->getOperand(i))->getValue() < 0)
434 // toOctal - Convert the low order bits of X into an octal letter
435 static inline char toOctal(int X) {
439 // getAsCString - Return the specified array as a C compatible string, only if
440 // the predicate isStringCompatible is true.
442 static string getAsCString(ConstantArray *CPA) {
443 if (isStringCompatible(CPA)) {
445 const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
447 for (unsigned i = 0; i < CPA->getNumOperands(); ++i) {
448 unsigned char C = (ETy == Type::SByteTy) ?
449 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
450 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
456 case '\a': Result += "\\a"; break;
457 case '\b': Result += "\\b"; break;
458 case '\f': Result += "\\f"; break;
459 case '\n': Result += "\\n"; break;
460 case '\r': Result += "\\r"; break;
461 case '\t': Result += "\\t"; break;
462 case '\v': Result += "\\v"; break;
465 Result += toOctal(C >> 6);
466 Result += toOctal(C >> 3);
467 Result += toOctal(C >> 0);
476 return CPA->getStrValue();
481 ArrayTypeIsString(ArrayType* arrayType)
483 return (arrayType->getElementType() == Type::UByteTy ||
484 arrayType->getElementType() == Type::SByteTy);
488 TypeToDataDirective(const Type* type)
490 switch(type->getPrimitiveID())
492 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
494 case Type::UShortTyID: case Type::ShortTyID:
496 case Type::UIntTyID: case Type::IntTyID:
498 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
500 case Type::FloatTyID:
502 case Type::DoubleTyID:
504 case Type::ArrayTyID:
505 if (ArrayTypeIsString((ArrayType*) type))
508 return "<InvaliDataTypeForPrinting>";
510 return "<InvaliDataTypeForPrinting>";
514 // Get the size of the constant for the given target.
515 // If this is an unsized array, return 0.
518 ConstantToSize(const Constant* CV, const TargetMachine& target)
520 if (ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
522 ArrayType *aty = cast<ArrayType>(CPA->getType());
523 if (ArrayTypeIsString(aty))
524 return 1 + CPA->getNumOperands();
527 return target.findOptimalStorageSize(CV->getType());
532 // Align data larger than one L1 cache line on L1 cache line boundaries.
533 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
536 SizeToAlignment(unsigned int size, const TargetMachine& target)
538 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
539 if (size > (unsigned) cacheLineSize / 2)
540 return cacheLineSize;
542 for (unsigned sz=1; /*no condition*/; sz *= 2)
547 // Get the size of the type and then use SizeToAlignment.
550 TypeToAlignment(const Type* type, const TargetMachine& target)
552 return SizeToAlignment(target.findOptimalStorageSize(type), target);
555 // Get the size of the constant and then use SizeToAlignment.
556 // Handles strings as a special case;
558 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
560 if (ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
561 if (ArrayTypeIsString(cast<ArrayType>(CPA->getType())))
562 return SizeToAlignment(1 + CPA->getNumOperands(), target);
564 return TypeToAlignment(CV->getType(), target);
568 // Print a single constant value.
570 SparcModuleAsmPrinter::printSingleConstant(const Constant* CV)
572 assert(CV->getType() != Type::VoidTy &&
573 CV->getType() != Type::TypeTy &&
574 CV->getType() != Type::LabelTy &&
575 "Unexpected type for Constant");
577 assert((! isa<ConstantArray>( CV) && ! isa<ConstantStruct>(CV))
578 && "Collective types should be handled outside this function");
580 toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
582 if (CV->getType()->isPrimitiveType())
584 if (CV->getType() == Type::FloatTy || CV->getType() == Type::DoubleTy)
585 toAsm << "0r"; // FP constants must have this prefix
586 toAsm << CV->getStrValue() << "\n";
588 else if (ConstantPointer* CPP = dyn_cast<ConstantPointer>(CV))
590 assert(CPP->isNullValue() &&
591 "Cannot yet print non-null pointer constants to assembly");
594 else if (isa<ConstantPointerRef>(CV))
596 assert(0 && "Cannot yet initialize pointer refs in assembly");
600 assert(0 && "Unknown elementary type for constant");
604 // Print a constant value or values (it may be an aggregate).
605 // Uses printSingleConstant() to print each individual value.
607 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV)
609 ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
611 if (CPA && isStringCompatible(CPA))
612 { // print the string alone and return
613 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
616 { // Not a string. Print the values in successive locations
617 const std::vector<Use> &constValues = CPA->getValues();
618 for (unsigned i=1; i < constValues.size(); i++)
619 this->printConstantValueOnly(cast<Constant>(constValues[i].get()));
621 else if (ConstantStruct *CPS = dyn_cast<ConstantStruct>(CV))
622 { // Print the fields in successive locations
623 const std::vector<Use>& constValues = CPS->getValues();
624 for (unsigned i=1; i < constValues.size(); i++)
625 this->printConstantValueOnly(cast<Constant>(constValues[i].get()));
628 this->printSingleConstant(CV);
631 // Print a constant (which may be an aggregate) prefixed by all the
632 // appropriate directives. Uses printConstantValueOnly() to print the
635 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
637 if (valID.length() == 0)
640 toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
642 // Print .size and .type only if it is not a string.
643 ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
644 if (CPA && isStringCompatible(CPA))
645 { // print it as a string and return
646 toAsm << valID << ":\n";
647 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
651 toAsm << "\t.type" << "\t" << valID << ",#object\n";
653 unsigned int constSize = ConstantToSize(CV, Target);
655 toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
657 toAsm << valID << ":\n";
659 printConstantValueOnly(CV);
663 void SparcModuleAsmPrinter::FoldConstants(const Module *M,
664 std::hash_set<const Constant*> &MC) {
665 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
666 if (!(*I)->isExternal()) {
667 const std::hash_set<const Constant*> &pool =
668 MachineCodeForMethod::get(*I).getConstantPoolValues();
669 MC.insert(pool.begin(), pool.end());
673 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
675 toAsm << "\t.global\t" << getID(GV) << "\n";
677 if (GV->hasInitializer())
678 printConstant(GV->getInitializer(), getID(GV));
680 toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
682 toAsm << "\t.type\t" << getID(GV) << ",#object\n";
683 toAsm << "\t.reserve\t" << getID(GV) << ","
684 << Target.findOptimalStorageSize(GV->getType()->getElementType())
690 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module *M) {
691 // First, get the constants there were marked by the code generator for
692 // inclusion in the assembly code data area and fold them all into a
693 // single constant pool since there may be lots of duplicates. Also,
694 // lets force these constants into the slot table so that we can get
695 // unique names for unnamed constants also.
697 std::hash_set<const Constant*> moduleConstants;
698 FoldConstants(M, moduleConstants);
700 // Now, emit the three data sections separately; the cost of I/O should
701 // make up for the cost of extra passes over the globals list!
703 // Read-only data section (implies initialized)
704 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
706 const GlobalVariable* GV = *GI;
707 if (GV->hasInitializer() && GV->isConstant())
709 if (GI == M->gbegin())
710 enterSection(AsmPrinter::ReadOnlyData);
711 printGlobalVariable(GV);
715 for (std::hash_set<const Constant*>::const_iterator
716 I = moduleConstants.begin(),
717 E = moduleConstants.end(); I != E; ++I)
720 // Initialized read-write data section
721 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
723 const GlobalVariable* GV = *GI;
724 if (GV->hasInitializer() && ! GV->isConstant())
726 if (GI == M->gbegin())
727 enterSection(AsmPrinter::InitRWData);
728 printGlobalVariable(GV);
732 // Uninitialized read-write data section
733 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
735 const GlobalVariable* GV = *GI;
736 if (! GV->hasInitializer())
738 if (GI == M->gbegin())
739 enterSection(AsmPrinter::UninitRWData);
740 printGlobalVariable(GV);
747 } // End anonymous namespace
749 Pass *UltraSparc::getModuleAsmPrinterPass(PassManager &PM, std::ostream &Out) {
750 return new SparcModuleAsmPrinter(Out, *this);