blob: 4cda0dd3b564b03040f5510c6b481bdc514f5c8a [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AsmPrinter class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/AsmPrinter.h"
15#include "llvm/Assembly/Writer.h"
16#include "llvm/DerivedTypes.h"
17#include "llvm/Constants.h"
18#include "llvm/Module.h"
19#include "llvm/CodeGen/MachineConstantPool.h"
20#include "llvm/CodeGen/MachineJumpTableInfo.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/Mangler.h"
23#include "llvm/Support/MathExtras.h"
24#include "llvm/Support/Streams.h"
25#include "llvm/Target/TargetAsmInfo.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetLowering.h"
28#include "llvm/Target/TargetMachine.h"
29#include <cerrno>
30using namespace llvm;
31
32static cl::opt<bool>
33AsmVerbose("asm-verbose", cl::Hidden, cl::desc("Add comments to directives."));
34
35char AsmPrinter::ID = 0;
36AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
37 const TargetAsmInfo *T)
38 : MachineFunctionPass((intptr_t)&ID), FunctionNumber(0), O(o), TM(tm), TAI(T)
39{}
40
41std::string AsmPrinter::getSectionForFunction(const Function &F) const {
42 return TAI->getTextSection();
43}
44
45
46/// SwitchToTextSection - Switch to the specified text section of the executable
47/// if we are not already in it!
48///
49void AsmPrinter::SwitchToTextSection(const char *NewSection,
50 const GlobalValue *GV) {
51 std::string NS;
52 if (GV && GV->hasSection())
53 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
54 else
55 NS = NewSection;
56
57 // If we're already in this section, we're done.
58 if (CurrentSection == NS) return;
59
60 // Close the current section, if applicable.
61 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
62 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
63
64 CurrentSection = NS;
65
66 if (!CurrentSection.empty())
67 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
68}
69
70/// SwitchToDataSection - Switch to the specified data section of the executable
71/// if we are not already in it!
72///
73void AsmPrinter::SwitchToDataSection(const char *NewSection,
74 const GlobalValue *GV) {
75 std::string NS;
76 if (GV && GV->hasSection())
77 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
78 else
79 NS = NewSection;
80
81 // If we're already in this section, we're done.
82 if (CurrentSection == NS) return;
83
84 // Close the current section, if applicable.
85 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
86 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
87
88 CurrentSection = NS;
89
90 if (!CurrentSection.empty())
91 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
92}
93
94
95bool AsmPrinter::doInitialization(Module &M) {
96 Mang = new Mangler(M, TAI->getGlobalPrefix());
97
98 if (!M.getModuleInlineAsm().empty())
99 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
100 << M.getModuleInlineAsm()
101 << "\n" << TAI->getCommentString()
102 << " End of file scope inline assembly\n";
103
104 SwitchToDataSection(""); // Reset back to no section.
105
106 if (MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>()) {
107 MMI->AnalyzeModule(M);
108 }
109
110 return false;
111}
112
113bool AsmPrinter::doFinalization(Module &M) {
114 if (TAI->getWeakRefDirective()) {
115 if (!ExtWeakSymbols.empty())
116 SwitchToDataSection("");
117
118 for (std::set<const GlobalValue*>::iterator i = ExtWeakSymbols.begin(),
119 e = ExtWeakSymbols.end(); i != e; ++i) {
120 const GlobalValue *GV = *i;
121 std::string Name = Mang->getValueName(GV);
122 O << TAI->getWeakRefDirective() << Name << "\n";
123 }
124 }
125
126 if (TAI->getSetDirective()) {
127 if (!M.alias_empty())
128 SwitchToTextSection(TAI->getTextSection());
129
130 O << "\n";
131 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
132 I!=E; ++I) {
133 std::string Name = Mang->getValueName(I);
134 std::string Target;
135
136 if (const GlobalValue *GV = I->getAliasedGlobal())
137 Target = Mang->getValueName(GV);
138 else
139 assert(0 && "Unsupported aliasee");
140
141 if (I->hasExternalLinkage())
142 O << "\t.globl\t" << Name << "\n";
143 else if (I->hasWeakLinkage())
144 O << TAI->getWeakRefDirective() << Name << "\n";
145 else if (!I->hasInternalLinkage())
146 assert(0 && "Invalid alias linkage");
147
148 O << TAI->getSetDirective() << Name << ", " << Target << "\n";
149 }
150 }
151
152 delete Mang; Mang = 0;
153 return false;
154}
155
156void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
157 // What's my mangled name?
158 CurrentFnName = Mang->getValueName(MF.getFunction());
159 IncrementFunctionNumber();
160}
161
162/// EmitConstantPool - Print to the current output stream assembly
163/// representations of the constants in the constant pool MCP. This is
164/// used to print out constants which have been "spilled to memory" by
165/// the code generator.
166///
167void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
168 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
169 if (CP.empty()) return;
170
171 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
172 // in special sections.
173 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
174 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
175 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
176 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
177 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
178 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
179 MachineConstantPoolEntry CPE = CP[i];
180 const Type *Ty = CPE.getType();
181 if (TAI->getFourByteConstantSection() &&
182 TM.getTargetData()->getTypeSize(Ty) == 4)
183 FourByteCPs.push_back(std::make_pair(CPE, i));
184 else if (TAI->getEightByteConstantSection() &&
185 TM.getTargetData()->getTypeSize(Ty) == 8)
186 EightByteCPs.push_back(std::make_pair(CPE, i));
187 else if (TAI->getSixteenByteConstantSection() &&
188 TM.getTargetData()->getTypeSize(Ty) == 16)
189 SixteenByteCPs.push_back(std::make_pair(CPE, i));
190 else
191 OtherCPs.push_back(std::make_pair(CPE, i));
192 }
193
194 unsigned Alignment = MCP->getConstantPoolAlignment();
195 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
196 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
197 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
198 SixteenByteCPs);
199 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
200}
201
202void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
203 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
204 if (CP.empty()) return;
205
206 SwitchToDataSection(Section);
207 EmitAlignment(Alignment);
208 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
209 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
210 << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
211 WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
212 if (CP[i].first.isMachineConstantPoolEntry())
213 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
214 else
215 EmitGlobalConstant(CP[i].first.Val.ConstVal);
216 if (i != e-1) {
217 const Type *Ty = CP[i].first.getType();
218 unsigned EntSize =
219 TM.getTargetData()->getTypeSize(Ty);
220 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
221 // Emit inter-object padding for alignment.
222 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
223 }
224 }
225}
226
227/// EmitJumpTableInfo - Print assembly representations of the jump tables used
228/// by the current function to the current output stream.
229///
230void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
231 MachineFunction &MF) {
232 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
233 if (JT.empty()) return;
234 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
235
236 // Use JumpTableDirective otherwise honor the entry size from the jump table
237 // info.
238 const char *JTEntryDirective = TAI->getJumpTableDirective();
239 bool HadJTEntryDirective = JTEntryDirective != NULL;
240 if (!HadJTEntryDirective) {
241 JTEntryDirective = MJTI->getEntrySize() == 4 ?
242 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
243 }
244
245 // Pick the directive to use to print the jump table entries, and switch to
246 // the appropriate section.
247 TargetLowering *LoweringInfo = TM.getTargetLowering();
248
249 const char* JumpTableDataSection = TAI->getJumpTableDataSection();
250 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
251 !JumpTableDataSection) {
252 // In PIC mode, we need to emit the jump table to the same section as the
253 // function body itself, otherwise the label differences won't make sense.
254 // We should also do if the section name is NULL.
255 const Function *F = MF.getFunction();
256 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
257 } else {
258 SwitchToDataSection(JumpTableDataSection);
259 }
260
261 EmitAlignment(Log2_32(MJTI->getAlignment()));
262
263 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
264 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
265
266 // If this jump table was deleted, ignore it.
267 if (JTBBs.empty()) continue;
268
269 // For PIC codegen, if possible we want to use the SetDirective to reduce
270 // the number of relocations the assembler will generate for the jump table.
271 // Set directives are all printed before the jump table itself.
272 std::set<MachineBasicBlock*> EmittedSets;
273 if (TAI->getSetDirective() && IsPic)
274 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
275 if (EmittedSets.insert(JTBBs[ii]).second)
276 printSetLabel(i, JTBBs[ii]);
277
278 // On some targets (e.g. darwin) we want to emit two consequtive labels
279 // before each jump table. The first label is never referenced, but tells
280 // the assembler and linker the extents of the jump table object. The
281 // second label is actually referenced by the code.
282 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
283 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
284
285 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
286 << '_' << i << ":\n";
287
288 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
289 O << JTEntryDirective << ' ';
290 // If we have emitted set directives for the jump table entries, print
291 // them rather than the entries themselves. If we're emitting PIC, then
292 // emit the table entries as differences between two text section labels.
293 // If we're emitting non-PIC code, then emit the entries as direct
294 // references to the target basic blocks.
295 if (!EmittedSets.empty()) {
296 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
297 << '_' << i << "_set_" << JTBBs[ii]->getNumber();
298 } else if (IsPic) {
299 printBasicBlockLabel(JTBBs[ii], false, false);
300 // If the arch uses custom Jump Table directives, don't calc relative to
301 // JT
302 if (!HadJTEntryDirective)
303 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
304 << getFunctionNumber() << '_' << i;
305 } else {
306 printBasicBlockLabel(JTBBs[ii], false, false);
307 }
308 O << '\n';
309 }
310 }
311}
312
313/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
314/// special global used by LLVM. If so, emit it and return true, otherwise
315/// do nothing and return false.
316bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
317 // Ignore debug and non-emitted data.
318 if (GV->getSection() == "llvm.metadata") return true;
319
320 if (!GV->hasAppendingLinkage()) return false;
321
322 assert(GV->hasInitializer() && "Not a special LLVM global!");
323
324 if (GV->getName() == "llvm.used") {
325 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
326 EmitLLVMUsedList(GV->getInitializer());
327 return true;
328 }
329
330 const TargetData *TD = TM.getTargetData();
331 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
332 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
333 SwitchToDataSection(TAI->getStaticCtorsSection());
334 EmitAlignment(Align, 0);
335 EmitXXStructorList(GV->getInitializer());
336 return true;
337 }
338
339 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
340 SwitchToDataSection(TAI->getStaticDtorsSection());
341 EmitAlignment(Align, 0);
342 EmitXXStructorList(GV->getInitializer());
343 return true;
344 }
345
346 return false;
347}
348
349/// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
350/// global in the specified llvm.used list as being used with this directive.
351void AsmPrinter::EmitLLVMUsedList(Constant *List) {
352 const char *Directive = TAI->getUsedDirective();
353
354 // Should be an array of 'sbyte*'.
355 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
356 if (InitList == 0) return;
357
358 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
359 O << Directive;
360 EmitConstantValueOnly(InitList->getOperand(i));
361 O << "\n";
362 }
363}
364
365/// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
366/// function pointers, ignoring the init priority.
367void AsmPrinter::EmitXXStructorList(Constant *List) {
368 // Should be an array of '{ int, void ()* }' structs. The first value is the
369 // init priority, which we ignore.
370 if (!isa<ConstantArray>(List)) return;
371 ConstantArray *InitList = cast<ConstantArray>(List);
372 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
373 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
374 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
375
376 if (CS->getOperand(1)->isNullValue())
377 return; // Found a null terminator, exit printing.
378 // Emit the function pointer.
379 EmitGlobalConstant(CS->getOperand(1));
380 }
381}
382
383/// getGlobalLinkName - Returns the asm/link name of of the specified
384/// global variable. Should be overridden by each target asm printer to
385/// generate the appropriate value.
386const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
387 std::string LinkName;
388
389 if (isa<Function>(GV)) {
390 LinkName += TAI->getFunctionAddrPrefix();
391 LinkName += Mang->getValueName(GV);
392 LinkName += TAI->getFunctionAddrSuffix();
393 } else {
394 LinkName += TAI->getGlobalVarAddrPrefix();
395 LinkName += Mang->getValueName(GV);
396 LinkName += TAI->getGlobalVarAddrSuffix();
397 }
398
399 return LinkName;
400}
401
402/// EmitExternalGlobal - Emit the external reference to a global variable.
403/// Should be overridden if an indirect reference should be used.
404void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
405 O << getGlobalLinkName(GV);
406}
407
408
409
410//===----------------------------------------------------------------------===//
411/// LEB 128 number encoding.
412
413/// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
414/// representing an unsigned leb128 value.
415void AsmPrinter::PrintULEB128(unsigned Value) const {
416 do {
417 unsigned Byte = Value & 0x7f;
418 Value >>= 7;
419 if (Value) Byte |= 0x80;
420 O << "0x" << std::hex << Byte << std::dec;
421 if (Value) O << ", ";
422 } while (Value);
423}
424
425/// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
426/// value.
427unsigned AsmPrinter::SizeULEB128(unsigned Value) {
428 unsigned Size = 0;
429 do {
430 Value >>= 7;
431 Size += sizeof(int8_t);
432 } while (Value);
433 return Size;
434}
435
436/// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
437/// representing a signed leb128 value.
438void AsmPrinter::PrintSLEB128(int Value) const {
439 int Sign = Value >> (8 * sizeof(Value) - 1);
440 bool IsMore;
441
442 do {
443 unsigned Byte = Value & 0x7f;
444 Value >>= 7;
445 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
446 if (IsMore) Byte |= 0x80;
447 O << "0x" << std::hex << Byte << std::dec;
448 if (IsMore) O << ", ";
449 } while (IsMore);
450}
451
452/// SizeSLEB128 - Compute the number of bytes required for a signed leb128
453/// value.
454unsigned AsmPrinter::SizeSLEB128(int Value) {
455 unsigned Size = 0;
456 int Sign = Value >> (8 * sizeof(Value) - 1);
457 bool IsMore;
458
459 do {
460 unsigned Byte = Value & 0x7f;
461 Value >>= 7;
462 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
463 Size += sizeof(int8_t);
464 } while (IsMore);
465 return Size;
466}
467
468//===--------------------------------------------------------------------===//
469// Emission and print routines
470//
471
472/// PrintHex - Print a value as a hexidecimal value.
473///
474void AsmPrinter::PrintHex(int Value) const {
475 O << "0x" << std::hex << Value << std::dec;
476}
477
478/// EOL - Print a newline character to asm stream. If a comment is present
479/// then it will be printed first. Comments should not contain '\n'.
480void AsmPrinter::EOL() const {
481 O << "\n";
482}
483void AsmPrinter::EOL(const std::string &Comment) const {
484 if (AsmVerbose && !Comment.empty()) {
485 O << "\t"
486 << TAI->getCommentString()
487 << " "
488 << Comment;
489 }
490 O << "\n";
491}
492
493/// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
494/// unsigned leb128 value.
495void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
496 if (TAI->hasLEB128()) {
497 O << "\t.uleb128\t"
498 << Value;
499 } else {
500 O << TAI->getData8bitsDirective();
501 PrintULEB128(Value);
502 }
503}
504
505/// EmitSLEB128Bytes - print an assembler byte data directive to compose a
506/// signed leb128 value.
507void AsmPrinter::EmitSLEB128Bytes(int Value) const {
508 if (TAI->hasLEB128()) {
509 O << "\t.sleb128\t"
510 << Value;
511 } else {
512 O << TAI->getData8bitsDirective();
513 PrintSLEB128(Value);
514 }
515}
516
517/// EmitInt8 - Emit a byte directive and value.
518///
519void AsmPrinter::EmitInt8(int Value) const {
520 O << TAI->getData8bitsDirective();
521 PrintHex(Value & 0xFF);
522}
523
524/// EmitInt16 - Emit a short directive and value.
525///
526void AsmPrinter::EmitInt16(int Value) const {
527 O << TAI->getData16bitsDirective();
528 PrintHex(Value & 0xFFFF);
529}
530
531/// EmitInt32 - Emit a long directive and value.
532///
533void AsmPrinter::EmitInt32(int Value) const {
534 O << TAI->getData32bitsDirective();
535 PrintHex(Value);
536}
537
538/// EmitInt64 - Emit a long long directive and value.
539///
540void AsmPrinter::EmitInt64(uint64_t Value) const {
541 if (TAI->getData64bitsDirective()) {
542 O << TAI->getData64bitsDirective();
543 PrintHex(Value);
544 } else {
545 if (TM.getTargetData()->isBigEndian()) {
546 EmitInt32(unsigned(Value >> 32)); O << "\n";
547 EmitInt32(unsigned(Value));
548 } else {
549 EmitInt32(unsigned(Value)); O << "\n";
550 EmitInt32(unsigned(Value >> 32));
551 }
552 }
553}
554
555/// toOctal - Convert the low order bits of X into an octal digit.
556///
557static inline char toOctal(int X) {
558 return (X&7)+'0';
559}
560
561/// printStringChar - Print a char, escaped if necessary.
562///
563static void printStringChar(std::ostream &O, unsigned char C) {
564 if (C == '"') {
565 O << "\\\"";
566 } else if (C == '\\') {
567 O << "\\\\";
568 } else if (isprint(C)) {
569 O << C;
570 } else {
571 switch(C) {
572 case '\b': O << "\\b"; break;
573 case '\f': O << "\\f"; break;
574 case '\n': O << "\\n"; break;
575 case '\r': O << "\\r"; break;
576 case '\t': O << "\\t"; break;
577 default:
578 O << '\\';
579 O << toOctal(C >> 6);
580 O << toOctal(C >> 3);
581 O << toOctal(C >> 0);
582 break;
583 }
584 }
585}
586
587/// EmitString - Emit a string with quotes and a null terminator.
588/// Special characters are emitted properly.
589/// \literal (Eg. '\t') \endliteral
590void AsmPrinter::EmitString(const std::string &String) const {
591 const char* AscizDirective = TAI->getAscizDirective();
592 if (AscizDirective)
593 O << AscizDirective;
594 else
595 O << TAI->getAsciiDirective();
596 O << "\"";
597 for (unsigned i = 0, N = String.size(); i < N; ++i) {
598 unsigned char C = String[i];
599 printStringChar(O, C);
600 }
601 if (AscizDirective)
602 O << "\"";
603 else
604 O << "\\0\"";
605}
606
607
608//===----------------------------------------------------------------------===//
609
610// EmitAlignment - Emit an alignment directive to the specified power of
611// two boundary. For example, if you pass in 3 here, you will get an 8
612// byte alignment. If a global value is specified, and if that global has
613// an explicit alignment requested, it will unconditionally override the
614// alignment request. However, if ForcedAlignBits is specified, this value
615// has final say: the ultimate alignment will be the max of ForcedAlignBits
616// and the alignment computed with NumBits and the global.
617//
618// The algorithm is:
619// Align = NumBits;
620// if (GV && GV->hasalignment) Align = GV->getalignment();
621// Align = std::max(Align, ForcedAlignBits);
622//
623void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
Evan Chengc1f41aa2007-07-25 23:35:07 +0000624 unsigned ForcedAlignBits, bool UseFillExpr,
625 unsigned FillValue) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 if (GV && GV->getAlignment())
627 NumBits = Log2_32(GV->getAlignment());
628 NumBits = std::max(NumBits, ForcedAlignBits);
629
630 if (NumBits == 0) return; // No need to emit alignment.
631 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
Evan Chengc1f41aa2007-07-25 23:35:07 +0000632 O << TAI->getAlignDirective() << NumBits;
633 if (UseFillExpr) O << ",0x" << std::hex << FillValue << std::dec;
634 O << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000635}
636
637
638/// EmitZeros - Emit a block of zeros.
639///
640void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
641 if (NumZeros) {
642 if (TAI->getZeroDirective()) {
643 O << TAI->getZeroDirective() << NumZeros;
644 if (TAI->getZeroDirectiveSuffix())
645 O << TAI->getZeroDirectiveSuffix();
646 O << "\n";
647 } else {
648 for (; NumZeros; --NumZeros)
649 O << TAI->getData8bitsDirective() << "0\n";
650 }
651 }
652}
653
654// Print out the specified constant, without a storage class. Only the
655// constants valid in constant expressions can occur here.
656void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
657 if (CV->isNullValue() || isa<UndefValue>(CV))
658 O << "0";
659 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
660 O << CI->getZExtValue();
661 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
662 // This is a constant address for a global variable or function. Use the
663 // name of the variable or function as the address value, possibly
664 // decorating it with GlobalVarAddrPrefix/Suffix or
665 // FunctionAddrPrefix/Suffix (these all default to "" )
666 if (isa<Function>(GV)) {
667 O << TAI->getFunctionAddrPrefix()
668 << Mang->getValueName(GV)
669 << TAI->getFunctionAddrSuffix();
670 } else {
671 O << TAI->getGlobalVarAddrPrefix()
672 << Mang->getValueName(GV)
673 << TAI->getGlobalVarAddrSuffix();
674 }
675 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
676 const TargetData *TD = TM.getTargetData();
677 unsigned Opcode = CE->getOpcode();
678 switch (Opcode) {
679 case Instruction::GetElementPtr: {
680 // generate a symbolic expression for the byte address
681 const Constant *ptrVal = CE->getOperand(0);
682 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
683 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
684 idxVec.size())) {
685 if (Offset)
686 O << "(";
687 EmitConstantValueOnly(ptrVal);
688 if (Offset > 0)
689 O << ") + " << Offset;
690 else if (Offset < 0)
691 O << ") - " << -Offset;
692 } else {
693 EmitConstantValueOnly(ptrVal);
694 }
695 break;
696 }
697 case Instruction::Trunc:
698 case Instruction::ZExt:
699 case Instruction::SExt:
700 case Instruction::FPTrunc:
701 case Instruction::FPExt:
702 case Instruction::UIToFP:
703 case Instruction::SIToFP:
704 case Instruction::FPToUI:
705 case Instruction::FPToSI:
706 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
707 break;
708 case Instruction::BitCast:
709 return EmitConstantValueOnly(CE->getOperand(0));
710
711 case Instruction::IntToPtr: {
712 // Handle casts to pointers by changing them into casts to the appropriate
713 // integer type. This promotes constant folding and simplifies this code.
714 Constant *Op = CE->getOperand(0);
715 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
716 return EmitConstantValueOnly(Op);
717 }
718
719
720 case Instruction::PtrToInt: {
721 // Support only foldable casts to/from pointers that can be eliminated by
722 // changing the pointer to the appropriately sized integer type.
723 Constant *Op = CE->getOperand(0);
724 const Type *Ty = CE->getType();
725
726 // We can emit the pointer value into this slot if the slot is an
727 // integer slot greater or equal to the size of the pointer.
728 if (Ty->isInteger() &&
729 TD->getTypeSize(Ty) >= TD->getTypeSize(Op->getType()))
730 return EmitConstantValueOnly(Op);
731
732 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
733 EmitConstantValueOnly(Op);
734 break;
735 }
736 case Instruction::Add:
737 case Instruction::Sub:
738 O << "(";
739 EmitConstantValueOnly(CE->getOperand(0));
740 O << (Opcode==Instruction::Add ? ") + (" : ") - (");
741 EmitConstantValueOnly(CE->getOperand(1));
742 O << ")";
743 break;
744 default:
745 assert(0 && "Unsupported operator!");
746 }
747 } else {
748 assert(0 && "Unknown constant value!");
749 }
750}
751
752/// printAsCString - Print the specified array as a C compatible string, only if
753/// the predicate isString is true.
754///
755static void printAsCString(std::ostream &O, const ConstantArray *CVA,
756 unsigned LastElt) {
757 assert(CVA->isString() && "Array is not string compatible!");
758
759 O << "\"";
760 for (unsigned i = 0; i != LastElt; ++i) {
761 unsigned char C =
762 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
763 printStringChar(O, C);
764 }
765 O << "\"";
766}
767
768/// EmitString - Emit a zero-byte-terminated string constant.
769///
770void AsmPrinter::EmitString(const ConstantArray *CVA) const {
771 unsigned NumElts = CVA->getNumOperands();
772 if (TAI->getAscizDirective() && NumElts &&
773 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
774 O << TAI->getAscizDirective();
775 printAsCString(O, CVA, NumElts-1);
776 } else {
777 O << TAI->getAsciiDirective();
778 printAsCString(O, CVA, NumElts);
779 }
780 O << "\n";
781}
782
783/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
784///
785void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
786 const TargetData *TD = TM.getTargetData();
787
788 if (CV->isNullValue() || isa<UndefValue>(CV)) {
789 EmitZeros(TD->getTypeSize(CV->getType()));
790 return;
791 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
792 if (CVA->isString()) {
793 EmitString(CVA);
794 } else { // Not a string. Print the values in successive locations
795 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
796 EmitGlobalConstant(CVA->getOperand(i));
797 }
798 return;
799 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
800 // Print the fields in successive locations. Pad to align if needed!
801 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
802 uint64_t sizeSoFar = 0;
803 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
804 const Constant* field = CVS->getOperand(i);
805
806 // Check if padding is needed and insert one or more 0s.
807 uint64_t fieldSize = TD->getTypeSize(field->getType());
808 uint64_t padSize = ((i == e-1? cvsLayout->getSizeInBytes()
809 : cvsLayout->getElementOffset(i+1))
810 - cvsLayout->getElementOffset(i)) - fieldSize;
811 sizeSoFar += fieldSize + padSize;
812
813 // Now print the actual field value
814 EmitGlobalConstant(field);
815
816 // Insert the field padding unless it's zero bytes...
817 EmitZeros(padSize);
818 }
819 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
820 "Layout of constant struct may be incorrect!");
821 return;
822 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
823 // FP Constants are printed as integer constants to avoid losing
824 // precision...
825 double Val = CFP->getValue();
826 if (CFP->getType() == Type::DoubleTy) {
827 if (TAI->getData64bitsDirective())
828 O << TAI->getData64bitsDirective() << DoubleToBits(Val) << "\t"
829 << TAI->getCommentString() << " double value: " << Val << "\n";
830 else if (TD->isBigEndian()) {
831 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
832 << "\t" << TAI->getCommentString()
833 << " double most significant word " << Val << "\n";
834 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
835 << "\t" << TAI->getCommentString()
836 << " double least significant word " << Val << "\n";
837 } else {
838 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
839 << "\t" << TAI->getCommentString()
840 << " double least significant word " << Val << "\n";
841 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
842 << "\t" << TAI->getCommentString()
843 << " double most significant word " << Val << "\n";
844 }
845 return;
846 } else {
847 O << TAI->getData32bitsDirective() << FloatToBits(Val)
848 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
849 return;
850 }
851 } else if (CV->getType() == Type::Int64Ty) {
852 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
853 uint64_t Val = CI->getZExtValue();
854
855 if (TAI->getData64bitsDirective())
856 O << TAI->getData64bitsDirective() << Val << "\n";
857 else if (TD->isBigEndian()) {
858 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
859 << "\t" << TAI->getCommentString()
860 << " Double-word most significant word " << Val << "\n";
861 O << TAI->getData32bitsDirective() << unsigned(Val)
862 << "\t" << TAI->getCommentString()
863 << " Double-word least significant word " << Val << "\n";
864 } else {
865 O << TAI->getData32bitsDirective() << unsigned(Val)
866 << "\t" << TAI->getCommentString()
867 << " Double-word least significant word " << Val << "\n";
868 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
869 << "\t" << TAI->getCommentString()
870 << " Double-word most significant word " << Val << "\n";
871 }
872 return;
873 }
874 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
875 const VectorType *PTy = CP->getType();
876
877 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
878 EmitGlobalConstant(CP->getOperand(I));
879
880 return;
881 }
882
883 const Type *type = CV->getType();
884 printDataDirective(type);
885 EmitConstantValueOnly(CV);
886 O << "\n";
887}
888
889void
890AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
891 // Target doesn't support this yet!
892 abort();
893}
894
895/// PrintSpecial - Print information related to the specified machine instr
896/// that is independent of the operand, and may be independent of the instr
897/// itself. This can be useful for portably encoding the comment character
898/// or other bits of target-specific knowledge into the asmstrings. The
899/// syntax used is ${:comment}. Targets can override this to add support
900/// for their own strange codes.
901void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
902 if (!strcmp(Code, "private")) {
903 O << TAI->getPrivateGlobalPrefix();
904 } else if (!strcmp(Code, "comment")) {
905 O << TAI->getCommentString();
906 } else if (!strcmp(Code, "uid")) {
907 // Assign a unique ID to this machine instruction.
908 static const MachineInstr *LastMI = 0;
909 static const Function *F = 0;
910 static unsigned Counter = 0U-1;
911
912 // Comparing the address of MI isn't sufficient, because machineinstrs may
913 // be allocated to the same address across functions.
914 const Function *ThisF = MI->getParent()->getParent()->getFunction();
915
916 // If this is a new machine instruction, bump the counter.
917 if (LastMI != MI || F != ThisF) {
918 ++Counter;
919 LastMI = MI;
920 F = ThisF;
921 }
922 O << Counter;
923 } else {
924 cerr << "Unknown special formatter '" << Code
925 << "' for machine instr: " << *MI;
926 exit(1);
927 }
928}
929
930
931/// printInlineAsm - This method formats and prints the specified machine
932/// instruction that is an inline asm.
933void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
934 unsigned NumOperands = MI->getNumOperands();
935
936 // Count the number of register definitions.
937 unsigned NumDefs = 0;
938 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
939 ++NumDefs)
940 assert(NumDefs != NumOperands-1 && "No asm string?");
941
942 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
943
944 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
945 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
946
947 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
948 if (AsmStr[0] == 0) {
949 O << "\n"; // Tab already printed, avoid double indenting next instr.
950 return;
951 }
952
953 O << TAI->getInlineAsmStart() << "\n\t";
954
955 // The variant of the current asmprinter.
956 int AsmPrinterVariant = TAI->getAssemblerDialect();
957
958 int CurVariant = -1; // The number of the {.|.|.} region we are in.
959 const char *LastEmitted = AsmStr; // One past the last character emitted.
960
961 while (*LastEmitted) {
962 switch (*LastEmitted) {
963 default: {
964 // Not a special case, emit the string section literally.
965 const char *LiteralEnd = LastEmitted+1;
966 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
967 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
968 ++LiteralEnd;
969 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
970 O.write(LastEmitted, LiteralEnd-LastEmitted);
971 LastEmitted = LiteralEnd;
972 break;
973 }
974 case '\n':
975 ++LastEmitted; // Consume newline character.
976 O << "\n"; // Indent code with newline.
977 break;
978 case '$': {
979 ++LastEmitted; // Consume '$' character.
980 bool Done = true;
981
982 // Handle escapes.
983 switch (*LastEmitted) {
984 default: Done = false; break;
985 case '$': // $$ -> $
986 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
987 O << '$';
988 ++LastEmitted; // Consume second '$' character.
989 break;
990 case '(': // $( -> same as GCC's { character.
991 ++LastEmitted; // Consume '(' character.
992 if (CurVariant != -1) {
993 cerr << "Nested variants found in inline asm string: '"
994 << AsmStr << "'\n";
995 exit(1);
996 }
997 CurVariant = 0; // We're in the first variant now.
998 break;
999 case '|':
1000 ++LastEmitted; // consume '|' character.
1001 if (CurVariant == -1) {
1002 cerr << "Found '|' character outside of variant in inline asm "
1003 << "string: '" << AsmStr << "'\n";
1004 exit(1);
1005 }
1006 ++CurVariant; // We're in the next variant.
1007 break;
1008 case ')': // $) -> same as GCC's } char.
1009 ++LastEmitted; // consume ')' character.
1010 if (CurVariant == -1) {
1011 cerr << "Found '}' character outside of variant in inline asm "
1012 << "string: '" << AsmStr << "'\n";
1013 exit(1);
1014 }
1015 CurVariant = -1;
1016 break;
1017 }
1018 if (Done) break;
1019
1020 bool HasCurlyBraces = false;
1021 if (*LastEmitted == '{') { // ${variable}
1022 ++LastEmitted; // Consume '{' character.
1023 HasCurlyBraces = true;
1024 }
1025
1026 const char *IDStart = LastEmitted;
1027 char *IDEnd;
1028 errno = 0;
1029 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1030 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1031 cerr << "Bad $ operand number in inline asm string: '"
1032 << AsmStr << "'\n";
1033 exit(1);
1034 }
1035 LastEmitted = IDEnd;
1036
1037 char Modifier[2] = { 0, 0 };
1038
1039 if (HasCurlyBraces) {
1040 // If we have curly braces, check for a modifier character. This
1041 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1042 if (*LastEmitted == ':') {
1043 ++LastEmitted; // Consume ':' character.
1044 if (*LastEmitted == 0) {
1045 cerr << "Bad ${:} expression in inline asm string: '"
1046 << AsmStr << "'\n";
1047 exit(1);
1048 }
1049
1050 Modifier[0] = *LastEmitted;
1051 ++LastEmitted; // Consume modifier character.
1052 }
1053
1054 if (*LastEmitted != '}') {
1055 cerr << "Bad ${} expression in inline asm string: '"
1056 << AsmStr << "'\n";
1057 exit(1);
1058 }
1059 ++LastEmitted; // Consume '}' character.
1060 }
1061
1062 if ((unsigned)Val >= NumOperands-1) {
1063 cerr << "Invalid $ operand number in inline asm string: '"
1064 << AsmStr << "'\n";
1065 exit(1);
1066 }
1067
1068 // Okay, we finally have a value number. Ask the target to print this
1069 // operand!
1070 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1071 unsigned OpNo = 1;
1072
1073 bool Error = false;
1074
1075 // Scan to find the machine operand number for the operand.
1076 for (; Val; --Val) {
1077 if (OpNo >= MI->getNumOperands()) break;
1078 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1079 OpNo += (OpFlags >> 3) + 1;
1080 }
1081
1082 if (OpNo >= MI->getNumOperands()) {
1083 Error = true;
1084 } else {
1085 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1086 ++OpNo; // Skip over the ID number.
1087
1088 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1089 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
1090 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1091 Modifier[0] ? Modifier : 0);
1092 } else {
1093 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1094 Modifier[0] ? Modifier : 0);
1095 }
1096 }
1097 if (Error) {
1098 cerr << "Invalid operand found in inline asm: '"
1099 << AsmStr << "'\n";
1100 MI->dump();
1101 exit(1);
1102 }
1103 }
1104 break;
1105 }
1106 }
1107 }
1108 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
1109}
1110
1111/// printLabel - This method prints a local label used by debug and
1112/// exception handling tables.
1113void AsmPrinter::printLabel(const MachineInstr *MI) const {
1114 O << "\n"
1115 << TAI->getPrivateGlobalPrefix()
1116 << "label"
1117 << MI->getOperand(0).getImmedValue()
1118 << ":\n";
1119}
1120
1121/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1122/// instruction, using the specified assembler variant. Targets should
1123/// overried this to format as appropriate.
1124bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1125 unsigned AsmVariant, const char *ExtraCode) {
1126 // Target doesn't support this yet!
1127 return true;
1128}
1129
1130bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1131 unsigned AsmVariant,
1132 const char *ExtraCode) {
1133 // Target doesn't support this yet!
1134 return true;
1135}
1136
1137/// printBasicBlockLabel - This method prints the label for the specified
1138/// MachineBasicBlock
1139void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1140 bool printColon,
1141 bool printComment) const {
1142 O << TAI->getPrivateGlobalPrefix() << "BB" << FunctionNumber << "_"
1143 << MBB->getNumber();
1144 if (printColon)
1145 O << ':';
1146 if (printComment && MBB->getBasicBlock())
Dan Gohman0912cda2007-07-30 15:06:25 +00001147 O << '\t' << TAI->getCommentString() << ' '
1148 << MBB->getBasicBlock()->getName();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149}
1150
1151/// printSetLabel - This method prints a set label for the specified
1152/// MachineBasicBlock
1153void AsmPrinter::printSetLabel(unsigned uid,
1154 const MachineBasicBlock *MBB) const {
1155 if (!TAI->getSetDirective())
1156 return;
1157
1158 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1159 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1160 printBasicBlockLabel(MBB, false, false);
1161 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1162 << '_' << uid << '\n';
1163}
1164
1165void AsmPrinter::printSetLabel(unsigned uid, unsigned uid2,
1166 const MachineBasicBlock *MBB) const {
1167 if (!TAI->getSetDirective())
1168 return;
1169
1170 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1171 << getFunctionNumber() << '_' << uid << '_' << uid2
1172 << "_set_" << MBB->getNumber() << ',';
1173 printBasicBlockLabel(MBB, false, false);
1174 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1175 << '_' << uid << '_' << uid2 << '\n';
1176}
1177
1178/// printDataDirective - This method prints the asm directive for the
1179/// specified type.
1180void AsmPrinter::printDataDirective(const Type *type) {
1181 const TargetData *TD = TM.getTargetData();
1182 switch (type->getTypeID()) {
1183 case Type::IntegerTyID: {
1184 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1185 if (BitWidth <= 8)
1186 O << TAI->getData8bitsDirective();
1187 else if (BitWidth <= 16)
1188 O << TAI->getData16bitsDirective();
1189 else if (BitWidth <= 32)
1190 O << TAI->getData32bitsDirective();
1191 else if (BitWidth <= 64) {
1192 assert(TAI->getData64bitsDirective() &&
1193 "Target cannot handle 64-bit constant exprs!");
1194 O << TAI->getData64bitsDirective();
1195 }
1196 break;
1197 }
1198 case Type::PointerTyID:
1199 if (TD->getPointerSize() == 8) {
1200 assert(TAI->getData64bitsDirective() &&
1201 "Target cannot handle 64-bit pointer exprs!");
1202 O << TAI->getData64bitsDirective();
1203 } else {
1204 O << TAI->getData32bitsDirective();
1205 }
1206 break;
1207 case Type::FloatTyID: case Type::DoubleTyID:
1208 assert (0 && "Should have already output floating point constant.");
1209 default:
1210 assert (0 && "Can't handle printing this type of thing");
1211 break;
1212 }
1213}
1214