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 // The entry point of this file is the UltraSparc::emitAssembly method.
9 //===----------------------------------------------------------------------===//
11 #include "SparcInternals.h"
12 #include "llvm/Analysis/SlotCalculator.h"
13 #include "llvm/Transforms/Linker.h"
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/GlobalVariable.h"
16 #include "llvm/GlobalValue.h"
17 #include "llvm/ConstPoolVals.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/BasicBlock.h"
20 #include "llvm/Method.h"
21 #include "llvm/Module.h"
22 #include "llvm/Support/HashExtras.h"
23 #include "llvm/Support/StringExtras.h"
29 class SparcAsmPrinter {
30 typedef hash_map<const Value*, int> ValIdMap;
31 typedef ValIdMap:: iterator ValIdMapIterator;
32 typedef ValIdMap::const_iterator ValIdMapConstIterator;
35 SlotCalculator Table; // map anonymous values to unique integer IDs
36 ValIdMap valToIdMap; // used for values not handled by SlotCalculator
37 const UltraSparc &Target;
48 inline SparcAsmPrinter(ostream &o, const Module *M, const UltraSparc &t)
49 : toAsm(o), Table(SlotCalculator(M, true)), Target(t), CurSection(Unknown) {
54 void emitModule(const Module *M);
55 void emitMethod(const Method *M);
56 void emitGlobalsAndConstants(const Module* module);
57 //void processMethodArgument(const MethodArgument *MA);
58 void emitBasicBlock(const BasicBlock *BB);
59 void emitMachineInst(const MachineInstr *MI);
61 void printGlobalVariable(const GlobalVariable* GV);
62 void printSingleConstant(const ConstPoolVal* CV, string valID = string(""));
63 void printConstant( const ConstPoolVal* CV, string valID = string(""));
65 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
66 void printOneOperand(const MachineOperand &Op);
68 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
69 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
71 // enterSection - Use this method to enter a different section of the output
72 // executable. This is used to only output neccesary section transitions.
74 void enterSection(enum Sections S) {
75 if (S == CurSection) return; // Only switch section if neccesary
78 toAsm << "\n\t.section ";
81 default: assert(0 && "Bad section name!");
82 case Text: toAsm << "\".text\""; break;
83 case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
84 case InitRWData: toAsm << "\".data\",#alloc,#write"; break;
85 case UninitRWData: toAsm << "\".bss\",#alloc,#write\nBbss.bss:"; break;
90 string getValidSymbolName(const string &S) {
93 // Symbol names in Sparc assembly language have these rules:
94 // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
95 // (b) A name beginning in "." is treated as a local name.
96 // (c) Names beginning with "_" are reserved by ANSI C and shd not be used.
98 if (S[0] == '_' || isdigit(S[0]))
101 for (unsigned i = 0; i < S.size(); ++i)
104 if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
109 Result += char('0' + ((unsigned char)C >> 4));
110 Result += char('0' + (C & 0xF));
116 // getID - Return a valid identifier for the specified value. Base it on
117 // the name of the identifier if possible, use a numbered value based on
118 // prefix otherwise. FPrefix is always prepended to the output identifier.
120 string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
122 string FP(FPrefix ? FPrefix : ""); // "Forced prefix"
124 Result = FP + V->getName();
126 int valId = Table.getValSlot(V);
128 ValIdMapConstIterator I = valToIdMap.find(V);
129 valId = (I == valToIdMap.end())? (valToIdMap[V] = valToIdMap.size())
132 Result = FP + string(Prefix) + itostr(valId);
134 return getValidSymbolName(Result);
137 // getID Wrappers - Ensure consistent usage...
138 string getID(const Module *M) {
139 return getID(M, "LLVMModule_");
141 string getID(const Method *M) {
142 return getID(M, "LLVMMethod_");
144 string getID(const BasicBlock *BB) {
145 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
147 string getID(const GlobalVariable *GV) {
148 return getID(GV, "LLVMGlobal_", ".G_");
150 string getID(const ConstPoolVal *CV) {
151 return getID(CV, "LLVMConst_", ".C_");
154 unsigned getOperandMask(unsigned Opcode) {
156 case SUBcc: return 1 << 3; // Remove CC argument
157 case BA: case BRZ: // Remove Arg #0, which is always null or xcc
158 case BRLEZ: case BRLZ:
159 case BRNZ: case BRGZ:
160 case BRGEZ: return 1 << 0;
162 default: return 0; // By default, don't hack operands...
168 SparcAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
169 unsigned int opNum) {
170 switch (MI->getOpCode()) {
172 case JMPLRET: return (opNum == 0);
173 default: return false;
179 SparcAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
180 unsigned int opNum) {
181 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
183 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
190 #define PrintOp1PlusOp2(Op1, Op2) \
191 printOneOperand(Op1); \
193 printOneOperand(Op2);
196 SparcAsmPrinter::printOperands(const MachineInstr *MI,
199 const MachineOperand& Op = MI->getOperand(opNum);
201 if (OpIsBranchTargetLabel(MI, opNum))
203 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
206 else if (OpIsMemoryAddressBase(MI, opNum))
209 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
222 SparcAsmPrinter::printOneOperand(const MachineOperand &op)
224 switch (op.getOperandType())
226 case MachineOperand::MO_VirtualRegister:
227 case MachineOperand::MO_CCRegister:
228 case MachineOperand::MO_MachineRegister:
230 int RegNum = (int)op.getAllocatedRegNum();
232 // ****this code is temporary till NULL Values are fixed
233 if (RegNum == 10000) {
234 toAsm << "<NULL VALUE>";
236 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
241 case MachineOperand::MO_PCRelativeDisp:
243 const Value *Val = op.getVRegValue();
245 toAsm << "\t<*NULL Value*>";
246 else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(Val))
248 else if (const Method *M = dyn_cast<const Method>(Val))
250 else if (const GlobalVariable *GV=dyn_cast<const GlobalVariable>(Val))
252 else if (const ConstPoolVal *CV = dyn_cast<const ConstPoolVal>(Val))
255 toAsm << "<unknown value=" << Val << ">";
259 case MachineOperand::MO_SignExtendedImmed:
260 case MachineOperand::MO_UnextendedImmed:
261 toAsm << op.getImmedValue();
265 toAsm << op; // use dump field
272 SparcAsmPrinter::emitMachineInst(const MachineInstr *MI)
274 unsigned Opcode = MI->getOpCode();
276 if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
277 return; // IGNORE PHI NODES
279 toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
281 unsigned Mask = getOperandMask(Opcode);
283 bool NeedComma = false;
285 for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
286 if (! ((1 << OpNum) & Mask)) { // Ignore this operand?
287 if (NeedComma) toAsm << ", "; // Handle comma outputing
289 N = printOperands(MI, OpNum);
298 SparcAsmPrinter::emitBasicBlock(const BasicBlock *BB)
300 // Emit a label for the basic block
301 toAsm << getID(BB) << ":\n";
303 // Get the vector of machine instructions corresponding to this bb.
304 const MachineCodeForBasicBlock &MIs = BB->getMachineInstrVec();
305 MachineCodeForBasicBlock::const_iterator MII = MIs.begin(), MIE = MIs.end();
307 // Loop over all of the instructions in the basic block...
308 for (; MII != MIE; ++MII)
309 emitMachineInst(*MII);
310 toAsm << "\n"; // Seperate BB's with newlines
314 SparcAsmPrinter::emitMethod(const Method *M)
316 if (M->isExternal()) return;
318 // Make sure the slot table has information about this method...
319 Table.incorporateMethod(M);
321 string methName = getID(M);
322 toAsm << "!****** Outputing Method: " << methName << " ******\n";
324 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
325 //toAsm << "\t.type\t" << methName << ",#function\n";
326 toAsm << "\t.type\t" << methName << ", 2\n";
327 toAsm << methName << ":\n";
329 // Output code for all of the basic blocks in the method...
330 for (Method::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
333 // Output a .size directive so the debugger knows the extents of the function
334 toAsm << ".EndOf_" << methName << ":\n\t.size "
335 << methName << ", .EndOf_"
336 << methName << "-" << methName << endl;
338 // Put some spaces between the methods
341 // Forget all about M.
346 ArrayTypeIsString(ArrayType* arrayType)
348 return (arrayType->getElementType() == Type::UByteTy ||
349 arrayType->getElementType() == Type::SByteTy);
353 TypeToDataDirective(const Type* type)
355 switch(type->getPrimitiveID())
357 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
359 case Type::UShortTyID: case Type::ShortTyID:
361 case Type::UIntTyID: case Type::IntTyID:
363 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
365 case Type::FloatTyID:
367 case Type::DoubleTyID:
369 case Type::ArrayTyID:
370 if (ArrayTypeIsString((ArrayType*) type))
373 return "<InvaliDataTypeForPrinting>";
375 return "<InvaliDataTypeForPrinting>";
380 ConstantToSize(const ConstPoolVal* CV, const TargetMachine& target)
382 if (ConstPoolArray* AV = dyn_cast<ConstPoolArray>(CV))
383 if (ArrayTypeIsString((ArrayType*) CV->getType()))
384 return 1 + AV->getNumOperands();
386 return target.findOptimalStorageSize(CV->getType());
391 unsigned int TypeToSize(const Type* type, const TargetMachine& target)
393 return target.findOptimalStorageSize(type);
397 // Align data larger than one L1 cache line on L1 cache line boundaries.
398 // Align all smaller types on the next higher 2^x boundary (4, 8, ...).
401 TypeToAlignment(const Type* type, const TargetMachine& target)
403 unsigned int typeSize = target.findOptimalStorageSize(type);
404 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
405 if (typeSize > (int) cacheLineSize / 2)
406 return cacheLineSize;
408 for (unsigned sz=1; /*no condition*/; sz *= 2)
415 SparcAsmPrinter::printSingleConstant(const ConstPoolVal* CV,string valID)
417 if (valID.length() == 0)
420 assert(CV->getType() != Type::VoidTy &&
421 CV->getType() != Type::TypeTy &&
422 CV->getType() != Type::LabelTy &&
423 "Unexpected type for ConstPoolVal");
425 assert((! isa<ConstPoolArray>( CV) && ! isa<ConstPoolStruct>(CV))
426 && "Collective types should be handled outside this function");
429 << TypeToDataDirective(CV->getType()) << "\t";
431 if (CV->getType()->isPrimitiveType())
433 if (CV->getType() == Type::FloatTy || CV->getType() == Type::DoubleTy)
434 toAsm << "0r"; // FP constants must have this prefix
435 toAsm << CV->getStrValue() << endl;
437 else if (ConstPoolPointer* CPP = dyn_cast<ConstPoolPointer>(CV))
439 if (! CPP->isNullValue())
440 assert(0 && "Cannot yet print non-null pointer constants to assembly");
442 toAsm << (void*) NULL << endl;
444 else if (ConstPoolPointerRef* CPRef = dyn_cast<ConstPoolPointerRef>(CV))
446 assert(0 && "Cannot yet initialize pointer refs in assembly");
450 assert(0 && "Unknown elementary type for constant");
455 SparcAsmPrinter::printConstant(const ConstPoolVal* CV, string valID)
457 if (valID.length() == 0)
460 assert(CV->getType() != Type::VoidTy &&
461 CV->getType() != Type::TypeTy &&
462 CV->getType() != Type::LabelTy &&
463 "Unexpected type for ConstPoolVal");
465 toAsm << "\t.align\t" << TypeToAlignment(CV->getType(), Target)
468 // Print .size and .type only if it is not a string.
469 ConstPoolArray *CPA = dyn_cast<ConstPoolArray>(CV);
471 if (CPA && isStringCompatible(CPA))
472 { // print it as a string and return
473 toAsm << valID << ":" << endl;
474 toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t"
475 << getAsCString(CPA) << endl;
479 toAsm << "\t.type" << "\t" << valID << ",#object" << endl;
480 toAsm << "\t.size" << "\t" << valID << ","
481 << ConstantToSize(CV, Target) << endl;
482 toAsm << valID << ":" << endl;
485 { // Not a string. Print the values in successive locations
486 const vector<Use>& constValues = CPA->getValues();
487 for (unsigned i=1; i < constValues.size(); i++)
488 this->printSingleConstant(cast<ConstPoolVal>(constValues[i].get()));
490 else if (ConstPoolStruct *CPS = dyn_cast<ConstPoolStruct>(CV))
491 { // Print the fields in successive locations
492 const vector<Use>& constValues = CPA->getValues();
493 for (unsigned i=1; i < constValues.size(); i++)
494 this->printSingleConstant(cast<ConstPoolVal>(constValues[i].get()));
497 this->printSingleConstant(CV, valID);
502 SparcAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
504 toAsm << "\t.global\t" << getID(GV) << endl;
506 if (GV->hasInitializer())
507 printConstant(GV->getInitializer(), getID(GV));
509 toAsm << "\t.align\t"
510 << TypeToAlignment(GV->getType()->getValueType(), Target) << endl;
511 toAsm << "\t.type\t" << getID(GV) << ",#object" << endl;
512 toAsm << "\t.reserve\t" << getID(GV) << ","
513 << TypeToSize(GV->getType()->getValueType(), Target)
520 FoldConstPools(const Module *M,
521 hash_set<const ConstPoolVal*>& moduleConstPool)
523 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
524 if (! (*I)->isExternal())
526 const hash_set<const ConstPoolVal*>& pool =
527 MachineCodeForMethod::get(*I).getConstantPoolValues();
528 moduleConstPool.insert(pool.begin(), pool.end());
534 SparcAsmPrinter::emitGlobalsAndConstants(const Module *M)
536 // First, get the constants there were marked by the code generator for
537 // inclusion in the assembly code data area and fold them all into a
538 // single constant pool since there may be lots of duplicates. Also,
539 // lets force these constants into the slot table so that we can get
540 // unique names for unnamed constants also.
542 hash_set<const ConstPoolVal*> moduleConstPool;
543 FoldConstPools(M, moduleConstPool);
545 // Now, emit the three data sections separately; the cost of I/O should
546 // make up for the cost of extra passes over the globals list!
548 // Read-only data section (implies initialized)
549 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
551 const GlobalVariable* GV = *GI;
552 if (GV->hasInitializer() && GV->isConstant())
554 if (GI == M->gbegin())
555 enterSection(ReadOnlyData);
556 printGlobalVariable(GV);
560 for (hash_set<const ConstPoolVal*>::const_iterator I=moduleConstPool.begin(),
561 E = moduleConstPool.end(); I != E; ++I)
564 // Initialized read-write data section
565 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
567 const GlobalVariable* GV = *GI;
568 if (GV->hasInitializer() && ! GV->isConstant())
570 if (GI == M->gbegin())
571 enterSection(InitRWData);
572 printGlobalVariable(GV);
576 // Uninitialized read-write data section
577 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
579 const GlobalVariable* GV = *GI;
580 if (! GV->hasInitializer())
582 if (GI == M->gbegin())
583 enterSection(UninitRWData);
584 printGlobalVariable(GV);
593 SparcAsmPrinter::emitModule(const Module *M)
595 // TODO: Look for a filename annotation on M to emit a .file directive
596 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
599 emitGlobalsAndConstants(M);
602 } // End anonymous namespace
606 // emitAssembly - Output assembly language code (a .s file) for the specified
607 // method. The specified method must have been compiled before this may be
611 UltraSparc::emitAssembly(const Module *M, ostream &toAsm) const
613 SparcAsmPrinter Print(toAsm, M, *this);