1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the AsmPrinter class.
12 //===----------------------------------------------------------------------===//
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"
33 AsmVerbose("asm-verbose", cl::Hidden
, cl::desc("Add comments to directives."));
35 char AsmPrinter::ID
= 0;
36 AsmPrinter::AsmPrinter(std::ostream
&o
, TargetMachine
&tm
,
37 const TargetAsmInfo
*T
)
38 : MachineFunctionPass((intptr_t)&ID
), FunctionNumber(0), O(o
), TM(tm
), TAI(T
)
41 std::string
AsmPrinter::getSectionForFunction(const Function
&F
) const {
42 return TAI
->getTextSection();
46 /// SwitchToTextSection - Switch to the specified text section of the executable
47 /// if we are not already in it!
49 void AsmPrinter::SwitchToTextSection(const char *NewSection
,
50 const GlobalValue
*GV
) {
52 if (GV
&& GV
->hasSection())
53 NS
= TAI
->getSwitchToSectionDirective() + GV
->getSection();
57 // If we're already in this section, we're done.
58 if (CurrentSection
== NS
) return;
60 // Close the current section, if applicable.
61 if (TAI
->getSectionEndDirectiveSuffix() && !CurrentSection
.empty())
62 O
<< CurrentSection
<< TAI
->getSectionEndDirectiveSuffix() << "\n";
66 if (!CurrentSection
.empty())
67 O
<< CurrentSection
<< TAI
->getTextSectionStartSuffix() << '\n';
70 /// SwitchToDataSection - Switch to the specified data section of the executable
71 /// if we are not already in it!
73 void AsmPrinter::SwitchToDataSection(const char *NewSection
,
74 const GlobalValue
*GV
) {
76 if (GV
&& GV
->hasSection())
77 NS
= TAI
->getSwitchToSectionDirective() + GV
->getSection();
81 // If we're already in this section, we're done.
82 if (CurrentSection
== NS
) return;
84 // Close the current section, if applicable.
85 if (TAI
->getSectionEndDirectiveSuffix() && !CurrentSection
.empty())
86 O
<< CurrentSection
<< TAI
->getSectionEndDirectiveSuffix() << "\n";
90 if (!CurrentSection
.empty())
91 O
<< CurrentSection
<< TAI
->getDataSectionStartSuffix() << '\n';
95 bool AsmPrinter::doInitialization(Module
&M
) {
96 Mang
= new Mangler(M
, TAI
->getGlobalPrefix());
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";
104 SwitchToDataSection(""); // Reset back to no section.
106 if (MachineModuleInfo
*MMI
= getAnalysisToUpdate
<MachineModuleInfo
>()) {
107 MMI
->AnalyzeModule(M
);
113 bool AsmPrinter::doFinalization(Module
&M
) {
114 if (TAI
->getWeakRefDirective()) {
115 if (!ExtWeakSymbols
.empty())
116 SwitchToDataSection("");
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";
126 if (TAI
->getSetDirective()) {
127 if (!M
.alias_empty())
128 SwitchToTextSection(TAI
->getTextSection());
131 for (Module::const_alias_iterator I
= M
.alias_begin(), E
= M
.alias_end();
133 std::string Name
= Mang
->getValueName(I
);
136 if (const GlobalValue
*GV
= I
->getAliasedGlobal())
137 Target
= Mang
->getValueName(GV
);
139 assert(0 && "Unsupported aliasee");
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");
148 O
<< TAI
->getSetDirective() << Name
<< ", " << Target
<< "\n";
152 delete Mang
; Mang
= 0;
156 void AsmPrinter::SetupMachineFunction(MachineFunction
&MF
) {
157 // What's my mangled name?
158 CurrentFnName
= Mang
->getValueName(MF
.getFunction());
159 IncrementFunctionNumber();
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.
167 void AsmPrinter::EmitConstantPool(MachineConstantPool
*MCP
) {
168 const std::vector
<MachineConstantPoolEntry
> &CP
= MCP
->getConstants();
169 if (CP
.empty()) return;
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
));
191 OtherCPs
.push_back(std::make_pair(CPE
, i
));
194 unsigned Alignment
= MCP
->getConstantPoolAlignment();
195 EmitConstantPool(Alignment
, TAI
->getFourByteConstantSection(), FourByteCPs
);
196 EmitConstantPool(Alignment
, TAI
->getEightByteConstantSection(), EightByteCPs
);
197 EmitConstantPool(Alignment
, TAI
->getSixteenByteConstantSection(),
199 EmitConstantPool(Alignment
, TAI
->getConstantPoolSection(), OtherCPs
);
202 void AsmPrinter::EmitConstantPool(unsigned Alignment
, const char *Section
,
203 std::vector
<std::pair
<MachineConstantPoolEntry
,unsigned> > &CP
) {
204 if (CP
.empty()) return;
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
);
215 EmitGlobalConstant(CP
[i
].first
.Val
.ConstVal
);
217 const Type
*Ty
= CP
[i
].first
.getType();
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
);
227 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
228 /// by the current function to the current output stream.
230 void 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_
;
236 // Use JumpTableDirective otherwise honor the entry size from the jump table
238 const char *JTEntryDirective
= TAI
->getJumpTableDirective();
239 bool HadJTEntryDirective
= JTEntryDirective
!= NULL
;
240 if (!HadJTEntryDirective
) {
241 JTEntryDirective
= MJTI
->getEntrySize() == 4 ?
242 TAI
->getData32bitsDirective() : TAI
->getData64bitsDirective();
245 // Pick the directive to use to print the jump table entries, and switch to
246 // the appropriate section.
247 TargetLowering
*LoweringInfo
= TM
.getTargetLowering();
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
);
258 SwitchToDataSection(JumpTableDataSection
);
261 EmitAlignment(Log2_32(MJTI
->getAlignment()));
263 for (unsigned i
= 0, e
= JT
.size(); i
!= e
; ++i
) {
264 const std::vector
<MachineBasicBlock
*> &JTBBs
= JT
[i
].MBBs
;
266 // If this jump table was deleted, ignore it.
267 if (JTBBs
.empty()) continue;
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
]);
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";
285 O
<< TAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
286 << '_' << i
<< ":\n";
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();
299 printBasicBlockLabel(JTBBs
[ii
], false, false);
300 // If the arch uses custom Jump Table directives, don't calc relative to
302 if (!HadJTEntryDirective
)
303 O
<< '-' << TAI
->getPrivateGlobalPrefix() << "JTI"
304 << getFunctionNumber() << '_' << i
;
306 printBasicBlockLabel(JTBBs
[ii
], false, false);
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.
316 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable
*GV
) {
317 // Ignore debug and non-emitted data.
318 if (GV
->getSection() == "llvm.metadata") return true;
320 if (!GV
->hasAppendingLinkage()) return false;
322 assert(GV
->hasInitializer() && "Not a special LLVM global!");
324 if (GV
->getName() == "llvm.used") {
325 if (TAI
->getUsedDirective() != 0) // No need to emit this at all.
326 EmitLLVMUsedList(GV
->getInitializer());
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());
339 if (GV
->getName() == "llvm.global_dtors" && GV
->use_empty()) {
340 SwitchToDataSection(TAI
->getStaticDtorsSection());
341 EmitAlignment(Align
, 0);
342 EmitXXStructorList(GV
->getInitializer());
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.
351 void AsmPrinter::EmitLLVMUsedList(Constant
*List
) {
352 const char *Directive
= TAI
->getUsedDirective();
354 // Should be an array of 'sbyte*'.
355 ConstantArray
*InitList
= dyn_cast
<ConstantArray
>(List
);
356 if (InitList
== 0) return;
358 for (unsigned i
= 0, e
= InitList
->getNumOperands(); i
!= e
; ++i
) {
360 EmitConstantValueOnly(InitList
->getOperand(i
));
365 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
366 /// function pointers, ignoring the init priority.
367 void 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.
376 if (CS
->getOperand(1)->isNullValue())
377 return; // Found a null terminator, exit printing.
378 // Emit the function pointer.
379 EmitGlobalConstant(CS
->getOperand(1));
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.
386 const std::string
AsmPrinter::getGlobalLinkName(const GlobalVariable
*GV
) const{
387 std::string LinkName
;
389 if (isa
<Function
>(GV
)) {
390 LinkName
+= TAI
->getFunctionAddrPrefix();
391 LinkName
+= Mang
->getValueName(GV
);
392 LinkName
+= TAI
->getFunctionAddrSuffix();
394 LinkName
+= TAI
->getGlobalVarAddrPrefix();
395 LinkName
+= Mang
->getValueName(GV
);
396 LinkName
+= TAI
->getGlobalVarAddrSuffix();
402 /// EmitExternalGlobal - Emit the external reference to a global variable.
403 /// Should be overridden if an indirect reference should be used.
404 void AsmPrinter::EmitExternalGlobal(const GlobalVariable
*GV
) {
405 O
<< getGlobalLinkName(GV
);
410 //===----------------------------------------------------------------------===//
411 /// LEB 128 number encoding.
413 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
414 /// representing an unsigned leb128 value.
415 void AsmPrinter::PrintULEB128(unsigned Value
) const {
417 unsigned Byte
= Value
& 0x7f;
419 if (Value
) Byte
|= 0x80;
420 O
<< "0x" << std::hex
<< Byte
<< std::dec
;
421 if (Value
) O
<< ", ";
425 /// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
427 unsigned AsmPrinter::SizeULEB128(unsigned Value
) {
431 Size
+= sizeof(int8_t);
436 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
437 /// representing a signed leb128 value.
438 void AsmPrinter::PrintSLEB128(int Value
) const {
439 int Sign
= Value
>> (8 * sizeof(Value
) - 1);
443 unsigned Byte
= Value
& 0x7f;
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
<< ", ";
452 /// SizeSLEB128 - Compute the number of bytes required for a signed leb128
454 unsigned AsmPrinter::SizeSLEB128(int Value
) {
456 int Sign
= Value
>> (8 * sizeof(Value
) - 1);
460 unsigned Byte
= Value
& 0x7f;
462 IsMore
= Value
!= Sign
|| ((Byte
^ Sign
) & 0x40) != 0;
463 Size
+= sizeof(int8_t);
468 //===--------------------------------------------------------------------===//
469 // Emission and print routines
472 /// PrintHex - Print a value as a hexidecimal value.
474 void AsmPrinter::PrintHex(int Value
) const {
475 O
<< "0x" << std::hex
<< Value
<< std::dec
;
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'.
480 void AsmPrinter::EOL() const {
483 void AsmPrinter::EOL(const std::string
&Comment
) const {
484 if (AsmVerbose
&& !Comment
.empty()) {
486 << TAI
->getCommentString()
493 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
494 /// unsigned leb128 value.
495 void AsmPrinter::EmitULEB128Bytes(unsigned Value
) const {
496 if (TAI
->hasLEB128()) {
500 O
<< TAI
->getData8bitsDirective();
505 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
506 /// signed leb128 value.
507 void AsmPrinter::EmitSLEB128Bytes(int Value
) const {
508 if (TAI
->hasLEB128()) {
512 O
<< TAI
->getData8bitsDirective();
517 /// EmitInt8 - Emit a byte directive and value.
519 void AsmPrinter::EmitInt8(int Value
) const {
520 O
<< TAI
->getData8bitsDirective();
521 PrintHex(Value
& 0xFF);
524 /// EmitInt16 - Emit a short directive and value.
526 void AsmPrinter::EmitInt16(int Value
) const {
527 O
<< TAI
->getData16bitsDirective();
528 PrintHex(Value
& 0xFFFF);
531 /// EmitInt32 - Emit a long directive and value.
533 void AsmPrinter::EmitInt32(int Value
) const {
534 O
<< TAI
->getData32bitsDirective();
538 /// EmitInt64 - Emit a long long directive and value.
540 void AsmPrinter::EmitInt64(uint64_t Value
) const {
541 if (TAI
->getData64bitsDirective()) {
542 O
<< TAI
->getData64bitsDirective();
545 if (TM
.getTargetData()->isBigEndian()) {
546 EmitInt32(unsigned(Value
>> 32)); O
<< "\n";
547 EmitInt32(unsigned(Value
));
549 EmitInt32(unsigned(Value
)); O
<< "\n";
550 EmitInt32(unsigned(Value
>> 32));
555 /// toOctal - Convert the low order bits of X into an octal digit.
557 static inline char toOctal(int X
) {
561 /// printStringChar - Print a char, escaped if necessary.
563 static void printStringChar(std::ostream
&O
, unsigned char C
) {
566 } else if (C
== '\\') {
568 } else if (isprint(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;
579 O
<< toOctal(C
>> 6);
580 O
<< toOctal(C
>> 3);
581 O
<< toOctal(C
>> 0);
587 /// EmitString - Emit a string with quotes and a null terminator.
588 /// Special characters are emitted properly.
589 /// \literal (Eg. '\t') \endliteral
590 void AsmPrinter::EmitString(const std::string
&String
) const {
591 const char* AscizDirective
= TAI
->getAscizDirective();
595 O
<< TAI
->getAsciiDirective();
597 for (unsigned i
= 0, N
= String
.size(); i
< N
; ++i
) {
598 unsigned char C
= String
[i
];
599 printStringChar(O
, C
);
608 //===----------------------------------------------------------------------===//
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.
620 // if (GV && GV->hasalignment) Align = GV->getalignment();
621 // Align = std::max(Align, ForcedAlignBits);
623 void AsmPrinter::EmitAlignment(unsigned NumBits
, const GlobalValue
*GV
,
624 unsigned ForcedAlignBits
) const {
625 if (GV
&& GV
->getAlignment())
626 NumBits
= Log2_32(GV
->getAlignment());
627 NumBits
= std::max(NumBits
, ForcedAlignBits
);
629 if (NumBits
== 0) return; // No need to emit alignment.
630 if (TAI
->getAlignmentIsInBytes()) NumBits
= 1 << NumBits
;
631 O
<< TAI
->getAlignDirective() << NumBits
<< "\n";
635 /// EmitZeros - Emit a block of zeros.
637 void AsmPrinter::EmitZeros(uint64_t NumZeros
) const {
639 if (TAI
->getZeroDirective()) {
640 O
<< TAI
->getZeroDirective() << NumZeros
;
641 if (TAI
->getZeroDirectiveSuffix())
642 O
<< TAI
->getZeroDirectiveSuffix();
645 for (; NumZeros
; --NumZeros
)
646 O
<< TAI
->getData8bitsDirective() << "0\n";
651 // Print out the specified constant, without a storage class. Only the
652 // constants valid in constant expressions can occur here.
653 void AsmPrinter::EmitConstantValueOnly(const Constant
*CV
) {
654 if (CV
->isNullValue() || isa
<UndefValue
>(CV
))
656 else if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
)) {
657 O
<< CI
->getZExtValue();
658 } else if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(CV
)) {
659 // This is a constant address for a global variable or function. Use the
660 // name of the variable or function as the address value, possibly
661 // decorating it with GlobalVarAddrPrefix/Suffix or
662 // FunctionAddrPrefix/Suffix (these all default to "" )
663 if (isa
<Function
>(GV
)) {
664 O
<< TAI
->getFunctionAddrPrefix()
665 << Mang
->getValueName(GV
)
666 << TAI
->getFunctionAddrSuffix();
668 O
<< TAI
->getGlobalVarAddrPrefix()
669 << Mang
->getValueName(GV
)
670 << TAI
->getGlobalVarAddrSuffix();
672 } else if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(CV
)) {
673 const TargetData
*TD
= TM
.getTargetData();
674 unsigned Opcode
= CE
->getOpcode();
676 case Instruction::GetElementPtr
: {
677 // generate a symbolic expression for the byte address
678 const Constant
*ptrVal
= CE
->getOperand(0);
679 SmallVector
<Value
*, 8> idxVec(CE
->op_begin()+1, CE
->op_end());
680 if (int64_t Offset
= TD
->getIndexedOffset(ptrVal
->getType(), &idxVec
[0],
684 EmitConstantValueOnly(ptrVal
);
686 O
<< ") + " << Offset
;
688 O
<< ") - " << -Offset
;
690 EmitConstantValueOnly(ptrVal
);
694 case Instruction::Trunc
:
695 case Instruction::ZExt
:
696 case Instruction::SExt
:
697 case Instruction::FPTrunc
:
698 case Instruction::FPExt
:
699 case Instruction::UIToFP
:
700 case Instruction::SIToFP
:
701 case Instruction::FPToUI
:
702 case Instruction::FPToSI
:
703 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
705 case Instruction::BitCast
:
706 return EmitConstantValueOnly(CE
->getOperand(0));
708 case Instruction::IntToPtr
: {
709 // Handle casts to pointers by changing them into casts to the appropriate
710 // integer type. This promotes constant folding and simplifies this code.
711 Constant
*Op
= CE
->getOperand(0);
712 Op
= ConstantExpr::getIntegerCast(Op
, TD
->getIntPtrType(), false/*ZExt*/);
713 return EmitConstantValueOnly(Op
);
717 case Instruction::PtrToInt
: {
718 // Support only foldable casts to/from pointers that can be eliminated by
719 // changing the pointer to the appropriately sized integer type.
720 Constant
*Op
= CE
->getOperand(0);
721 const Type
*Ty
= CE
->getType();
723 // We can emit the pointer value into this slot if the slot is an
724 // integer slot greater or equal to the size of the pointer.
725 if (Ty
->isInteger() &&
726 TD
->getTypeSize(Ty
) >= TD
->getTypeSize(Op
->getType()))
727 return EmitConstantValueOnly(Op
);
729 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
730 EmitConstantValueOnly(Op
);
733 case Instruction::Add
:
734 case Instruction::Sub
:
736 EmitConstantValueOnly(CE
->getOperand(0));
737 O
<< (Opcode
==Instruction::Add
? ") + (" : ") - (");
738 EmitConstantValueOnly(CE
->getOperand(1));
742 assert(0 && "Unsupported operator!");
745 assert(0 && "Unknown constant value!");
749 /// printAsCString - Print the specified array as a C compatible string, only if
750 /// the predicate isString is true.
752 static void printAsCString(std::ostream
&O
, const ConstantArray
*CVA
,
754 assert(CVA
->isString() && "Array is not string compatible!");
757 for (unsigned i
= 0; i
!= LastElt
; ++i
) {
759 (unsigned char)cast
<ConstantInt
>(CVA
->getOperand(i
))->getZExtValue();
760 printStringChar(O
, C
);
765 /// EmitString - Emit a zero-byte-terminated string constant.
767 void AsmPrinter::EmitString(const ConstantArray
*CVA
) const {
768 unsigned NumElts
= CVA
->getNumOperands();
769 if (TAI
->getAscizDirective() && NumElts
&&
770 cast
<ConstantInt
>(CVA
->getOperand(NumElts
-1))->getZExtValue() == 0) {
771 O
<< TAI
->getAscizDirective();
772 printAsCString(O
, CVA
, NumElts
-1);
774 O
<< TAI
->getAsciiDirective();
775 printAsCString(O
, CVA
, NumElts
);
780 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
782 void AsmPrinter::EmitGlobalConstant(const Constant
*CV
) {
783 const TargetData
*TD
= TM
.getTargetData();
785 if (CV
->isNullValue() || isa
<UndefValue
>(CV
)) {
786 EmitZeros(TD
->getTypeSize(CV
->getType()));
788 } else if (const ConstantArray
*CVA
= dyn_cast
<ConstantArray
>(CV
)) {
789 if (CVA
->isString()) {
791 } else { // Not a string. Print the values in successive locations
792 for (unsigned i
= 0, e
= CVA
->getNumOperands(); i
!= e
; ++i
)
793 EmitGlobalConstant(CVA
->getOperand(i
));
796 } else if (const ConstantStruct
*CVS
= dyn_cast
<ConstantStruct
>(CV
)) {
797 // Print the fields in successive locations. Pad to align if needed!
798 const StructLayout
*cvsLayout
= TD
->getStructLayout(CVS
->getType());
799 uint64_t sizeSoFar
= 0;
800 for (unsigned i
= 0, e
= CVS
->getNumOperands(); i
!= e
; ++i
) {
801 const Constant
* field
= CVS
->getOperand(i
);
803 // Check if padding is needed and insert one or more 0s.
804 uint64_t fieldSize
= TD
->getTypeSize(field
->getType());
805 uint64_t padSize
= ((i
== e
-1? cvsLayout
->getSizeInBytes()
806 : cvsLayout
->getElementOffset(i
+1))
807 - cvsLayout
->getElementOffset(i
)) - fieldSize
;
808 sizeSoFar
+= fieldSize
+ padSize
;
810 // Now print the actual field value
811 EmitGlobalConstant(field
);
813 // Insert the field padding unless it's zero bytes...
816 assert(sizeSoFar
== cvsLayout
->getSizeInBytes() &&
817 "Layout of constant struct may be incorrect!");
819 } else if (const ConstantFP
*CFP
= dyn_cast
<ConstantFP
>(CV
)) {
820 // FP Constants are printed as integer constants to avoid losing
822 double Val
= CFP
->getValue();
823 if (CFP
->getType() == Type::DoubleTy
) {
824 if (TAI
->getData64bitsDirective())
825 O
<< TAI
->getData64bitsDirective() << DoubleToBits(Val
) << "\t"
826 << TAI
->getCommentString() << " double value: " << Val
<< "\n";
827 else if (TD
->isBigEndian()) {
828 O
<< TAI
->getData32bitsDirective() << unsigned(DoubleToBits(Val
) >> 32)
829 << "\t" << TAI
->getCommentString()
830 << " double most significant word " << Val
<< "\n";
831 O
<< TAI
->getData32bitsDirective() << unsigned(DoubleToBits(Val
))
832 << "\t" << TAI
->getCommentString()
833 << " double least significant word " << Val
<< "\n";
835 O
<< TAI
->getData32bitsDirective() << unsigned(DoubleToBits(Val
))
836 << "\t" << TAI
->getCommentString()
837 << " double least significant word " << Val
<< "\n";
838 O
<< TAI
->getData32bitsDirective() << unsigned(DoubleToBits(Val
) >> 32)
839 << "\t" << TAI
->getCommentString()
840 << " double most significant word " << Val
<< "\n";
844 O
<< TAI
->getData32bitsDirective() << FloatToBits(Val
)
845 << "\t" << TAI
->getCommentString() << " float " << Val
<< "\n";
848 } else if (CV
->getType() == Type::Int64Ty
) {
849 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
)) {
850 uint64_t Val
= CI
->getZExtValue();
852 if (TAI
->getData64bitsDirective())
853 O
<< TAI
->getData64bitsDirective() << Val
<< "\n";
854 else if (TD
->isBigEndian()) {
855 O
<< TAI
->getData32bitsDirective() << unsigned(Val
>> 32)
856 << "\t" << TAI
->getCommentString()
857 << " Double-word most significant word " << Val
<< "\n";
858 O
<< TAI
->getData32bitsDirective() << unsigned(Val
)
859 << "\t" << TAI
->getCommentString()
860 << " Double-word least significant word " << Val
<< "\n";
862 O
<< TAI
->getData32bitsDirective() << unsigned(Val
)
863 << "\t" << TAI
->getCommentString()
864 << " Double-word least significant word " << Val
<< "\n";
865 O
<< TAI
->getData32bitsDirective() << unsigned(Val
>> 32)
866 << "\t" << TAI
->getCommentString()
867 << " Double-word most significant word " << Val
<< "\n";
871 } else if (const ConstantVector
*CP
= dyn_cast
<ConstantVector
>(CV
)) {
872 const VectorType
*PTy
= CP
->getType();
874 for (unsigned I
= 0, E
= PTy
->getNumElements(); I
< E
; ++I
)
875 EmitGlobalConstant(CP
->getOperand(I
));
880 const Type
*type
= CV
->getType();
881 printDataDirective(type
);
882 EmitConstantValueOnly(CV
);
887 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue
*MCPV
) {
888 // Target doesn't support this yet!
892 /// PrintSpecial - Print information related to the specified machine instr
893 /// that is independent of the operand, and may be independent of the instr
894 /// itself. This can be useful for portably encoding the comment character
895 /// or other bits of target-specific knowledge into the asmstrings. The
896 /// syntax used is ${:comment}. Targets can override this to add support
897 /// for their own strange codes.
898 void AsmPrinter::PrintSpecial(const MachineInstr
*MI
, const char *Code
) {
899 if (!strcmp(Code
, "private")) {
900 O
<< TAI
->getPrivateGlobalPrefix();
901 } else if (!strcmp(Code
, "comment")) {
902 O
<< TAI
->getCommentString();
903 } else if (!strcmp(Code
, "uid")) {
904 // Assign a unique ID to this machine instruction.
905 static const MachineInstr
*LastMI
= 0;
906 static const Function
*F
= 0;
907 static unsigned Counter
= 0U-1;
909 // Comparing the address of MI isn't sufficient, because machineinstrs may
910 // be allocated to the same address across functions.
911 const Function
*ThisF
= MI
->getParent()->getParent()->getFunction();
913 // If this is a new machine instruction, bump the counter.
914 if (LastMI
!= MI
|| F
!= ThisF
) {
921 cerr
<< "Unknown special formatter '" << Code
922 << "' for machine instr: " << *MI
;
928 /// printInlineAsm - This method formats and prints the specified machine
929 /// instruction that is an inline asm.
930 void AsmPrinter::printInlineAsm(const MachineInstr
*MI
) const {
931 unsigned NumOperands
= MI
->getNumOperands();
933 // Count the number of register definitions.
934 unsigned NumDefs
= 0;
935 for (; MI
->getOperand(NumDefs
).isReg() && MI
->getOperand(NumDefs
).isDef();
937 assert(NumDefs
!= NumOperands
-1 && "No asm string?");
939 assert(MI
->getOperand(NumDefs
).isExternalSymbol() && "No asm string?");
941 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
942 const char *AsmStr
= MI
->getOperand(NumDefs
).getSymbolName();
944 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
945 if (AsmStr
[0] == 0) {
946 O
<< "\n"; // Tab already printed, avoid double indenting next instr.
950 O
<< TAI
->getInlineAsmStart() << "\n\t";
952 // The variant of the current asmprinter.
953 int AsmPrinterVariant
= TAI
->getAssemblerDialect();
955 int CurVariant
= -1; // The number of the {.|.|.} region we are in.
956 const char *LastEmitted
= AsmStr
; // One past the last character emitted.
958 while (*LastEmitted
) {
959 switch (*LastEmitted
) {
961 // Not a special case, emit the string section literally.
962 const char *LiteralEnd
= LastEmitted
+1;
963 while (*LiteralEnd
&& *LiteralEnd
!= '{' && *LiteralEnd
!= '|' &&
964 *LiteralEnd
!= '}' && *LiteralEnd
!= '$' && *LiteralEnd
!= '\n')
966 if (CurVariant
== -1 || CurVariant
== AsmPrinterVariant
)
967 O
.write(LastEmitted
, LiteralEnd
-LastEmitted
);
968 LastEmitted
= LiteralEnd
;
972 ++LastEmitted
; // Consume newline character.
973 O
<< "\n"; // Indent code with newline.
976 ++LastEmitted
; // Consume '$' character.
980 switch (*LastEmitted
) {
981 default: Done
= false; break;
983 if (CurVariant
== -1 || CurVariant
== AsmPrinterVariant
)
985 ++LastEmitted
; // Consume second '$' character.
987 case '(': // $( -> same as GCC's { character.
988 ++LastEmitted
; // Consume '(' character.
989 if (CurVariant
!= -1) {
990 cerr
<< "Nested variants found in inline asm string: '"
994 CurVariant
= 0; // We're in the first variant now.
997 ++LastEmitted
; // consume '|' character.
998 if (CurVariant
== -1) {
999 cerr
<< "Found '|' character outside of variant in inline asm "
1000 << "string: '" << AsmStr
<< "'\n";
1003 ++CurVariant
; // We're in the next variant.
1005 case ')': // $) -> same as GCC's } char.
1006 ++LastEmitted
; // consume ')' character.
1007 if (CurVariant
== -1) {
1008 cerr
<< "Found '}' character outside of variant in inline asm "
1009 << "string: '" << AsmStr
<< "'\n";
1017 bool HasCurlyBraces
= false;
1018 if (*LastEmitted
== '{') { // ${variable}
1019 ++LastEmitted
; // Consume '{' character.
1020 HasCurlyBraces
= true;
1023 const char *IDStart
= LastEmitted
;
1026 long Val
= strtol(IDStart
, &IDEnd
, 10); // We only accept numbers for IDs.
1027 if (!isdigit(*IDStart
) || (Val
== 0 && errno
== EINVAL
)) {
1028 cerr
<< "Bad $ operand number in inline asm string: '"
1032 LastEmitted
= IDEnd
;
1034 char Modifier
[2] = { 0, 0 };
1036 if (HasCurlyBraces
) {
1037 // If we have curly braces, check for a modifier character. This
1038 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1039 if (*LastEmitted
== ':') {
1040 ++LastEmitted
; // Consume ':' character.
1041 if (*LastEmitted
== 0) {
1042 cerr
<< "Bad ${:} expression in inline asm string: '"
1047 Modifier
[0] = *LastEmitted
;
1048 ++LastEmitted
; // Consume modifier character.
1051 if (*LastEmitted
!= '}') {
1052 cerr
<< "Bad ${} expression in inline asm string: '"
1056 ++LastEmitted
; // Consume '}' character.
1059 if ((unsigned)Val
>= NumOperands
-1) {
1060 cerr
<< "Invalid $ operand number in inline asm string: '"
1065 // Okay, we finally have a value number. Ask the target to print this
1067 if (CurVariant
== -1 || CurVariant
== AsmPrinterVariant
) {
1072 // Scan to find the machine operand number for the operand.
1073 for (; Val
; --Val
) {
1074 if (OpNo
>= MI
->getNumOperands()) break;
1075 unsigned OpFlags
= MI
->getOperand(OpNo
).getImmedValue();
1076 OpNo
+= (OpFlags
>> 3) + 1;
1079 if (OpNo
>= MI
->getNumOperands()) {
1082 unsigned OpFlags
= MI
->getOperand(OpNo
).getImmedValue();
1083 ++OpNo
; // Skip over the ID number.
1085 AsmPrinter
*AP
= const_cast<AsmPrinter
*>(this);
1086 if ((OpFlags
& 7) == 4 /*ADDR MODE*/) {
1087 Error
= AP
->PrintAsmMemoryOperand(MI
, OpNo
, AsmPrinterVariant
,
1088 Modifier
[0] ? Modifier
: 0);
1090 Error
= AP
->PrintAsmOperand(MI
, OpNo
, AsmPrinterVariant
,
1091 Modifier
[0] ? Modifier
: 0);
1095 cerr
<< "Invalid operand found in inline asm: '"
1105 O
<< "\n\t" << TAI
->getInlineAsmEnd() << "\n";
1108 /// printLabel - This method prints a local label used by debug and
1109 /// exception handling tables.
1110 void AsmPrinter::printLabel(const MachineInstr
*MI
) const {
1112 << TAI
->getPrivateGlobalPrefix()
1114 << MI
->getOperand(0).getImmedValue()
1118 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1119 /// instruction, using the specified assembler variant. Targets should
1120 /// overried this to format as appropriate.
1121 bool AsmPrinter::PrintAsmOperand(const MachineInstr
*MI
, unsigned OpNo
,
1122 unsigned AsmVariant
, const char *ExtraCode
) {
1123 // Target doesn't support this yet!
1127 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr
*MI
, unsigned OpNo
,
1128 unsigned AsmVariant
,
1129 const char *ExtraCode
) {
1130 // Target doesn't support this yet!
1134 /// printBasicBlockLabel - This method prints the label for the specified
1135 /// MachineBasicBlock
1136 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock
*MBB
,
1138 bool printComment
) const {
1139 O
<< TAI
->getPrivateGlobalPrefix() << "BB" << FunctionNumber
<< "_"
1140 << MBB
->getNumber();
1143 if (printComment
&& MBB
->getBasicBlock())
1144 O
<< '\t' << TAI
->getCommentString() << MBB
->getBasicBlock()->getName();
1147 /// printSetLabel - This method prints a set label for the specified
1148 /// MachineBasicBlock
1149 void AsmPrinter::printSetLabel(unsigned uid
,
1150 const MachineBasicBlock
*MBB
) const {
1151 if (!TAI
->getSetDirective())
1154 O
<< TAI
->getSetDirective() << ' ' << TAI
->getPrivateGlobalPrefix()
1155 << getFunctionNumber() << '_' << uid
<< "_set_" << MBB
->getNumber() << ',';
1156 printBasicBlockLabel(MBB
, false, false);
1157 O
<< '-' << TAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1158 << '_' << uid
<< '\n';
1161 void AsmPrinter::printSetLabel(unsigned uid
, unsigned uid2
,
1162 const MachineBasicBlock
*MBB
) const {
1163 if (!TAI
->getSetDirective())
1166 O
<< TAI
->getSetDirective() << ' ' << TAI
->getPrivateGlobalPrefix()
1167 << getFunctionNumber() << '_' << uid
<< '_' << uid2
1168 << "_set_" << MBB
->getNumber() << ',';
1169 printBasicBlockLabel(MBB
, false, false);
1170 O
<< '-' << TAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1171 << '_' << uid
<< '_' << uid2
<< '\n';
1174 /// printDataDirective - This method prints the asm directive for the
1176 void AsmPrinter::printDataDirective(const Type
*type
) {
1177 const TargetData
*TD
= TM
.getTargetData();
1178 switch (type
->getTypeID()) {
1179 case Type::IntegerTyID
: {
1180 unsigned BitWidth
= cast
<IntegerType
>(type
)->getBitWidth();
1182 O
<< TAI
->getData8bitsDirective();
1183 else if (BitWidth
<= 16)
1184 O
<< TAI
->getData16bitsDirective();
1185 else if (BitWidth
<= 32)
1186 O
<< TAI
->getData32bitsDirective();
1187 else if (BitWidth
<= 64) {
1188 assert(TAI
->getData64bitsDirective() &&
1189 "Target cannot handle 64-bit constant exprs!");
1190 O
<< TAI
->getData64bitsDirective();
1194 case Type::PointerTyID
:
1195 if (TD
->getPointerSize() == 8) {
1196 assert(TAI
->getData64bitsDirective() &&
1197 "Target cannot handle 64-bit pointer exprs!");
1198 O
<< TAI
->getData64bitsDirective();
1200 O
<< TAI
->getData32bitsDirective();
1203 case Type::FloatTyID
: case Type::DoubleTyID
:
1204 assert (0 && "Should have already output floating point constant.");
1206 assert (0 && "Can't handle printing this type of thing");