1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/GCMetadataPrinter.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineJumpTableInfo.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/DwarfWriter.h"
24 #include "llvm/Analysis/DebugInfo.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/Mangler.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34 #include "llvm/Target/TargetData.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/StringExtras.h"
45 static cl::opt<cl::boolOrDefault>
46 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
47 cl::init(cl::BOU_UNSET));
49 char AsmPrinter::ID = 0;
50 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
51 const TargetAsmInfo *T, bool VDef)
52 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
53 TM(tm), TAI(T), TRI(tm.getRegisterInfo()),
55 OutContext(*new MCContext()),
56 OutStreamer(*createAsmStreamer(OutContext, O)),
58 LastMI(0), LastFn(0), Counter(~0U),
59 PrevDLT(0, ~0U, ~0U) {
63 case cl::BOU_UNSET: VerboseAsm = VDef; break;
64 case cl::BOU_TRUE: VerboseAsm = true; break;
65 case cl::BOU_FALSE: VerboseAsm = false; break;
69 AsmPrinter::~AsmPrinter() {
70 for (gcp_iterator I = GCMetadataPrinters.begin(),
71 E = GCMetadataPrinters.end(); I != E; ++I)
78 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
79 return TM.getTargetLowering()->getObjFileLowering();
82 /// SwitchToSection - Switch to the specified section of the executable if we
83 /// are not already in it! If "NS" is null, then this causes us to exit the
84 /// current section and not reenter another one. This is generally used for
87 /// FIXME: Remove support for null sections.
89 void AsmPrinter::SwitchToSection(const MCSection *NS) {
90 // If we're already in this section, we're done.
91 if (CurrentSection == NS) return;
97 NS->PrintSwitchToSection(*TAI, O);
100 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
101 AU.setPreservesAll();
102 MachineFunctionPass::getAnalysisUsage(AU);
103 AU.addRequired<GCModuleInfo>();
106 bool AsmPrinter::doInitialization(Module &M) {
107 // Initialize TargetLoweringObjectFile.
108 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
109 .Initialize(OutContext, TM);
111 Mang = new Mangler(M, TAI->getGlobalPrefix(), TAI->getPrivateGlobalPrefix(),
112 TAI->getLinkerPrivateGlobalPrefix());
114 if (TAI->doesAllowQuotesInName())
115 Mang->setUseQuotes(true);
117 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
118 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
120 if (TAI->hasSingleParameterDotFile()) {
121 /* Very minimal debug info. It is ignored if we emit actual
122 debug info. If we don't, this at helps the user find where
123 a function came from. */
124 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
127 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
128 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
129 MP->beginAssembly(O, *this, *TAI);
131 if (!M.getModuleInlineAsm().empty())
132 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
133 << M.getModuleInlineAsm()
134 << '\n' << TAI->getCommentString()
135 << " End of file scope inline assembly\n";
137 SwitchToSection(0); // Reset back to no section to close off sections.
139 if (TAI->doesSupportDebugInformation() ||
140 TAI->doesSupportExceptionHandling()) {
141 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
143 MMI->AnalyzeModule(M);
144 DW = getAnalysisIfAvailable<DwarfWriter>();
146 DW->BeginModule(&M, MMI, O, this, TAI);
152 bool AsmPrinter::doFinalization(Module &M) {
153 // Emit global variables.
154 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
156 PrintGlobalVariable(I);
158 // Emit final debug information.
159 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
162 // If the target wants to know about weak references, print them all.
163 if (TAI->getWeakRefDirective()) {
164 // FIXME: This is not lazy, it would be nice to only print weak references
165 // to stuff that is actually used. Note that doing so would require targets
166 // to notice uses in operands (due to constant exprs etc). This should
167 // happen with the MC stuff eventually.
170 // Print out module-level global variables here.
171 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
173 if (I->hasExternalWeakLinkage())
174 O << TAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
177 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
178 if (I->hasExternalWeakLinkage())
179 O << TAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
183 if (TAI->getSetDirective()) {
185 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
187 std::string Name = Mang->getMangledName(I);
189 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
190 std::string Target = Mang->getMangledName(GV);
192 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
193 O << "\t.globl\t" << Name << '\n';
194 else if (I->hasWeakLinkage())
195 O << TAI->getWeakRefDirective() << Name << '\n';
196 else if (!I->hasLocalLinkage())
197 llvm_unreachable("Invalid alias linkage");
199 printVisibility(Name, I->getVisibility());
201 O << TAI->getSetDirective() << ' ' << Name << ", " << Target << '\n';
205 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
206 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
207 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
208 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
209 MP->finishAssembly(O, *this, *TAI);
211 // If we don't have any trampolines, then we don't require stack memory
212 // to be executable. Some targets have a directive to declare this.
213 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
214 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
215 if (TAI->getNonexecutableStackDirective())
216 O << TAI->getNonexecutableStackDirective() << '\n';
218 delete Mang; Mang = 0;
221 OutStreamer.Finish();
226 AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) const {
227 assert(MF && "No machine function?");
228 return Mang->getMangledName(MF->getFunction(), ".eh",
229 TAI->is_EHSymbolPrivate());
232 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
233 // What's my mangled name?
234 CurrentFnName = Mang->getMangledName(MF.getFunction());
235 IncrementFunctionNumber();
239 // SectionCPs - Keep track the alignment, constpool entries per Section.
243 SmallVector<unsigned, 4> CPEs;
244 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {};
248 /// EmitConstantPool - Print to the current output stream assembly
249 /// representations of the constants in the constant pool MCP. This is
250 /// used to print out constants which have been "spilled to memory" by
251 /// the code generator.
253 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
254 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
255 if (CP.empty()) return;
257 // Calculate sections for constant pool entries. We collect entries to go into
258 // the same section together to reduce amount of section switch statements.
259 SmallVector<SectionCPs, 4> CPSections;
260 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
261 const MachineConstantPoolEntry &CPE = CP[i];
262 unsigned Align = CPE.getAlignment();
265 switch (CPE.getRelocationInfo()) {
266 default: llvm_unreachable("Unknown section kind");
267 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
269 Kind = SectionKind::getReadOnlyWithRelLocal();
272 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
273 case 4: Kind = SectionKind::getMergeableConst4(); break;
274 case 8: Kind = SectionKind::getMergeableConst8(); break;
275 case 16: Kind = SectionKind::getMergeableConst16();break;
276 default: Kind = SectionKind::getMergeableConst(); break;
280 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
282 // The number of sections are small, just do a linear search from the
283 // last section to the first.
285 unsigned SecIdx = CPSections.size();
286 while (SecIdx != 0) {
287 if (CPSections[--SecIdx].S == S) {
293 SecIdx = CPSections.size();
294 CPSections.push_back(SectionCPs(S, Align));
297 if (Align > CPSections[SecIdx].Alignment)
298 CPSections[SecIdx].Alignment = Align;
299 CPSections[SecIdx].CPEs.push_back(i);
302 // Now print stuff into the calculated sections.
303 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
304 SwitchToSection(CPSections[i].S);
305 EmitAlignment(Log2_32(CPSections[i].Alignment));
308 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
309 unsigned CPI = CPSections[i].CPEs[j];
310 MachineConstantPoolEntry CPE = CP[CPI];
312 // Emit inter-object padding for alignment.
313 unsigned AlignMask = CPE.getAlignment() - 1;
314 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
315 EmitZeros(NewOffset - Offset);
317 const Type *Ty = CPE.getType();
318 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
320 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
321 << CPI << ":\t\t\t\t\t";
323 O << TAI->getCommentString() << ' ';
324 WriteTypeSymbolic(O, CPE.getType(), 0);
327 if (CPE.isMachineConstantPoolEntry())
328 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
330 EmitGlobalConstant(CPE.Val.ConstVal);
335 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
336 /// by the current function to the current output stream.
338 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
339 MachineFunction &MF) {
340 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
341 if (JT.empty()) return;
343 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
345 // Pick the directive to use to print the jump table entries, and switch to
346 // the appropriate section.
347 TargetLowering *LoweringInfo = TM.getTargetLowering();
349 const Function *F = MF.getFunction();
350 bool JTInDiffSection = false;
351 if (F->isWeakForLinker() ||
352 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
353 // In PIC mode, we need to emit the jump table to the same section as the
354 // function body itself, otherwise the label differences won't make sense.
355 // We should also do if the section name is NULL or function is declared in
356 // discardable section.
357 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
359 // Otherwise, drop it in the readonly section.
360 const MCSection *ReadOnlySection =
361 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
362 SwitchToSection(ReadOnlySection);
363 JTInDiffSection = true;
366 EmitAlignment(Log2_32(MJTI->getAlignment()));
368 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
369 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
371 // If this jump table was deleted, ignore it.
372 if (JTBBs.empty()) continue;
374 // For PIC codegen, if possible we want to use the SetDirective to reduce
375 // the number of relocations the assembler will generate for the jump table.
376 // Set directives are all printed before the jump table itself.
377 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
378 if (TAI->getSetDirective() && IsPic)
379 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
380 if (EmittedSets.insert(JTBBs[ii]))
381 printPICJumpTableSetLabel(i, JTBBs[ii]);
383 // On some targets (e.g. darwin) we want to emit two consequtive labels
384 // before each jump table. The first label is never referenced, but tells
385 // the assembler and linker the extents of the jump table object. The
386 // second label is actually referenced by the code.
387 if (JTInDiffSection) {
388 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
389 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
392 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
393 << '_' << i << ":\n";
395 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
396 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
402 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
403 const MachineBasicBlock *MBB,
404 unsigned uid) const {
405 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
407 // Use JumpTableDirective otherwise honor the entry size from the jump table
409 const char *JTEntryDirective = TAI->getJumpTableDirective();
410 bool HadJTEntryDirective = JTEntryDirective != NULL;
411 if (!HadJTEntryDirective) {
412 JTEntryDirective = MJTI->getEntrySize() == 4 ?
413 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
416 O << JTEntryDirective << ' ';
418 // If we have emitted set directives for the jump table entries, print
419 // them rather than the entries themselves. If we're emitting PIC, then
420 // emit the table entries as differences between two text section labels.
421 // If we're emitting non-PIC code, then emit the entries as direct
422 // references to the target basic blocks.
424 if (TAI->getSetDirective()) {
425 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
426 << '_' << uid << "_set_" << MBB->getNumber();
428 printBasicBlockLabel(MBB, false, false, false);
429 // If the arch uses custom Jump Table directives, don't calc relative to
431 if (!HadJTEntryDirective)
432 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
433 << getFunctionNumber() << '_' << uid;
436 printBasicBlockLabel(MBB, false, false, false);
441 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
442 /// special global used by LLVM. If so, emit it and return true, otherwise
443 /// do nothing and return false.
444 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
445 if (GV->getName() == "llvm.used") {
446 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
447 EmitLLVMUsedList(GV->getInitializer());
451 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
452 if (GV->getSection() == "llvm.metadata" ||
453 GV->hasAvailableExternallyLinkage())
456 if (!GV->hasAppendingLinkage()) return false;
458 assert(GV->hasInitializer() && "Not a special LLVM global!");
460 const TargetData *TD = TM.getTargetData();
461 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
462 if (GV->getName() == "llvm.global_ctors") {
463 SwitchToSection(getObjFileLowering().getStaticCtorSection());
464 EmitAlignment(Align, 0);
465 EmitXXStructorList(GV->getInitializer());
469 if (GV->getName() == "llvm.global_dtors") {
470 SwitchToSection(getObjFileLowering().getStaticDtorSection());
471 EmitAlignment(Align, 0);
472 EmitXXStructorList(GV->getInitializer());
479 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
480 /// global in the specified llvm.used list for which emitUsedDirectiveFor
481 /// is true, as being used with this directive.
482 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
483 const char *Directive = TAI->getUsedDirective();
485 // Should be an array of 'i8*'.
486 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
487 if (InitList == 0) return;
489 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
490 const GlobalValue *GV =
491 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
492 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
494 EmitConstantValueOnly(InitList->getOperand(i));
500 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
501 /// function pointers, ignoring the init priority.
502 void AsmPrinter::EmitXXStructorList(Constant *List) {
503 // Should be an array of '{ int, void ()* }' structs. The first value is the
504 // init priority, which we ignore.
505 if (!isa<ConstantArray>(List)) return;
506 ConstantArray *InitList = cast<ConstantArray>(List);
507 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
508 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
509 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
511 if (CS->getOperand(1)->isNullValue())
512 return; // Found a null terminator, exit printing.
513 // Emit the function pointer.
514 EmitGlobalConstant(CS->getOperand(1));
518 /// getGlobalLinkName - Returns the asm/link name of of the specified
519 /// global variable. Should be overridden by each target asm printer to
520 /// generate the appropriate value.
521 const std::string &AsmPrinter::getGlobalLinkName(const GlobalVariable *GV,
522 std::string &LinkName) const {
523 if (isa<Function>(GV)) {
524 LinkName += TAI->getFunctionAddrPrefix();
525 LinkName += Mang->getMangledName(GV);
526 LinkName += TAI->getFunctionAddrSuffix();
528 LinkName += TAI->getGlobalVarAddrPrefix();
529 LinkName += Mang->getMangledName(GV);
530 LinkName += TAI->getGlobalVarAddrSuffix();
536 /// EmitExternalGlobal - Emit the external reference to a global variable.
537 /// Should be overridden if an indirect reference should be used.
538 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
540 O << getGlobalLinkName(GV, GLN);
545 //===----------------------------------------------------------------------===//
546 /// LEB 128 number encoding.
548 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
549 /// representing an unsigned leb128 value.
550 void AsmPrinter::PrintULEB128(unsigned Value) const {
553 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
555 if (Value) Byte |= 0x80;
556 O << "0x" << utohex_buffer(Byte, Buffer+20);
557 if (Value) O << ", ";
561 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
562 /// representing a signed leb128 value.
563 void AsmPrinter::PrintSLEB128(int Value) const {
564 int Sign = Value >> (8 * sizeof(Value) - 1);
569 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
571 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
572 if (IsMore) Byte |= 0x80;
573 O << "0x" << utohex_buffer(Byte, Buffer+20);
574 if (IsMore) O << ", ";
578 //===--------------------------------------------------------------------===//
579 // Emission and print routines
582 /// PrintHex - Print a value as a hexidecimal value.
584 void AsmPrinter::PrintHex(int Value) const {
586 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
589 /// EOL - Print a newline character to asm stream. If a comment is present
590 /// then it will be printed first. Comments should not contain '\n'.
591 void AsmPrinter::EOL() const {
595 void AsmPrinter::EOL(const std::string &Comment) const {
596 if (VerboseAsm && !Comment.empty()) {
598 << TAI->getCommentString()
605 void AsmPrinter::EOL(const char* Comment) const {
606 if (VerboseAsm && *Comment) {
608 << TAI->getCommentString()
615 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
616 /// unsigned leb128 value.
617 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
618 if (TAI->hasLEB128()) {
622 O << TAI->getData8bitsDirective();
627 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
628 /// signed leb128 value.
629 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
630 if (TAI->hasLEB128()) {
634 O << TAI->getData8bitsDirective();
639 /// EmitInt8 - Emit a byte directive and value.
641 void AsmPrinter::EmitInt8(int Value) const {
642 O << TAI->getData8bitsDirective();
643 PrintHex(Value & 0xFF);
646 /// EmitInt16 - Emit a short directive and value.
648 void AsmPrinter::EmitInt16(int Value) const {
649 O << TAI->getData16bitsDirective();
650 PrintHex(Value & 0xFFFF);
653 /// EmitInt32 - Emit a long directive and value.
655 void AsmPrinter::EmitInt32(int Value) const {
656 O << TAI->getData32bitsDirective();
660 /// EmitInt64 - Emit a long long directive and value.
662 void AsmPrinter::EmitInt64(uint64_t Value) const {
663 if (TAI->getData64bitsDirective()) {
664 O << TAI->getData64bitsDirective();
667 if (TM.getTargetData()->isBigEndian()) {
668 EmitInt32(unsigned(Value >> 32)); O << '\n';
669 EmitInt32(unsigned(Value));
671 EmitInt32(unsigned(Value)); O << '\n';
672 EmitInt32(unsigned(Value >> 32));
677 /// toOctal - Convert the low order bits of X into an octal digit.
679 static inline char toOctal(int X) {
683 /// printStringChar - Print a char, escaped if necessary.
685 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
688 } else if (C == '\\') {
690 } else if (isprint((unsigned char)C)) {
694 case '\b': O << "\\b"; break;
695 case '\f': O << "\\f"; break;
696 case '\n': O << "\\n"; break;
697 case '\r': O << "\\r"; break;
698 case '\t': O << "\\t"; break;
701 O << toOctal(C >> 6);
702 O << toOctal(C >> 3);
703 O << toOctal(C >> 0);
709 /// EmitString - Emit a string with quotes and a null terminator.
710 /// Special characters are emitted properly.
711 /// \literal (Eg. '\t') \endliteral
712 void AsmPrinter::EmitString(const std::string &String) const {
713 EmitString(String.c_str(), String.size());
716 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
717 const char* AscizDirective = TAI->getAscizDirective();
721 O << TAI->getAsciiDirective();
723 for (unsigned i = 0; i < Size; ++i)
724 printStringChar(O, String[i]);
732 /// EmitFile - Emit a .file directive.
733 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
734 O << "\t.file\t" << Number << " \"";
735 for (unsigned i = 0, N = Name.size(); i < N; ++i)
736 printStringChar(O, Name[i]);
741 //===----------------------------------------------------------------------===//
743 // EmitAlignment - Emit an alignment directive to the specified power of
744 // two boundary. For example, if you pass in 3 here, you will get an 8
745 // byte alignment. If a global value is specified, and if that global has
746 // an explicit alignment requested, it will unconditionally override the
747 // alignment request. However, if ForcedAlignBits is specified, this value
748 // has final say: the ultimate alignment will be the max of ForcedAlignBits
749 // and the alignment computed with NumBits and the global.
753 // if (GV && GV->hasalignment) Align = GV->getalignment();
754 // Align = std::max(Align, ForcedAlignBits);
756 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
757 unsigned ForcedAlignBits,
758 bool UseFillExpr) const {
759 if (GV && GV->getAlignment())
760 NumBits = Log2_32(GV->getAlignment());
761 NumBits = std::max(NumBits, ForcedAlignBits);
763 if (NumBits == 0) return; // No need to emit alignment.
764 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
765 O << TAI->getAlignDirective() << NumBits;
767 if (CurrentSection && CurrentSection->getKind().isText())
768 if (unsigned FillValue = TAI->getTextAlignFillValue()) {
775 /// EmitZeros - Emit a block of zeros.
777 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
779 if (TAI->getZeroDirective()) {
780 O << TAI->getZeroDirective() << NumZeros;
781 if (TAI->getZeroDirectiveSuffix())
782 O << TAI->getZeroDirectiveSuffix();
785 for (; NumZeros; --NumZeros)
786 O << TAI->getData8bitsDirective(AddrSpace) << "0\n";
791 // Print out the specified constant, without a storage class. Only the
792 // constants valid in constant expressions can occur here.
793 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
794 if (CV->isNullValue() || isa<UndefValue>(CV))
796 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
797 O << CI->getZExtValue();
798 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
799 // This is a constant address for a global variable or function. Use the
800 // name of the variable or function as the address value, possibly
801 // decorating it with GlobalVarAddrPrefix/Suffix or
802 // FunctionAddrPrefix/Suffix (these all default to "" )
803 if (isa<Function>(GV)) {
804 O << TAI->getFunctionAddrPrefix()
805 << Mang->getMangledName(GV)
806 << TAI->getFunctionAddrSuffix();
808 O << TAI->getGlobalVarAddrPrefix()
809 << Mang->getMangledName(GV)
810 << TAI->getGlobalVarAddrSuffix();
812 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
813 const TargetData *TD = TM.getTargetData();
814 unsigned Opcode = CE->getOpcode();
816 case Instruction::Trunc:
817 case Instruction::ZExt:
818 case Instruction::SExt:
819 case Instruction::FPTrunc:
820 case Instruction::FPExt:
821 case Instruction::UIToFP:
822 case Instruction::SIToFP:
823 case Instruction::FPToUI:
824 case Instruction::FPToSI:
825 llvm_unreachable("FIXME: Don't support this constant cast expr");
826 case Instruction::GetElementPtr: {
827 // generate a symbolic expression for the byte address
828 const Constant *ptrVal = CE->getOperand(0);
829 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
830 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
832 // Truncate/sext the offset to the pointer size.
833 if (TD->getPointerSizeInBits() != 64) {
834 int SExtAmount = 64-TD->getPointerSizeInBits();
835 Offset = (Offset << SExtAmount) >> SExtAmount;
840 EmitConstantValueOnly(ptrVal);
842 O << ") + " << Offset;
844 O << ") - " << -Offset;
846 EmitConstantValueOnly(ptrVal);
850 case Instruction::BitCast:
851 return EmitConstantValueOnly(CE->getOperand(0));
853 case Instruction::IntToPtr: {
854 // Handle casts to pointers by changing them into casts to the appropriate
855 // integer type. This promotes constant folding and simplifies this code.
856 Constant *Op = CE->getOperand(0);
857 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
858 return EmitConstantValueOnly(Op);
862 case Instruction::PtrToInt: {
863 // Support only foldable casts to/from pointers that can be eliminated by
864 // changing the pointer to the appropriately sized integer type.
865 Constant *Op = CE->getOperand(0);
866 const Type *Ty = CE->getType();
868 // We can emit the pointer value into this slot if the slot is an
869 // integer slot greater or equal to the size of the pointer.
870 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
871 return EmitConstantValueOnly(Op);
874 EmitConstantValueOnly(Op);
876 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
879 ptrMask.toStringUnsigned(S);
880 O << ") & " << S.c_str() << ')';
883 case Instruction::Add:
884 case Instruction::Sub:
885 case Instruction::And:
886 case Instruction::Or:
887 case Instruction::Xor:
889 EmitConstantValueOnly(CE->getOperand(0));
892 case Instruction::Add:
895 case Instruction::Sub:
898 case Instruction::And:
901 case Instruction::Or:
904 case Instruction::Xor:
911 EmitConstantValueOnly(CE->getOperand(1));
915 llvm_unreachable("Unsupported operator!");
918 llvm_unreachable("Unknown constant value!");
922 /// printAsCString - Print the specified array as a C compatible string, only if
923 /// the predicate isString is true.
925 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
927 assert(CVA->isString() && "Array is not string compatible!");
930 for (unsigned i = 0; i != LastElt; ++i) {
932 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
933 printStringChar(O, C);
938 /// EmitString - Emit a zero-byte-terminated string constant.
940 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
941 unsigned NumElts = CVA->getNumOperands();
942 if (TAI->getAscizDirective() && NumElts &&
943 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
944 O << TAI->getAscizDirective();
945 printAsCString(O, CVA, NumElts-1);
947 O << TAI->getAsciiDirective();
948 printAsCString(O, CVA, NumElts);
953 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
954 unsigned AddrSpace) {
955 if (CVA->isString()) {
957 } else { // Not a string. Print the values in successive locations
958 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
959 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
963 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
964 const VectorType *PTy = CP->getType();
966 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
967 EmitGlobalConstant(CP->getOperand(I));
970 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
971 unsigned AddrSpace) {
972 // Print the fields in successive locations. Pad to align if needed!
973 const TargetData *TD = TM.getTargetData();
974 unsigned Size = TD->getTypeAllocSize(CVS->getType());
975 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
976 uint64_t sizeSoFar = 0;
977 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
978 const Constant* field = CVS->getOperand(i);
980 // Check if padding is needed and insert one or more 0s.
981 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
982 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
983 - cvsLayout->getElementOffset(i)) - fieldSize;
984 sizeSoFar += fieldSize + padSize;
986 // Now print the actual field value.
987 EmitGlobalConstant(field, AddrSpace);
989 // Insert padding - this may include padding to increase the size of the
990 // current field up to the ABI size (if the struct is not packed) as well
991 // as padding to ensure that the next field starts at the right offset.
992 EmitZeros(padSize, AddrSpace);
994 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
995 "Layout of constant struct may be incorrect!");
998 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
999 unsigned AddrSpace) {
1000 // FP Constants are printed as integer constants to avoid losing
1002 const TargetData *TD = TM.getTargetData();
1003 if (CFP->getType() == Type::DoubleTy) {
1004 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1005 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1006 if (TAI->getData64bitsDirective(AddrSpace)) {
1007 O << TAI->getData64bitsDirective(AddrSpace) << i;
1009 O << '\t' << TAI->getCommentString() << " double value: " << Val;
1011 } else if (TD->isBigEndian()) {
1012 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1014 O << '\t' << TAI->getCommentString()
1015 << " double most significant word " << Val;
1017 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1019 O << '\t' << TAI->getCommentString()
1020 << " double least significant word " << Val;
1023 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1025 O << '\t' << TAI->getCommentString()
1026 << " double least significant word " << Val;
1028 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1030 O << '\t' << TAI->getCommentString()
1031 << " double most significant word " << Val;
1035 } else if (CFP->getType() == Type::FloatTy) {
1036 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1037 O << TAI->getData32bitsDirective(AddrSpace)
1038 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1040 O << '\t' << TAI->getCommentString() << " float " << Val;
1043 } else if (CFP->getType() == Type::X86_FP80Ty) {
1044 // all long double variants are printed as hex
1045 // api needed to prevent premature destruction
1046 APInt api = CFP->getValueAPF().bitcastToAPInt();
1047 const uint64_t *p = api.getRawData();
1048 // Convert to double so we can print the approximate val as a comment.
1049 APFloat DoubleVal = CFP->getValueAPF();
1051 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1053 if (TD->isBigEndian()) {
1054 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1056 O << '\t' << TAI->getCommentString()
1057 << " long double most significant halfword of ~"
1058 << DoubleVal.convertToDouble();
1060 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1062 O << '\t' << TAI->getCommentString() << " long double next halfword";
1064 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1066 O << '\t' << TAI->getCommentString() << " long double next halfword";
1068 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1070 O << '\t' << TAI->getCommentString() << " long double next halfword";
1072 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1074 O << '\t' << TAI->getCommentString()
1075 << " long double least significant halfword";
1078 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1080 O << '\t' << TAI->getCommentString()
1081 << " long double least significant halfword of ~"
1082 << DoubleVal.convertToDouble();
1084 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1086 O << '\t' << TAI->getCommentString()
1087 << " long double next halfword";
1089 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1091 O << '\t' << TAI->getCommentString()
1092 << " long double next halfword";
1094 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1096 O << '\t' << TAI->getCommentString()
1097 << " long double next halfword";
1099 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1101 O << '\t' << TAI->getCommentString()
1102 << " long double most significant halfword";
1105 EmitZeros(TD->getTypeAllocSize(Type::X86_FP80Ty) -
1106 TD->getTypeStoreSize(Type::X86_FP80Ty), AddrSpace);
1108 } else if (CFP->getType() == Type::PPC_FP128Ty) {
1109 // all long double variants are printed as hex
1110 // api needed to prevent premature destruction
1111 APInt api = CFP->getValueAPF().bitcastToAPInt();
1112 const uint64_t *p = api.getRawData();
1113 if (TD->isBigEndian()) {
1114 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1116 O << '\t' << TAI->getCommentString()
1117 << " long double most significant word";
1119 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1121 O << '\t' << TAI->getCommentString()
1122 << " long double next word";
1124 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1126 O << '\t' << TAI->getCommentString()
1127 << " long double next word";
1129 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1131 O << '\t' << TAI->getCommentString()
1132 << " long double least significant word";
1135 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1137 O << '\t' << TAI->getCommentString()
1138 << " long double least significant word";
1140 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1142 O << '\t' << TAI->getCommentString()
1143 << " long double next word";
1145 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1147 O << '\t' << TAI->getCommentString()
1148 << " long double next word";
1150 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1152 O << '\t' << TAI->getCommentString()
1153 << " long double most significant word";
1157 } else llvm_unreachable("Floating point constant type not handled");
1160 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1161 unsigned AddrSpace) {
1162 const TargetData *TD = TM.getTargetData();
1163 unsigned BitWidth = CI->getBitWidth();
1164 assert(isPowerOf2_32(BitWidth) &&
1165 "Non-power-of-2-sized integers not handled!");
1167 // We don't expect assemblers to support integer data directives
1168 // for more than 64 bits, so we emit the data in at most 64-bit
1169 // quantities at a time.
1170 const uint64_t *RawData = CI->getValue().getRawData();
1171 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1173 if (TD->isBigEndian())
1174 Val = RawData[e - i - 1];
1178 if (TAI->getData64bitsDirective(AddrSpace))
1179 O << TAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1180 else if (TD->isBigEndian()) {
1181 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1183 O << '\t' << TAI->getCommentString()
1184 << " Double-word most significant word " << Val;
1186 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1188 O << '\t' << TAI->getCommentString()
1189 << " Double-word least significant word " << Val;
1192 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1194 O << '\t' << TAI->getCommentString()
1195 << " Double-word least significant word " << Val;
1197 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1199 O << '\t' << TAI->getCommentString()
1200 << " Double-word most significant word " << Val;
1206 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1207 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1208 const TargetData *TD = TM.getTargetData();
1209 const Type *type = CV->getType();
1210 unsigned Size = TD->getTypeAllocSize(type);
1212 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1213 EmitZeros(Size, AddrSpace);
1215 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1216 EmitGlobalConstantArray(CVA , AddrSpace);
1218 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1219 EmitGlobalConstantStruct(CVS, AddrSpace);
1221 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1222 EmitGlobalConstantFP(CFP, AddrSpace);
1224 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1225 // Small integers are handled below; large integers are handled here.
1227 EmitGlobalConstantLargeInt(CI, AddrSpace);
1230 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1231 EmitGlobalConstantVector(CP);
1235 printDataDirective(type, AddrSpace);
1236 EmitConstantValueOnly(CV);
1238 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1240 CI->getValue().toStringUnsigned(S, 16);
1241 O << "\t\t\t" << TAI->getCommentString() << " 0x" << S.c_str();
1247 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1248 // Target doesn't support this yet!
1249 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1252 /// PrintSpecial - Print information related to the specified machine instr
1253 /// that is independent of the operand, and may be independent of the instr
1254 /// itself. This can be useful for portably encoding the comment character
1255 /// or other bits of target-specific knowledge into the asmstrings. The
1256 /// syntax used is ${:comment}. Targets can override this to add support
1257 /// for their own strange codes.
1258 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1259 if (!strcmp(Code, "private")) {
1260 O << TAI->getPrivateGlobalPrefix();
1261 } else if (!strcmp(Code, "comment")) {
1263 O << TAI->getCommentString();
1264 } else if (!strcmp(Code, "uid")) {
1265 // Comparing the address of MI isn't sufficient, because machineinstrs may
1266 // be allocated to the same address across functions.
1267 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1269 // If this is a new LastFn instruction, bump the counter.
1270 if (LastMI != MI || LastFn != ThisF) {
1278 raw_string_ostream Msg(msg);
1279 Msg << "Unknown special formatter '" << Code
1280 << "' for machine instr: " << *MI;
1281 llvm_report_error(Msg.str());
1285 /// processDebugLoc - Processes the debug information of each machine
1286 /// instruction's DebugLoc.
1287 void AsmPrinter::processDebugLoc(DebugLoc DL) {
1291 if (TAI->doesSupportDebugInformation() && DW->ShouldEmitDwarfDebug()) {
1292 if (!DL.isUnknown()) {
1293 DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1295 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT)
1296 printLabel(DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1297 DICompileUnit(CurDLT.CompileUnit)));
1304 /// printInlineAsm - This method formats and prints the specified machine
1305 /// instruction that is an inline asm.
1306 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1307 unsigned NumOperands = MI->getNumOperands();
1309 // Count the number of register definitions.
1310 unsigned NumDefs = 0;
1311 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1313 assert(NumDefs != NumOperands-1 && "No asm string?");
1315 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1317 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1318 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1320 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1321 // These are useful to see where empty asm's wound up.
1322 if (AsmStr[0] == 0) {
1323 O << TAI->getInlineAsmStart() << "\n\t" << TAI->getInlineAsmEnd() << '\n';
1327 O << TAI->getInlineAsmStart() << "\n\t";
1329 // The variant of the current asmprinter.
1330 int AsmPrinterVariant = TAI->getAssemblerDialect();
1332 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1333 const char *LastEmitted = AsmStr; // One past the last character emitted.
1335 while (*LastEmitted) {
1336 switch (*LastEmitted) {
1338 // Not a special case, emit the string section literally.
1339 const char *LiteralEnd = LastEmitted+1;
1340 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1341 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1343 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1344 O.write(LastEmitted, LiteralEnd-LastEmitted);
1345 LastEmitted = LiteralEnd;
1349 ++LastEmitted; // Consume newline character.
1350 O << '\n'; // Indent code with newline.
1353 ++LastEmitted; // Consume '$' character.
1357 switch (*LastEmitted) {
1358 default: Done = false; break;
1359 case '$': // $$ -> $
1360 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1362 ++LastEmitted; // Consume second '$' character.
1364 case '(': // $( -> same as GCC's { character.
1365 ++LastEmitted; // Consume '(' character.
1366 if (CurVariant != -1) {
1367 llvm_report_error("Nested variants found in inline asm string: '"
1368 + std::string(AsmStr) + "'");
1370 CurVariant = 0; // We're in the first variant now.
1373 ++LastEmitted; // consume '|' character.
1374 if (CurVariant == -1)
1375 O << '|'; // this is gcc's behavior for | outside a variant
1377 ++CurVariant; // We're in the next variant.
1379 case ')': // $) -> same as GCC's } char.
1380 ++LastEmitted; // consume ')' character.
1381 if (CurVariant == -1)
1382 O << '}'; // this is gcc's behavior for } outside a variant
1389 bool HasCurlyBraces = false;
1390 if (*LastEmitted == '{') { // ${variable}
1391 ++LastEmitted; // Consume '{' character.
1392 HasCurlyBraces = true;
1395 // If we have ${:foo}, then this is not a real operand reference, it is a
1396 // "magic" string reference, just like in .td files. Arrange to call
1398 if (HasCurlyBraces && *LastEmitted == ':') {
1400 const char *StrStart = LastEmitted;
1401 const char *StrEnd = strchr(StrStart, '}');
1403 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1404 + std::string(AsmStr) + "'");
1407 std::string Val(StrStart, StrEnd);
1408 PrintSpecial(MI, Val.c_str());
1409 LastEmitted = StrEnd+1;
1413 const char *IDStart = LastEmitted;
1416 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1417 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1418 llvm_report_error("Bad $ operand number in inline asm string: '"
1419 + std::string(AsmStr) + "'");
1421 LastEmitted = IDEnd;
1423 char Modifier[2] = { 0, 0 };
1425 if (HasCurlyBraces) {
1426 // If we have curly braces, check for a modifier character. This
1427 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1428 if (*LastEmitted == ':') {
1429 ++LastEmitted; // Consume ':' character.
1430 if (*LastEmitted == 0) {
1431 llvm_report_error("Bad ${:} expression in inline asm string: '"
1432 + std::string(AsmStr) + "'");
1435 Modifier[0] = *LastEmitted;
1436 ++LastEmitted; // Consume modifier character.
1439 if (*LastEmitted != '}') {
1440 llvm_report_error("Bad ${} expression in inline asm string: '"
1441 + std::string(AsmStr) + "'");
1443 ++LastEmitted; // Consume '}' character.
1446 if ((unsigned)Val >= NumOperands-1) {
1447 llvm_report_error("Invalid $ operand number in inline asm string: '"
1448 + std::string(AsmStr) + "'");
1451 // Okay, we finally have a value number. Ask the target to print this
1453 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1458 // Scan to find the machine operand number for the operand.
1459 for (; Val; --Val) {
1460 if (OpNo >= MI->getNumOperands()) break;
1461 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1462 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1465 if (OpNo >= MI->getNumOperands()) {
1468 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1469 ++OpNo; // Skip over the ID number.
1471 if (Modifier[0]=='l') // labels are target independent
1472 printBasicBlockLabel(MI->getOperand(OpNo).getMBB(),
1473 false, false, false);
1475 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1476 if ((OpFlags & 7) == 4) {
1477 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1478 Modifier[0] ? Modifier : 0);
1480 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1481 Modifier[0] ? Modifier : 0);
1487 raw_string_ostream Msg(msg);
1488 Msg << "Invalid operand found in inline asm: '"
1491 llvm_report_error(Msg.str());
1498 O << "\n\t" << TAI->getInlineAsmEnd() << '\n';
1501 /// printImplicitDef - This method prints the specified machine instruction
1502 /// that is an implicit def.
1503 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1505 O << '\t' << TAI->getCommentString() << " implicit-def: "
1506 << TRI->getAsmName(MI->getOperand(0).getReg()) << '\n';
1509 /// printLabel - This method prints a local label used by debug and
1510 /// exception handling tables.
1511 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1512 printLabel(MI->getOperand(0).getImm());
1515 void AsmPrinter::printLabel(unsigned Id) const {
1516 O << TAI->getPrivateGlobalPrefix() << "label" << Id << ":\n";
1519 /// printDeclare - This method prints a local variable declaration used by
1521 /// FIXME: It doesn't really print anything rather it inserts a DebugVariable
1522 /// entry into dwarf table.
1523 void AsmPrinter::printDeclare(const MachineInstr *MI) const {
1524 unsigned FI = MI->getOperand(0).getIndex();
1525 GlobalValue *GV = MI->getOperand(1).getGlobal();
1526 DW->RecordVariable(cast<GlobalVariable>(GV), FI, MI);
1529 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1530 /// instruction, using the specified assembler variant. Targets should
1531 /// overried this to format as appropriate.
1532 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1533 unsigned AsmVariant, const char *ExtraCode) {
1534 // Target doesn't support this yet!
1538 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1539 unsigned AsmVariant,
1540 const char *ExtraCode) {
1541 // Target doesn't support this yet!
1545 /// printBasicBlockLabel - This method prints the label for the specified
1546 /// MachineBasicBlock
1547 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1550 bool printComment) const {
1552 unsigned Align = MBB->getAlignment();
1554 EmitAlignment(Log2_32(Align));
1557 O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << '_'
1558 << MBB->getNumber();
1561 if (printComment && MBB->getBasicBlock())
1562 O << '\t' << TAI->getCommentString() << ' '
1563 << MBB->getBasicBlock()->getNameStr();
1566 /// printPICJumpTableSetLabel - This method prints a set label for the
1567 /// specified MachineBasicBlock for a jumptable entry.
1568 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1569 const MachineBasicBlock *MBB) const {
1570 if (!TAI->getSetDirective())
1573 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1574 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1575 printBasicBlockLabel(MBB, false, false, false);
1576 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1577 << '_' << uid << '\n';
1580 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1581 const MachineBasicBlock *MBB) const {
1582 if (!TAI->getSetDirective())
1585 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1586 << getFunctionNumber() << '_' << uid << '_' << uid2
1587 << "_set_" << MBB->getNumber() << ',';
1588 printBasicBlockLabel(MBB, false, false, false);
1589 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1590 << '_' << uid << '_' << uid2 << '\n';
1593 /// printDataDirective - This method prints the asm directive for the
1595 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1596 const TargetData *TD = TM.getTargetData();
1597 switch (type->getTypeID()) {
1598 case Type::FloatTyID: case Type::DoubleTyID:
1599 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1600 assert(0 && "Should have already output floating point constant.");
1602 assert(0 && "Can't handle printing this type of thing");
1603 case Type::IntegerTyID: {
1604 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1606 O << TAI->getData8bitsDirective(AddrSpace);
1607 else if (BitWidth <= 16)
1608 O << TAI->getData16bitsDirective(AddrSpace);
1609 else if (BitWidth <= 32)
1610 O << TAI->getData32bitsDirective(AddrSpace);
1611 else if (BitWidth <= 64) {
1612 assert(TAI->getData64bitsDirective(AddrSpace) &&
1613 "Target cannot handle 64-bit constant exprs!");
1614 O << TAI->getData64bitsDirective(AddrSpace);
1616 llvm_unreachable("Target cannot handle given data directive width!");
1620 case Type::PointerTyID:
1621 if (TD->getPointerSize() == 8) {
1622 assert(TAI->getData64bitsDirective(AddrSpace) &&
1623 "Target cannot handle 64-bit pointer exprs!");
1624 O << TAI->getData64bitsDirective(AddrSpace);
1625 } else if (TD->getPointerSize() == 2) {
1626 O << TAI->getData16bitsDirective(AddrSpace);
1627 } else if (TD->getPointerSize() == 1) {
1628 O << TAI->getData8bitsDirective(AddrSpace);
1630 O << TAI->getData32bitsDirective(AddrSpace);
1636 void AsmPrinter::printVisibility(const std::string& Name,
1637 unsigned Visibility) const {
1638 if (Visibility == GlobalValue::HiddenVisibility) {
1639 if (const char *Directive = TAI->getHiddenDirective())
1640 O << Directive << Name << '\n';
1641 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1642 if (const char *Directive = TAI->getProtectedDirective())
1643 O << Directive << Name << '\n';
1647 void AsmPrinter::printOffset(int64_t Offset) const {
1650 else if (Offset < 0)
1654 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1655 if (!S->usesMetadata())
1658 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1659 if (GCPI != GCMetadataPrinters.end())
1660 return GCPI->second;
1662 const char *Name = S->getName().c_str();
1664 for (GCMetadataPrinterRegistry::iterator
1665 I = GCMetadataPrinterRegistry::begin(),
1666 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1667 if (strcmp(Name, I->getName()) == 0) {
1668 GCMetadataPrinter *GMP = I->instantiate();
1670 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1674 cerr << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1675 llvm_unreachable(0);
1678 /// EmitComments - Pretty-print comments for instructions
1679 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1681 MI.getDebugLoc().isUnknown())
1684 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1686 // Print source line info
1687 O.PadToColumn(TAI->getCommentColumn(), 1);
1688 O << TAI->getCommentString() << " SrcLine ";
1689 if (DLT.CompileUnit->hasInitializer()) {
1690 Constant *Name = DLT.CompileUnit->getInitializer();
1691 if (ConstantArray *NameString = dyn_cast<ConstantArray>(Name))
1692 if (NameString->isString())
1693 O << NameString->getAsString() << " ";
1697 O << ":" << DLT.Col;
1700 /// EmitComments - Pretty-print comments for instructions
1701 void AsmPrinter::EmitComments(const MCInst &MI) const
1704 if (!MI.getDebugLoc().isUnknown()) {
1705 DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1707 // Print source line info
1708 O.PadToColumn(TAI->getCommentColumn(), 1);
1709 O << TAI->getCommentString() << " SrcLine ";
1710 if (DLT.CompileUnit->hasInitializer()) {
1711 Constant *Name = DLT.CompileUnit->getInitializer();
1712 if (ConstantArray *NameString = dyn_cast<ConstantArray>(Name))
1713 if (NameString->isString()) {
1714 O << NameString->getAsString() << " ";
1719 O << ":" << DLT.Col;