blob: f4ca22f9da90c9e186e31880080edc0fec3b2334 [file] [log] [blame]
Chris Lattnere88f78c2001-09-19 13:47:27 +00001//===-- EmitAssembly.cpp - Emit Sparc Specific .s File ---------------------==//
2//
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.
6//
Chris Lattnerf57b8452002-04-27 06:56:12 +00007// 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.
Chris Lattnere88f78c2001-09-19 13:47:27 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "SparcInternals.h"
Chris Lattnere88f78c2001-09-19 13:47:27 +000015#include "llvm/CodeGen/MachineInstr.h"
Chris Lattnerc019a172002-02-03 07:48:06 +000016#include "llvm/CodeGen/MachineCodeForMethod.h"
Vikram S. Adve953c83e2001-10-28 21:38:52 +000017#include "llvm/GlobalVariable.h"
Chris Lattner31bcdb82002-04-28 19:55:58 +000018#include "llvm/Constants.h"
Vikram S. Adve953c83e2001-10-28 21:38:52 +000019#include "llvm/DerivedTypes.h"
Vikram S. Adved198c472002-03-18 03:07:26 +000020#include "llvm/Annotation.h"
Chris Lattnere88f78c2001-09-19 13:47:27 +000021#include "llvm/BasicBlock.h"
Chris Lattner2fbfdcf2002-04-07 20:49:59 +000022#include "llvm/Function.h"
Chris Lattnere88f78c2001-09-19 13:47:27 +000023#include "llvm/Module.h"
Chris Lattnerb5794002002-04-07 22:49:37 +000024#include "llvm/SlotCalculator.h"
Chris Lattnerd50b6712002-04-28 20:40:59 +000025#include "llvm/Pass.h"
Chris Lattner4b1de8e2002-04-18 18:15:38 +000026#include "llvm/Assembly/Writer.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000027#include "Support/StringExtras.h"
28#include "Support/HashExtras.h"
Vikram S. Adve9ee9d712002-03-03 20:46:32 +000029#include <iostream>
Chris Lattner697954c2002-01-20 22:54:45 +000030using std::string;
Chris Lattnere88f78c2001-09-19 13:47:27 +000031
32namespace {
33
Vikram S. Adved198c472002-03-18 03:07:26 +000034class GlobalIdTable: public Annotation {
35 static AnnotationID AnnotId;
36 friend class AsmPrinter; // give access to AnnotId
Vikram S. Adve953c83e2001-10-28 21:38:52 +000037
Vikram S. Adved198c472002-03-18 03:07:26 +000038 typedef std::hash_map<const Value*, int> ValIdMap;
39 typedef ValIdMap::const_iterator ValIdMapConstIterator;
40 typedef ValIdMap:: iterator ValIdMapIterator;
41public:
Chris Lattnerfd63f25f2002-04-28 04:50:54 +000042 SlotCalculator Table; // map anonymous values to unique integer IDs
Chris Lattnerc19b8b12002-02-03 23:41:08 +000043 ValIdMap valToIdMap; // used for values not handled by SlotCalculator
Vikram S. Adved198c472002-03-18 03:07:26 +000044
Chris Lattnerfd63f25f2002-04-28 04:50:54 +000045 GlobalIdTable(Module* M) : Annotation(AnnotId), Table(M, true) {}
Vikram S. Adved198c472002-03-18 03:07:26 +000046};
47
48AnnotationID GlobalIdTable::AnnotId =
49 AnnotationManager::getID("ASM PRINTER GLOBAL TABLE ANNOT");
50
51//===---------------------------------------------------------------------===//
52// Code Shared By the two printer passes, as a mixin
53//===---------------------------------------------------------------------===//
54
55class AsmPrinter {
56 GlobalIdTable* idTable;
Chris Lattnerc19b8b12002-02-03 23:41:08 +000057public:
Chris Lattner697954c2002-01-20 22:54:45 +000058 std::ostream &toAsm;
Chris Lattner59ba1092002-02-04 15:53:23 +000059 const TargetMachine &Target;
Vikram S. Adved198c472002-03-18 03:07:26 +000060
Chris Lattnere88f78c2001-09-19 13:47:27 +000061 enum Sections {
62 Unknown,
63 Text,
Vikram S. Adve953c83e2001-10-28 21:38:52 +000064 ReadOnlyData,
65 InitRWData,
66 UninitRWData,
Chris Lattnere88f78c2001-09-19 13:47:27 +000067 } CurSection;
Chris Lattnerc19b8b12002-02-03 23:41:08 +000068
Chris Lattner59ba1092002-02-04 15:53:23 +000069 AsmPrinter(std::ostream &os, const TargetMachine &T)
Vikram S. Adved198c472002-03-18 03:07:26 +000070 : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
71
Chris Lattner2fbfdcf2002-04-07 20:49:59 +000072 // (start|end)(Module|Function) - Callback methods to be invoked by subclasses
Chris Lattnerc19b8b12002-02-03 23:41:08 +000073 void startModule(Module *M) {
Vikram S. Adved198c472002-03-18 03:07:26 +000074 // 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);
79 }
Chris Lattnerc19b8b12002-02-03 23:41:08 +000080 }
Chris Lattner2fbfdcf2002-04-07 20:49:59 +000081 void startFunction(Function *F) {
Chris Lattnerb5794002002-04-07 22:49:37 +000082 // Make sure the slot table has information about this function...
Chris Lattnerfd63f25f2002-04-28 04:50:54 +000083 idTable->Table.incorporateFunction(F);
Chris Lattnerc19b8b12002-02-03 23:41:08 +000084 }
Chris Lattner2fbfdcf2002-04-07 20:49:59 +000085 void endFunction(Function *F) {
Chris Lattnerfd63f25f2002-04-28 04:50:54 +000086 idTable->Table.purgeFunction(); // Forget all about F
Chris Lattnerc19b8b12002-02-03 23:41:08 +000087 }
88 void endModule() {
Chris Lattnere88f78c2001-09-19 13:47:27 +000089 }
90
Vikram S. Adved198c472002-03-18 03:07:26 +000091 // 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) {
Chris Lattner2fbfdcf2002-04-07 20:49:59 +000095 const Function *F = dyn_cast<Function>(V);
96 return F && (F->isExternal() || F->getName() == "main");
Vikram S. Adved198c472002-03-18 03:07:26 +000097 }
Vikram S. Adve953c83e2001-10-28 21:38:52 +000098
Chris Lattnere88f78c2001-09-19 13:47:27 +000099 // enterSection - Use this method to enter a different section of the output
100 // executable. This is used to only output neccesary section transitions.
101 //
102 void enterSection(enum Sections S) {
103 if (S == CurSection) return; // Only switch section if neccesary
104 CurSection = S;
105
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000106 toAsm << "\n\t.section ";
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000107 switch (S)
108 {
109 default: assert(0 && "Bad section name!");
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000110 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;
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000114 }
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000115 toAsm << "\n";
Chris Lattnere88f78c2001-09-19 13:47:27 +0000116 }
117
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000118 static std::string getValidSymbolName(const string &S) {
Chris Lattnerc56d7792001-09-28 15:07:24 +0000119 string Result;
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000120
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.
125 //
126 if (S[0] == '_' || isdigit(S[0]))
127 Result += "ll";
128
129 for (unsigned i = 0; i < S.size(); ++i)
130 {
131 char C = S[i];
132 if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
133 Result += C;
134 else
135 {
136 Result += '_';
137 Result += char('0' + ((unsigned char)C >> 4));
138 Result += char('0' + (C & 0xF));
139 }
Chris Lattnerc56d7792001-09-28 15:07:24 +0000140 }
Chris Lattnerc56d7792001-09-28 15:07:24 +0000141 return Result;
142 }
143
Chris Lattnere88f78c2001-09-19 13:47:27 +0000144 // getID - Return a valid identifier for the specified value. Base it on
Vikram S. Adved198c472002-03-18 03:07:26 +0000145 // 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.
Chris Lattnere88f78c2001-09-19 13:47:27 +0000148 //
149 string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
Vikram S. Adved198c472002-03-18 03:07:26 +0000150 string Result = FPrefix ? FPrefix : ""; // "Forced prefix"
151
152 Result = Result + (V->hasName()? V->getName() : string(Prefix));
153
154 // Qualify all internal names with a unique id.
155 if (!isExternal(V)) {
Chris Lattnerfd63f25f2002-04-28 04:50:54 +0000156 int valId = idTable->Table.getValSlot(V);
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000157 if (valId == -1) {
Vikram S. Adved198c472002-03-18 03:07:26 +0000158 GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
159 if (I == idTable->valToIdMap.end())
160 valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000161 else
162 valId = I->second;
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000163 }
Vikram S. Adved198c472002-03-18 03:07:26 +0000164 Result = Result + "_" + itostr(valId);
Chris Lattnere88f78c2001-09-19 13:47:27 +0000165 }
Vikram S. Adved198c472002-03-18 03:07:26 +0000166
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000167 return getValidSymbolName(Result);
Chris Lattnere88f78c2001-09-19 13:47:27 +0000168 }
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000169
Chris Lattnere88f78c2001-09-19 13:47:27 +0000170 // getID Wrappers - Ensure consistent usage...
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000171 string getID(const Function *F) {
172 return getID(F, "LLVMFunction_");
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000173 }
174 string getID(const BasicBlock *BB) {
175 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
176 }
177 string getID(const GlobalVariable *GV) {
178 return getID(GV, "LLVMGlobal_", ".G_");
179 }
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000180 string getID(const Constant *CV) {
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000181 return getID(CV, "LLVMConst_", ".C_");
182 }
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000183};
184
185
186
187//===----------------------------------------------------------------------===//
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000188// SparcFunctionAsmPrinter Code
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000189//===----------------------------------------------------------------------===//
190
Chris Lattnerf57b8452002-04-27 06:56:12 +0000191struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000192 inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000193 : AsmPrinter(os, t) {}
194
195 virtual bool doInitialization(Module *M) {
196 startModule(M);
197 return false;
198 }
199
Chris Lattnerf57b8452002-04-27 06:56:12 +0000200 virtual bool runOnFunction(Function *F) {
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000201 startFunction(F);
202 emitFunction(F);
203 endFunction(F);
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000204 return false;
205 }
206
207 virtual bool doFinalization(Module *M) {
208 endModule();
209 return false;
210 }
211
Chris Lattner97e52e42002-04-28 21:27:06 +0000212 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
213 AU.setPreservesAll();
214 }
215
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000216 void emitFunction(const Function *F);
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000217private :
218 void emitBasicBlock(const BasicBlock *BB);
219 void emitMachineInst(const MachineInstr *MI);
220
221 unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
222 void printOneOperand(const MachineOperand &Op);
223
224 bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
225 bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000226
Chris Lattnere88f78c2001-09-19 13:47:27 +0000227 unsigned getOperandMask(unsigned Opcode) {
228 switch (Opcode) {
229 case SUBcc: return 1 << 3; // Remove CC argument
Vikram S. Adve998cf0d2001-11-11 23:11:36 +0000230 case BA: return 1 << 0; // Remove Arg #0, which is always null or xcc
Chris Lattnere88f78c2001-09-19 13:47:27 +0000231 default: return 0; // By default, don't hack operands...
232 }
233 }
234};
235
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000236inline bool
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000237SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
238 unsigned int opNum) {
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000239 switch (MI->getOpCode()) {
240 case JMPLCALL:
241 case JMPLRET: return (opNum == 0);
242 default: return false;
243 }
244}
245
246
247inline bool
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000248SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
249 unsigned int opNum) {
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000250 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
251 return (opNum == 0);
252 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
253 return (opNum == 1);
254 else
255 return false;
256}
257
258
259#define PrintOp1PlusOp2(Op1, Op2) \
260 printOneOperand(Op1); \
261 toAsm << "+"; \
262 printOneOperand(Op2);
263
264unsigned int
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000265SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000266 unsigned int opNum)
267{
268 const MachineOperand& Op = MI->getOperand(opNum);
269
270 if (OpIsBranchTargetLabel(MI, opNum))
271 {
272 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
273 return 2;
274 }
275 else if (OpIsMemoryAddressBase(MI, opNum))
276 {
277 toAsm << "[";
278 PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
279 toAsm << "]";
280 return 2;
281 }
282 else
283 {
284 printOneOperand(Op);
285 return 1;
286 }
287}
288
289
290void
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000291SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &op)
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000292{
293 switch (op.getOperandType())
294 {
295 case MachineOperand::MO_VirtualRegister:
296 case MachineOperand::MO_CCRegister:
297 case MachineOperand::MO_MachineRegister:
298 {
299 int RegNum = (int)op.getAllocatedRegNum();
300
Vikram S. Advefbd21612002-03-31 19:03:58 +0000301 // better to print code with NULL registers than to die
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000302 if (RegNum == Target.getRegInfo().getInvalidRegNum()) {
303 toAsm << "<NULL VALUE>";
304 } else {
305 toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
306 }
307 break;
308 }
309
310 case MachineOperand::MO_PCRelativeDisp:
311 {
312 const Value *Val = op.getVRegValue();
313 if (!Val)
314 toAsm << "\t<*NULL Value*>";
Chris Lattner31bcdb82002-04-28 19:55:58 +0000315 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(Val))
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000316 toAsm << getID(BB);
Chris Lattner31bcdb82002-04-28 19:55:58 +0000317 else if (const Function *M = dyn_cast<Function>(Val))
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000318 toAsm << getID(M);
Chris Lattner31bcdb82002-04-28 19:55:58 +0000319 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000320 toAsm << getID(GV);
Chris Lattner31bcdb82002-04-28 19:55:58 +0000321 else if (const Constant *CV = dyn_cast<Constant>(Val))
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000322 toAsm << getID(CV);
323 else
324 toAsm << "<unknown value=" << Val << ">";
325 break;
326 }
327
328 case MachineOperand::MO_SignExtendedImmed:
329 case MachineOperand::MO_UnextendedImmed:
330 toAsm << (long)op.getImmedValue();
331 break;
332
333 default:
334 toAsm << op; // use dump field
335 break;
336 }
337}
338
339
340void
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000341SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000342{
343 unsigned Opcode = MI->getOpCode();
344
345 if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
346 return; // IGNORE PHI NODES
347
348 toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
349
350 unsigned Mask = getOperandMask(Opcode);
351
352 bool NeedComma = false;
353 unsigned N = 1;
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
357 NeedComma = true;
358 N = printOperands(MI, OpNum);
359 }
360 else
361 N = 1;
362
363 toAsm << "\n";
364}
365
366void
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000367SparcFunctionAsmPrinter::emitBasicBlock(const BasicBlock *BB)
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000368{
369 // Emit a label for the basic block
370 toAsm << getID(BB) << ":\n";
371
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();
375
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
380}
381
382void
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000383SparcFunctionAsmPrinter::emitFunction(const Function *M)
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000384{
385 string methName = getID(M);
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000386 toAsm << "!****** Outputing Function: " << methName << " ******\n";
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000387 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";
392
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000393 // 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)
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000395 emitBasicBlock(*I);
396
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";
401
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000402 // Put some spaces between the functions
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000403 toAsm << "\n\n";
404}
405
406} // End anonymous namespace
407
Chris Lattnerf57b8452002-04-27 06:56:12 +0000408Pass *UltraSparc::getFunctionAsmPrinterPass(PassManager &PM, std::ostream &Out){
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000409 return new SparcFunctionAsmPrinter(Out, *this);
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000410}
411
412
413
414
415
416//===----------------------------------------------------------------------===//
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000417// SparcFunctionAsmPrinter Code
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000418//===----------------------------------------------------------------------===//
419
420namespace {
421
422class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
423public:
Chris Lattner49b8a9c2002-02-24 23:02:40 +0000424 SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
425 : AsmPrinter(os, t) {}
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000426
427 virtual bool run(Module *M) {
428 startModule(M);
429 emitGlobalsAndConstants(M);
430 endModule();
431 return false;
432 }
433
Chris Lattner97e52e42002-04-28 21:27:06 +0000434 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
435 AU.setPreservesAll();
436 }
437
438private:
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000439 void emitGlobalsAndConstants(const Module *M);
440
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 = "");
445
446 static void FoldConstants(const Module *M,
447 std::hash_set<const Constant*> &moduleConstants);
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000448};
449
Chris Lattnercee8f9a2001-11-27 00:03:19 +0000450
451// Can we treat the specified array as a string? Only if it is an array of
452// ubytes or non-negative sbytes.
453//
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000454static bool isStringCompatible(ConstantArray *CPA) {
Chris Lattnercee8f9a2001-11-27 00:03:19 +0000455 const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
456 if (ETy == Type::UByteTy) return true;
457 if (ETy != Type::SByteTy) return false;
458
459 for (unsigned i = 0; i < CPA->getNumOperands(); ++i)
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000460 if (cast<ConstantSInt>(CPA->getOperand(i))->getValue() < 0)
Chris Lattnercee8f9a2001-11-27 00:03:19 +0000461 return false;
462
463 return true;
464}
465
466// toOctal - Convert the low order bits of X into an octal letter
467static inline char toOctal(int X) {
468 return (X&7)+'0';
469}
470
471// getAsCString - Return the specified array as a C compatible string, only if
472// the predicate isStringCompatible is true.
473//
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000474static string getAsCString(ConstantArray *CPA) {
Chris Lattner4b1de8e2002-04-18 18:15:38 +0000475 assert(isStringCompatible(CPA) && "Array is not string compatible!");
Chris Lattnercee8f9a2001-11-27 00:03:19 +0000476
Chris Lattner4b1de8e2002-04-18 18:15:38 +0000477 string Result;
478 const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
479 Result = "\"";
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();
484
485 if (isprint(C)) {
486 Result += C;
487 } else {
488 switch(C) {
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;
496 default:
497 Result += '\\';
498 Result += toOctal(C >> 6);
499 Result += toOctal(C >> 3);
500 Result += toOctal(C >> 0);
501 break;
Chris Lattnercee8f9a2001-11-27 00:03:19 +0000502 }
503 }
Chris Lattnercee8f9a2001-11-27 00:03:19 +0000504 }
Chris Lattner4b1de8e2002-04-18 18:15:38 +0000505 Result += "\"";
506
507 return Result;
Chris Lattnercee8f9a2001-11-27 00:03:19 +0000508}
509
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000510inline bool
511ArrayTypeIsString(ArrayType* arrayType)
512{
513 return (arrayType->getElementType() == Type::UByteTy ||
514 arrayType->getElementType() == Type::SByteTy);
515}
Chris Lattnere88f78c2001-09-19 13:47:27 +0000516
Vikram S. Adve915b58d2001-11-09 02:19:29 +0000517inline const string
518TypeToDataDirective(const Type* type)
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000519{
520 switch(type->getPrimitiveID())
521 {
522 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
523 return ".byte";
524 case Type::UShortTyID: case Type::ShortTyID:
525 return ".half";
526 case Type::UIntTyID: case Type::IntTyID:
527 return ".word";
528 case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
529 return ".xword";
530 case Type::FloatTyID:
Chris Lattnerf678dc62002-04-11 21:44:02 +0000531 return ".word";
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000532 case Type::DoubleTyID:
Chris Lattnerf678dc62002-04-11 21:44:02 +0000533 return ".xword";
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000534 case Type::ArrayTyID:
535 if (ArrayTypeIsString((ArrayType*) type))
536 return ".ascii";
537 else
538 return "<InvaliDataTypeForPrinting>";
539 default:
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000540 return "<InvaliDataTypeForPrinting>";
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000541 }
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000542}
543
Vikram S. Adve21447222001-11-10 02:03:06 +0000544// Get the size of the constant for the given target.
545// If this is an unsized array, return 0.
546//
Vikram S. Adve915b58d2001-11-09 02:19:29 +0000547inline unsigned int
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000548ConstantToSize(const Constant* CV, const TargetMachine& target)
Vikram S. Adve915b58d2001-11-09 02:19:29 +0000549{
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000550 if (ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
Vikram S. Adve21447222001-11-10 02:03:06 +0000551 {
552 ArrayType *aty = cast<ArrayType>(CPA->getType());
553 if (ArrayTypeIsString(aty))
554 return 1 + CPA->getNumOperands();
Vikram S. Adve21447222001-11-10 02:03:06 +0000555 }
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000556
557 return target.findOptimalStorageSize(CV->getType());
558}
559
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000560
561
Vikram S. Adve915b58d2001-11-09 02:19:29 +0000562// Align data larger than one L1 cache line on L1 cache line boundaries.
Vikram S. Adve21447222001-11-10 02:03:06 +0000563// Align all smaller data on the next higher 2^x boundary (4, 8, ...).
564//
565inline unsigned int
566SizeToAlignment(unsigned int size, const TargetMachine& target)
567{
568 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
569 if (size > (unsigned) cacheLineSize / 2)
570 return cacheLineSize;
571 else
572 for (unsigned sz=1; /*no condition*/; sz *= 2)
573 if (sz >= size)
574 return sz;
575}
576
577// Get the size of the type and then use SizeToAlignment.
Vikram S. Adve915b58d2001-11-09 02:19:29 +0000578//
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000579inline unsigned int
580TypeToAlignment(const Type* type, const TargetMachine& target)
581{
Vikram S. Adve21447222001-11-10 02:03:06 +0000582 return SizeToAlignment(target.findOptimalStorageSize(type), target);
583}
584
585// Get the size of the constant and then use SizeToAlignment.
586// Handles strings as a special case;
587inline unsigned int
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000588ConstantToAlignment(const Constant* CV, const TargetMachine& target)
Vikram S. Adve21447222001-11-10 02:03:06 +0000589{
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000590 if (ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
Vikram S. Adve21447222001-11-10 02:03:06 +0000591 if (ArrayTypeIsString(cast<ArrayType>(CPA->getType())))
592 return SizeToAlignment(1 + CPA->getNumOperands(), target);
593
594 return TypeToAlignment(CV->getType(), target);
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000595}
596
597
Vikram S. Adve21447222001-11-10 02:03:06 +0000598// Print a single constant value.
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000599void
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000600SparcModuleAsmPrinter::printSingleConstant(const Constant* CV)
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000601{
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000602 assert(CV->getType() != Type::VoidTy &&
603 CV->getType() != Type::TypeTy &&
604 CV->getType() != Type::LabelTy &&
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000605 "Unexpected type for Constant");
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000606
Chris Lattnerf678dc62002-04-11 21:44:02 +0000607 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
608 && "Aggregate types should be handled outside this function");
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000609
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000610 toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000611
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000612 if (CV->getType()->isPrimitiveType())
613 {
Chris Lattnerf678dc62002-04-11 21:44:02 +0000614 if (CV->getType()->isFloatingPoint()) {
615 // FP Constants are printed as integer constants to avoid losing
616 // precision...
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;
625 } else {
626 assert(0 && "Unknown floating point type!");
627 }
628
629 toAsm << "\t! " << CV->getType()->getDescription()
630 << " value: " << Val << "\n";
631 } else {
Chris Lattner4b1de8e2002-04-18 18:15:38 +0000632 WriteAsOperand(toAsm, CV, false, false) << "\n";
Chris Lattnerf678dc62002-04-11 21:44:02 +0000633 }
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000634 }
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000635 else if (ConstantPointer* CPP = dyn_cast<ConstantPointer>(CV))
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000636 {
Chris Lattner697954c2002-01-20 22:54:45 +0000637 assert(CPP->isNullValue() &&
638 "Cannot yet print non-null pointer constants to assembly");
639 toAsm << "0\n";
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000640 }
Chris Lattner697954c2002-01-20 22:54:45 +0000641 else if (isa<ConstantPointerRef>(CV))
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000642 {
643 assert(0 && "Cannot yet initialize pointer refs in assembly");
644 }
645 else
646 {
Vikram S. Adve915b58d2001-11-09 02:19:29 +0000647 assert(0 && "Unknown elementary type for constant");
Vikram S. Adve29ff8732001-11-08 05:12:37 +0000648 }
Vikram S. Adve915b58d2001-11-09 02:19:29 +0000649}
650
Vikram S. Adve21447222001-11-10 02:03:06 +0000651// Print a constant value or values (it may be an aggregate).
652// Uses printSingleConstant() to print each individual value.
653void
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000654SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV)
Vikram S. Adve21447222001-11-10 02:03:06 +0000655{
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000656 ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
Vikram S. Adve21447222001-11-10 02:03:06 +0000657
658 if (CPA && isStringCompatible(CPA))
659 { // print the string alone and return
Chris Lattner697954c2002-01-20 22:54:45 +0000660 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
Vikram S. Adve21447222001-11-10 02:03:06 +0000661 }
662 else if (CPA)
663 { // Not a string. Print the values in successive locations
Chris Lattner697954c2002-01-20 22:54:45 +0000664 const std::vector<Use> &constValues = CPA->getValues();
Vikram S. Adve21447222001-11-10 02:03:06 +0000665 for (unsigned i=1; i < constValues.size(); i++)
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000666 this->printConstantValueOnly(cast<Constant>(constValues[i].get()));
Vikram S. Adve21447222001-11-10 02:03:06 +0000667 }
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000668 else if (ConstantStruct *CPS = dyn_cast<ConstantStruct>(CV))
Vikram S. Adve21447222001-11-10 02:03:06 +0000669 { // Print the fields in successive locations
Chris Lattner697954c2002-01-20 22:54:45 +0000670 const std::vector<Use>& constValues = CPS->getValues();
Vikram S. Adve21447222001-11-10 02:03:06 +0000671 for (unsigned i=1; i < constValues.size(); i++)
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000672 this->printConstantValueOnly(cast<Constant>(constValues[i].get()));
Vikram S. Adve21447222001-11-10 02:03:06 +0000673 }
674 else
675 this->printSingleConstant(CV);
676}
677
678// Print a constant (which may be an aggregate) prefixed by all the
679// appropriate directives. Uses printConstantValueOnly() to print the
680// value or values.
Vikram S. Adve915b58d2001-11-09 02:19:29 +0000681void
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000682SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
Vikram S. Adve915b58d2001-11-09 02:19:29 +0000683{
684 if (valID.length() == 0)
685 valID = getID(CV);
686
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000687 toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
Vikram S. Adve915b58d2001-11-09 02:19:29 +0000688
689 // Print .size and .type only if it is not a string.
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000690 ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
Vikram S. Adve915b58d2001-11-09 02:19:29 +0000691 if (CPA && isStringCompatible(CPA))
692 { // print it as a string and return
Chris Lattner697954c2002-01-20 22:54:45 +0000693 toAsm << valID << ":\n";
694 toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
Vikram S. Adve915b58d2001-11-09 02:19:29 +0000695 return;
696 }
Vikram S. Adve21447222001-11-10 02:03:06 +0000697
Chris Lattner697954c2002-01-20 22:54:45 +0000698 toAsm << "\t.type" << "\t" << valID << ",#object\n";
Vikram S. Adve21447222001-11-10 02:03:06 +0000699
700 unsigned int constSize = ConstantToSize(CV, Target);
701 if (constSize)
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000702 toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
Vikram S. Adve21447222001-11-10 02:03:06 +0000703
Chris Lattner697954c2002-01-20 22:54:45 +0000704 toAsm << valID << ":\n";
Vikram S. Adve915b58d2001-11-09 02:19:29 +0000705
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000706 printConstantValueOnly(CV);
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000707}
708
709
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000710void 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());
717 }
718}
719
720void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000721{
Chris Lattner697954c2002-01-20 22:54:45 +0000722 toAsm << "\t.global\t" << getID(GV) << "\n";
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000723
724 if (GV->hasInitializer())
725 printConstant(GV->getInitializer(), getID(GV));
726 else {
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000727 toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
728 Target) << "\n";
Chris Lattner697954c2002-01-20 22:54:45 +0000729 toAsm << "\t.type\t" << getID(GV) << ",#object\n";
Vikram S. Adveffbba0f2001-11-08 14:29:57 +0000730 toAsm << "\t.reserve\t" << getID(GV) << ","
Chris Lattnerc019a172002-02-03 07:48:06 +0000731 << Target.findOptimalStorageSize(GV->getType()->getElementType())
Chris Lattner697954c2002-01-20 22:54:45 +0000732 << "\n";
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000733 }
734}
735
736
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000737void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module *M) {
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000738 // 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.
743 //
Chris Lattner697954c2002-01-20 22:54:45 +0000744 std::hash_set<const Constant*> moduleConstants;
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000745 FoldConstants(M, moduleConstants);
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000746
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000747 // 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!
Vikram S. Advefbd21612002-03-31 19:03:58 +0000749
750 // Section 1 : Read-only data section (implies initialized)
751 enterSection(AsmPrinter::ReadOnlyData);
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000752 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
Vikram S. Advefbd21612002-03-31 19:03:58 +0000753 if ((*GI)->hasInitializer() && (*GI)->isConstant())
754 printGlobalVariable(*GI);
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000755
Chris Lattner697954c2002-01-20 22:54:45 +0000756 for (std::hash_set<const Constant*>::const_iterator
757 I = moduleConstants.begin(),
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000758 E = moduleConstants.end(); I != E; ++I)
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000759 printConstant(*I);
760
Vikram S. Advefbd21612002-03-31 19:03:58 +0000761 // Section 2 : Initialized read-write data section
762 enterSection(AsmPrinter::InitRWData);
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000763 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
Vikram S. Advefbd21612002-03-31 19:03:58 +0000764 if ((*GI)->hasInitializer() && ! (*GI)->isConstant())
765 printGlobalVariable(*GI);
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000766
Vikram S. Advefbd21612002-03-31 19:03:58 +0000767 // Section 3 : Uninitialized read-write data section
768 enterSection(AsmPrinter::UninitRWData);
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000769 for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
Vikram S. Advefbd21612002-03-31 19:03:58 +0000770 if (! (*GI)->hasInitializer())
771 printGlobalVariable(*GI);
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000772
Chris Lattner697954c2002-01-20 22:54:45 +0000773 toAsm << "\n";
Vikram S. Adve953c83e2001-10-28 21:38:52 +0000774}
775
Chris Lattnere88f78c2001-09-19 13:47:27 +0000776} // End anonymous namespace
777
Chris Lattnerc19b8b12002-02-03 23:41:08 +0000778Pass *UltraSparc::getModuleAsmPrinterPass(PassManager &PM, std::ostream &Out) {
779 return new SparcModuleAsmPrinter(Out, *this);
Chris Lattnerc019a172002-02-03 07:48:06 +0000780}