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/DwarfWriter.h"
20 #include "llvm/CodeGen/GCMetadataPrinter.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/Analysis/DebugInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCInst.h"
30 #include "llvm/MC/MCSection.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/FormattedStream.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/Target/Mangler.h"
38 #include "llvm/Target/TargetData.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/ADT/SmallPtrSet.h"
45 #include "llvm/ADT/SmallString.h"
49 static cl::opt<cl::boolOrDefault>
50 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
51 cl::init(cl::BOU_UNSET));
53 char AsmPrinter::ID = 0;
54 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
55 const MCAsmInfo *T, bool VDef)
56 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
57 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
59 OutContext(*new MCContext()),
60 // FIXME: Pass instprinter to streamer.
61 OutStreamer(*createAsmStreamer(OutContext, O, *T,
62 TM.getTargetData()->isLittleEndian(), 0)),
64 LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
67 case cl::BOU_UNSET: VerboseAsm = VDef; break;
68 case cl::BOU_TRUE: VerboseAsm = true; break;
69 case cl::BOU_FALSE: VerboseAsm = false; break;
73 AsmPrinter::~AsmPrinter() {
74 for (gcp_iterator I = GCMetadataPrinters.begin(),
75 E = GCMetadataPrinters.end(); I != E; ++I)
82 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
83 return TM.getTargetLowering()->getObjFileLowering();
86 /// getCurrentSection() - Return the current section we are emitting to.
87 const MCSection *AsmPrinter::getCurrentSection() const {
88 return OutStreamer.getCurrentSection();
92 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
94 MachineFunctionPass::getAnalysisUsage(AU);
95 AU.addRequired<GCModuleInfo>();
97 AU.addRequired<MachineLoopInfo>();
100 bool AsmPrinter::doInitialization(Module &M) {
101 // Initialize TargetLoweringObjectFile.
102 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
103 .Initialize(OutContext, TM);
105 Mang = new Mangler(*MAI);
107 // Allow the target to emit any magic that it wants at the start of the file.
108 EmitStartOfAsmFile(M);
110 if (MAI->hasSingleParameterDotFile()) {
111 /* Very minimal debug info. It is ignored if we emit actual
112 debug info. If we don't, this at least helps the user find where
113 a function came from. */
114 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
117 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
118 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
119 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
120 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
121 MP->beginAssembly(O, *this, *MAI);
123 if (!M.getModuleInlineAsm().empty())
124 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
125 << M.getModuleInlineAsm()
126 << '\n' << MAI->getCommentString()
127 << " End of file scope inline assembly\n";
129 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
131 MMI->AnalyzeModule(M);
132 DW = getAnalysisIfAvailable<DwarfWriter>();
134 DW->BeginModule(&M, MMI, O, this, MAI);
139 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
140 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
141 if (!GV->hasInitializer()) // External globals require no code.
144 // Check to see if this is a special global used by LLVM, if so, emit it.
145 if (EmitSpecialLLVMGlobal(GV))
148 MCSymbol *GVSym = GetGlobalValueSymbol(GV);
149 printVisibility(GVSym, GV->getVisibility());
151 if (MAI->hasDotTypeDotSizeDirective()) {
152 O << "\t.type\t" << *GVSym;
153 if (MAI->getCommentString()[0] != '@')
159 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
161 const TargetData *TD = TM.getTargetData();
162 unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
163 unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
165 // Handle common and BSS local symbols (.lcomm).
166 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
167 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
170 O.PadToColumn(MAI->getCommentColumn());
171 O << MAI->getCommentString() << ' ';
172 WriteAsOperand(O, GV, /*PrintType=*/false, GV->getParent());
176 // Handle common symbols.
177 if (GVKind.isCommon()) {
179 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
183 // Handle local BSS symbols.
184 if (MAI->hasMachoZeroFillDirective()) {
185 const MCSection *TheSection =
186 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
187 // .zerofill __DATA, __bss, _foo, 400, 5
188 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
192 if (const char *LComm = MAI->getLCOMMDirective()) {
194 O << LComm << *GVSym << ',' << Size;
200 O << "\t.local\t" << *GVSym << '\n';
202 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
206 const MCSection *TheSection =
207 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
209 // Handle the zerofill directive on darwin, which is a special form of BSS
211 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
213 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
214 // .zerofill __DATA, __common, _foo, 400, 5
215 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
219 OutStreamer.SwitchSection(TheSection);
221 // TODO: Factor into an 'emit linkage' thing that is shared with function
223 switch (GV->getLinkage()) {
224 case GlobalValue::CommonLinkage:
225 case GlobalValue::LinkOnceAnyLinkage:
226 case GlobalValue::LinkOnceODRLinkage:
227 case GlobalValue::WeakAnyLinkage:
228 case GlobalValue::WeakODRLinkage:
229 case GlobalValue::LinkerPrivateLinkage:
230 if (MAI->getWeakDefDirective() != 0) {
232 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
233 // .weak_definition _foo
234 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::WeakDefinition);
235 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
237 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
238 // .linkonce same_size
242 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Weak);
245 case GlobalValue::DLLExportLinkage:
246 case GlobalValue::AppendingLinkage:
247 // FIXME: appending linkage variables should go into a section of
248 // their name or something. For now, just emit them as external.
249 case GlobalValue::ExternalLinkage:
250 // If external or appending, declare as a global symbol.
252 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
254 case GlobalValue::PrivateLinkage:
255 case GlobalValue::InternalLinkage:
258 llvm_unreachable("Unknown linkage type!");
261 EmitAlignment(AlignLog, GV);
263 O.PadToColumn(MAI->getCommentColumn());
264 O << MAI->getCommentString() << ' ';
265 WriteAsOperand(O, GV, /*PrintType=*/false, GV->getParent());
268 OutStreamer.EmitLabel(GVSym);
270 EmitGlobalConstant(GV->getInitializer());
272 if (MAI->hasDotTypeDotSizeDirective())
273 O << "\t.size\t" << *GVSym << ", " << Size << '\n';
277 bool AsmPrinter::doFinalization(Module &M) {
278 // Emit global variables.
279 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
281 EmitGlobalVariable(I);
283 // Emit final debug information.
284 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
287 // If the target wants to know about weak references, print them all.
288 if (MAI->getWeakRefDirective()) {
289 // FIXME: This is not lazy, it would be nice to only print weak references
290 // to stuff that is actually used. Note that doing so would require targets
291 // to notice uses in operands (due to constant exprs etc). This should
292 // happen with the MC stuff eventually.
294 // Print out module-level global variables here.
295 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
297 if (!I->hasExternalWeakLinkage()) continue;
298 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n';
301 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
302 if (!I->hasExternalWeakLinkage()) continue;
303 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n';
307 if (MAI->getSetDirective()) {
309 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
311 MCSymbol *Name = GetGlobalValueSymbol(I);
313 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
314 MCSymbol *Target = GetGlobalValueSymbol(GV);
316 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
317 O << "\t.globl\t" << *Name << '\n';
318 else if (I->hasWeakLinkage())
319 O << MAI->getWeakRefDirective() << *Name << '\n';
321 assert(I->hasLocalLinkage() && "Invalid alias linkage");
323 printVisibility(Name, I->getVisibility());
325 O << MAI->getSetDirective() << ' ' << *Name << ", " << *Target << '\n';
329 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
330 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
331 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
332 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
333 MP->finishAssembly(O, *this, *MAI);
335 // If we don't have any trampolines, then we don't require stack memory
336 // to be executable. Some targets have a directive to declare this.
337 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
338 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
339 if (MAI->getNonexecutableStackDirective())
340 O << MAI->getNonexecutableStackDirective() << '\n';
343 // Allow the target to emit any magic that it wants at the end of the file,
344 // after everything else has gone out.
347 delete Mang; Mang = 0;
350 OutStreamer.Finish();
354 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
355 // Get the function symbol.
356 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
357 IncrementFunctionNumber();
360 LI = &getAnalysis<MachineLoopInfo>();
364 // SectionCPs - Keep track the alignment, constpool entries per Section.
368 SmallVector<unsigned, 4> CPEs;
369 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
373 /// EmitConstantPool - Print to the current output stream assembly
374 /// representations of the constants in the constant pool MCP. This is
375 /// used to print out constants which have been "spilled to memory" by
376 /// the code generator.
378 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
379 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
380 if (CP.empty()) return;
382 // Calculate sections for constant pool entries. We collect entries to go into
383 // the same section together to reduce amount of section switch statements.
384 SmallVector<SectionCPs, 4> CPSections;
385 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
386 const MachineConstantPoolEntry &CPE = CP[i];
387 unsigned Align = CPE.getAlignment();
390 switch (CPE.getRelocationInfo()) {
391 default: llvm_unreachable("Unknown section kind");
392 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
394 Kind = SectionKind::getReadOnlyWithRelLocal();
397 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
398 case 4: Kind = SectionKind::getMergeableConst4(); break;
399 case 8: Kind = SectionKind::getMergeableConst8(); break;
400 case 16: Kind = SectionKind::getMergeableConst16();break;
401 default: Kind = SectionKind::getMergeableConst(); break;
405 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
407 // The number of sections are small, just do a linear search from the
408 // last section to the first.
410 unsigned SecIdx = CPSections.size();
411 while (SecIdx != 0) {
412 if (CPSections[--SecIdx].S == S) {
418 SecIdx = CPSections.size();
419 CPSections.push_back(SectionCPs(S, Align));
422 if (Align > CPSections[SecIdx].Alignment)
423 CPSections[SecIdx].Alignment = Align;
424 CPSections[SecIdx].CPEs.push_back(i);
427 // Now print stuff into the calculated sections.
428 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
429 OutStreamer.SwitchSection(CPSections[i].S);
430 EmitAlignment(Log2_32(CPSections[i].Alignment));
433 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
434 unsigned CPI = CPSections[i].CPEs[j];
435 MachineConstantPoolEntry CPE = CP[CPI];
437 // Emit inter-object padding for alignment.
438 unsigned AlignMask = CPE.getAlignment() - 1;
439 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
440 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
442 const Type *Ty = CPE.getType();
443 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
445 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
448 O.PadToColumn(MAI->getCommentColumn());
449 O << MAI->getCommentString() << " constant ";
450 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
453 if (CPE.isMachineConstantPoolEntry())
454 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
456 EmitGlobalConstant(CPE.Val.ConstVal);
461 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
462 /// by the current function to the current output stream.
464 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
465 MachineFunction &MF) {
466 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
467 if (JT.empty()) return;
469 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
471 // Pick the directive to use to print the jump table entries, and switch to
472 // the appropriate section.
473 TargetLowering *LoweringInfo = TM.getTargetLowering();
475 const Function *F = MF.getFunction();
476 bool JTInDiffSection = false;
477 if (F->isWeakForLinker() ||
478 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
479 // In PIC mode, we need to emit the jump table to the same section as the
480 // function body itself, otherwise the label differences won't make sense.
481 // We should also do if the section name is NULL or function is declared in
482 // discardable section.
483 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
486 // Otherwise, drop it in the readonly section.
487 const MCSection *ReadOnlySection =
488 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
489 OutStreamer.SwitchSection(ReadOnlySection);
490 JTInDiffSection = true;
493 EmitAlignment(Log2_32(MJTI->getAlignment()));
495 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
496 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
498 // If this jump table was deleted, ignore it.
499 if (JTBBs.empty()) continue;
501 // For PIC codegen, if possible we want to use the SetDirective to reduce
502 // the number of relocations the assembler will generate for the jump table.
503 // Set directives are all printed before the jump table itself.
504 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
505 if (MAI->getSetDirective() && IsPic)
506 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
507 if (EmittedSets.insert(JTBBs[ii]))
508 printPICJumpTableSetLabel(i, JTBBs[ii]);
510 // On some targets (e.g. Darwin) we want to emit two consequtive labels
511 // before each jump table. The first label is never referenced, but tells
512 // the assembler and linker the extents of the jump table object. The
513 // second label is actually referenced by the code.
514 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
515 O << MAI->getLinkerPrivateGlobalPrefix()
516 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
519 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
520 << '_' << i << ":\n";
522 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
523 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
529 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
530 const MachineBasicBlock *MBB,
531 unsigned uid) const {
532 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
534 // Use JumpTableDirective otherwise honor the entry size from the jump table
536 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
537 bool HadJTEntryDirective = JTEntryDirective != NULL;
538 if (!HadJTEntryDirective) {
539 JTEntryDirective = MJTI->getEntrySize() == 4 ?
540 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
543 O << JTEntryDirective << ' ';
545 // If we have emitted set directives for the jump table entries, print
546 // them rather than the entries themselves. If we're emitting PIC, then
547 // emit the table entries as differences between two text section labels.
548 // If we're emitting non-PIC code, then emit the entries as direct
549 // references to the target basic blocks.
551 O << *GetMBBSymbol(MBB->getNumber());
552 } else if (MAI->getSetDirective()) {
553 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
554 << '_' << uid << "_set_" << MBB->getNumber();
556 O << *GetMBBSymbol(MBB->getNumber());
557 // If the arch uses custom Jump Table directives, don't calc relative to
559 if (!HadJTEntryDirective)
560 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
561 << getFunctionNumber() << '_' << uid;
566 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
567 /// special global used by LLVM. If so, emit it and return true, otherwise
568 /// do nothing and return false.
569 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
570 if (GV->getName() == "llvm.used") {
571 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
572 EmitLLVMUsedList(GV->getInitializer());
576 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
577 if (GV->getSection() == "llvm.metadata" ||
578 GV->hasAvailableExternallyLinkage())
581 if (!GV->hasAppendingLinkage()) return false;
583 assert(GV->hasInitializer() && "Not a special LLVM global!");
585 const TargetData *TD = TM.getTargetData();
586 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
587 if (GV->getName() == "llvm.global_ctors") {
588 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
589 EmitAlignment(Align, 0);
590 EmitXXStructorList(GV->getInitializer());
592 if (TM.getRelocationModel() == Reloc::Static &&
593 MAI->hasStaticCtorDtorReferenceInStaticMode())
594 O << ".reference .constructors_used\n";
598 if (GV->getName() == "llvm.global_dtors") {
599 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
600 EmitAlignment(Align, 0);
601 EmitXXStructorList(GV->getInitializer());
603 if (TM.getRelocationModel() == Reloc::Static &&
604 MAI->hasStaticCtorDtorReferenceInStaticMode())
605 O << ".reference .destructors_used\n";
612 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
613 /// global in the specified llvm.used list for which emitUsedDirectiveFor
614 /// is true, as being used with this directive.
615 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
616 const char *Directive = MAI->getUsedDirective();
618 // Should be an array of 'i8*'.
619 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
620 if (InitList == 0) return;
622 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
623 const GlobalValue *GV =
624 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
625 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
627 EmitConstantValueOnly(InitList->getOperand(i));
633 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
634 /// function pointers, ignoring the init priority.
635 void AsmPrinter::EmitXXStructorList(Constant *List) {
636 // Should be an array of '{ int, void ()* }' structs. The first value is the
637 // init priority, which we ignore.
638 if (!isa<ConstantArray>(List)) return;
639 ConstantArray *InitList = cast<ConstantArray>(List);
640 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
641 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
642 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
644 if (CS->getOperand(1)->isNullValue())
645 return; // Found a null terminator, exit printing.
646 // Emit the function pointer.
647 EmitGlobalConstant(CS->getOperand(1));
652 //===----------------------------------------------------------------------===//
653 /// LEB 128 number encoding.
655 /// PrintULEB128 - Print a series of hexadecimal values (separated by commas)
656 /// representing an unsigned leb128 value.
657 void AsmPrinter::PrintULEB128(unsigned Value) const {
659 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
661 if (Value) Byte |= 0x80;
663 if (Value) O << ", ";
667 /// PrintSLEB128 - Print a series of hexadecimal values (separated by commas)
668 /// representing a signed leb128 value.
669 void AsmPrinter::PrintSLEB128(int Value) const {
670 int Sign = Value >> (8 * sizeof(Value) - 1);
674 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
676 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
677 if (IsMore) Byte |= 0x80;
679 if (IsMore) O << ", ";
683 //===--------------------------------------------------------------------===//
684 // Emission and print routines
687 /// PrintHex - Print a value as a hexadecimal value.
689 void AsmPrinter::PrintHex(uint64_t Value) const {
694 /// EOL - Print a newline character to asm stream. If a comment is present
695 /// then it will be printed first. Comments should not contain '\n'.
696 void AsmPrinter::EOL() const {
700 void AsmPrinter::EOL(const Twine &Comment) const {
701 if (VerboseAsm && !Comment.isTriviallyEmpty()) {
702 O.PadToColumn(MAI->getCommentColumn());
703 O << MAI->getCommentString()
710 static const char *DecodeDWARFEncoding(unsigned Encoding) {
712 case dwarf::DW_EH_PE_absptr:
714 case dwarf::DW_EH_PE_omit:
716 case dwarf::DW_EH_PE_pcrel:
718 case dwarf::DW_EH_PE_udata4:
720 case dwarf::DW_EH_PE_udata8:
722 case dwarf::DW_EH_PE_sdata4:
724 case dwarf::DW_EH_PE_sdata8:
726 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
727 return "pcrel udata4";
728 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
729 return "pcrel sdata4";
730 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
731 return "pcrel udata8";
732 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
733 return "pcrel sdata8";
734 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
735 return "indirect pcrel udata4";
736 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
737 return "indirect pcrel sdata4";
738 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
739 return "indirect pcrel udata8";
740 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
741 return "indirect pcrel sdata8";
747 void AsmPrinter::EOL(const Twine &Comment, unsigned Encoding) const {
748 if (VerboseAsm && !Comment.isTriviallyEmpty()) {
749 O.PadToColumn(MAI->getCommentColumn());
750 O << MAI->getCommentString()
754 if (const char *EncStr = DecodeDWARFEncoding(Encoding))
755 O << " (" << EncStr << ')';
760 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
761 /// unsigned leb128 value.
762 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
763 if (MAI->hasLEB128()) {
767 O << MAI->getData8bitsDirective();
772 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
773 /// signed leb128 value.
774 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
775 if (MAI->hasLEB128()) {
779 O << MAI->getData8bitsDirective();
784 /// EmitInt8 - Emit a byte directive and value.
786 void AsmPrinter::EmitInt8(int Value) const {
787 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
790 /// EmitInt16 - Emit a short directive and value.
792 void AsmPrinter::EmitInt16(int Value) const {
793 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
796 /// EmitInt32 - Emit a long directive and value.
798 void AsmPrinter::EmitInt32(int Value) const {
799 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
802 /// EmitInt64 - Emit a long long directive and value.
804 void AsmPrinter::EmitInt64(uint64_t Value) const {
805 OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
808 /// toOctal - Convert the low order bits of X into an octal digit.
810 static inline char toOctal(int X) {
814 /// printStringChar - Print a char, escaped if necessary.
816 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
819 } else if (C == '\\') {
821 } else if (isprint((unsigned char)C)) {
825 case '\b': O << "\\b"; break;
826 case '\f': O << "\\f"; break;
827 case '\n': O << "\\n"; break;
828 case '\r': O << "\\r"; break;
829 case '\t': O << "\\t"; break;
832 O << toOctal(C >> 6);
833 O << toOctal(C >> 3);
834 O << toOctal(C >> 0);
840 /// EmitString - Emit a string with quotes and a null terminator.
841 /// Special characters are emitted properly.
842 /// \literal (Eg. '\t') \endliteral
843 void AsmPrinter::EmitString(const StringRef String) const {
844 EmitString(String.data(), String.size());
847 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
848 const char* AscizDirective = MAI->getAscizDirective();
852 O << MAI->getAsciiDirective();
854 for (unsigned i = 0; i < Size; ++i)
855 printStringChar(O, String[i]);
863 /// EmitFile - Emit a .file directive.
864 void AsmPrinter::EmitFile(unsigned Number, StringRef Name) const {
865 O << "\t.file\t" << Number << " \"";
866 for (unsigned i = 0, N = Name.size(); i < N; ++i)
867 printStringChar(O, Name[i]);
872 //===----------------------------------------------------------------------===//
874 // EmitAlignment - Emit an alignment directive to the specified power of
875 // two boundary. For example, if you pass in 3 here, you will get an 8
876 // byte alignment. If a global value is specified, and if that global has
877 // an explicit alignment requested, it will unconditionally override the
878 // alignment request. However, if ForcedAlignBits is specified, this value
879 // has final say: the ultimate alignment will be the max of ForcedAlignBits
880 // and the alignment computed with NumBits and the global.
884 // if (GV && GV->hasalignment) Align = GV->getalignment();
885 // Align = std::max(Align, ForcedAlignBits);
887 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
888 unsigned ForcedAlignBits,
889 bool UseFillExpr) const {
890 if (GV && GV->getAlignment())
891 NumBits = Log2_32(GV->getAlignment());
892 NumBits = std::max(NumBits, ForcedAlignBits);
894 if (NumBits == 0) return; // No need to emit alignment.
896 unsigned FillValue = 0;
897 if (getCurrentSection()->getKind().isText())
898 FillValue = MAI->getTextAlignFillValue();
900 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
903 // Print out the specified constant, without a storage class. Only the
904 // constants valid in constant expressions can occur here.
905 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
906 if (CV->isNullValue() || isa<UndefValue>(CV)) {
911 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
912 O << CI->getZExtValue();
916 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
917 // This is a constant address for a global variable or function. Use the
918 // name of the variable or function as the address value.
919 O << *GetGlobalValueSymbol(GV);
923 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
924 O << *GetBlockAddressSymbol(BA);
928 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
930 llvm_unreachable("Unknown constant value!");
935 switch (CE->getOpcode()) {
936 case Instruction::ZExt:
937 case Instruction::SExt:
938 case Instruction::FPTrunc:
939 case Instruction::FPExt:
940 case Instruction::UIToFP:
941 case Instruction::SIToFP:
942 case Instruction::FPToUI:
943 case Instruction::FPToSI:
945 llvm_unreachable("FIXME: Don't support this constant cast expr");
946 case Instruction::GetElementPtr: {
947 // generate a symbolic expression for the byte address
948 const TargetData *TD = TM.getTargetData();
949 const Constant *ptrVal = CE->getOperand(0);
950 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
951 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
954 return EmitConstantValueOnly(ptrVal);
956 // Truncate/sext the offset to the pointer size.
957 if (TD->getPointerSizeInBits() != 64) {
958 int SExtAmount = 64-TD->getPointerSizeInBits();
959 Offset = (Offset << SExtAmount) >> SExtAmount;
964 EmitConstantValueOnly(ptrVal);
966 O << ") + " << Offset;
968 O << ") - " << -Offset;
971 case Instruction::BitCast:
972 return EmitConstantValueOnly(CE->getOperand(0));
974 case Instruction::IntToPtr: {
975 // Handle casts to pointers by changing them into casts to the appropriate
976 // integer type. This promotes constant folding and simplifies this code.
977 const TargetData *TD = TM.getTargetData();
978 Constant *Op = CE->getOperand(0);
979 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
981 return EmitConstantValueOnly(Op);
984 case Instruction::PtrToInt: {
985 // Support only foldable casts to/from pointers that can be eliminated by
986 // changing the pointer to the appropriately sized integer type.
987 Constant *Op = CE->getOperand(0);
988 const Type *Ty = CE->getType();
989 const TargetData *TD = TM.getTargetData();
991 // We can emit the pointer value into this slot if the slot is an
992 // integer slot greater or equal to the size of the pointer.
993 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
994 return EmitConstantValueOnly(Op);
997 EmitConstantValueOnly(Op);
999 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
1002 ptrMask.toStringUnsigned(S);
1003 O << ") & " << S.str() << ')';
1007 case Instruction::Trunc:
1008 // We emit the value and depend on the assembler to truncate the generated
1009 // expression properly. This is important for differences between
1010 // blockaddress labels. Since the two labels are in the same function, it
1011 // is reasonable to treat their delta as a 32-bit value.
1012 return EmitConstantValueOnly(CE->getOperand(0));
1014 case Instruction::Add:
1015 case Instruction::Sub:
1016 case Instruction::And:
1017 case Instruction::Or:
1018 case Instruction::Xor:
1020 EmitConstantValueOnly(CE->getOperand(0));
1022 switch (CE->getOpcode()) {
1023 case Instruction::Add:
1026 case Instruction::Sub:
1029 case Instruction::And:
1032 case Instruction::Or:
1035 case Instruction::Xor:
1042 EmitConstantValueOnly(CE->getOperand(1));
1048 /// printAsCString - Print the specified array as a C compatible string, only if
1049 /// the predicate isString is true.
1051 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
1053 assert(CVA->isString() && "Array is not string compatible!");
1056 for (unsigned i = 0; i != LastElt; ++i) {
1058 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
1059 printStringChar(O, C);
1064 /// EmitString - Emit a zero-byte-terminated string constant.
1066 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
1067 unsigned NumElts = CVA->getNumOperands();
1068 if (MAI->getAscizDirective() && NumElts &&
1069 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
1070 O << MAI->getAscizDirective();
1071 printAsCString(O, CVA, NumElts-1);
1073 O << MAI->getAsciiDirective();
1074 printAsCString(O, CVA, NumElts);
1079 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1081 if (AddrSpace == 0 && CA->isString()) {
1083 } else { // Not a string. Print the values in successive locations
1084 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1085 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
1089 static void EmitGlobalConstantVector(const ConstantVector *CV,
1090 unsigned AddrSpace, AsmPrinter &AP) {
1091 const VectorType *VTy = CV->getType();
1092 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
1093 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
1096 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1097 unsigned AddrSpace, AsmPrinter &AP) {
1098 // Print the fields in successive locations. Pad to align if needed!
1099 const TargetData *TD = AP.TM.getTargetData();
1100 unsigned Size = TD->getTypeAllocSize(CS->getType());
1101 const StructLayout *Layout = TD->getStructLayout(CS->getType());
1102 uint64_t SizeSoFar = 0;
1103 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1104 const Constant *field = CS->getOperand(i);
1106 // Check if padding is needed and insert one or more 0s.
1107 uint64_t FieldSize = TD->getTypeAllocSize(field->getType());
1108 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1109 - Layout->getElementOffset(i)) - FieldSize;
1110 SizeSoFar += FieldSize + PadSize;
1112 // Now print the actual field value.
1113 AP.EmitGlobalConstant(field, AddrSpace);
1115 // Insert padding - this may include padding to increase the size of the
1116 // current field up to the ABI size (if the struct is not packed) as well
1117 // as padding to ensure that the next field starts at the right offset.
1118 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1120 assert(SizeSoFar == Layout->getSizeInBytes() &&
1121 "Layout of constant struct may be incorrect!");
1124 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1126 // FP Constants are printed as integer constants to avoid losing
1128 if (CFP->getType()->isDoubleTy()) {
1129 if (AP.VerboseAsm) {
1130 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1131 AP.O.PadToColumn(AP.MAI->getCommentColumn());
1132 AP.O << AP.MAI->getCommentString() << " double " << Val << '\n';
1135 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1136 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1140 if (CFP->getType()->isFloatTy()) {
1141 if (AP.VerboseAsm) {
1142 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1143 AP.O.PadToColumn(AP.MAI->getCommentColumn());
1144 AP.O << AP.MAI->getCommentString() << " float " << Val << '\n';
1146 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1147 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1151 if (CFP->getType()->isX86_FP80Ty()) {
1152 // all long double variants are printed as hex
1153 // api needed to prevent premature destruction
1154 APInt API = CFP->getValueAPF().bitcastToAPInt();
1155 const uint64_t *p = API.getRawData();
1156 if (AP.VerboseAsm) {
1157 // Convert to double so we can print the approximate val as a comment.
1158 APFloat DoubleVal = CFP->getValueAPF();
1160 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1162 AP.O.PadToColumn(AP.MAI->getCommentColumn());
1163 AP.O << AP.MAI->getCommentString() << " x86_fp80 ~= "
1164 << DoubleVal.convertToDouble() << '\n';
1167 if (AP.TM.getTargetData()->isBigEndian()) {
1168 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1169 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1171 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1172 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1175 // Emit the tail padding for the long double.
1176 const TargetData &TD = *AP.TM.getTargetData();
1177 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1178 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1182 assert(CFP->getType()->isPPC_FP128Ty() &&
1183 "Floating point constant type not handled");
1184 // All long double variants are printed as hex api needed to prevent
1185 // premature destruction.
1186 APInt API = CFP->getValueAPF().bitcastToAPInt();
1187 const uint64_t *p = API.getRawData();
1188 if (AP.TM.getTargetData()->isBigEndian()) {
1189 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1190 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1192 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1193 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1197 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1198 unsigned AddrSpace, AsmPrinter &AP) {
1199 const TargetData *TD = AP.TM.getTargetData();
1200 unsigned BitWidth = CI->getBitWidth();
1201 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1203 // We don't expect assemblers to support integer data directives
1204 // for more than 64 bits, so we emit the data in at most 64-bit
1205 // quantities at a time.
1206 const uint64_t *RawData = CI->getValue().getRawData();
1207 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1208 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1209 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1213 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1214 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1215 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1216 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1217 return OutStreamer.EmitZeros(Size, AddrSpace);
1220 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1221 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1228 O.PadToColumn(MAI->getCommentColumn());
1229 O << MAI->getCommentString() << " 0x";
1230 O.write_hex(CI->getZExtValue());
1233 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1236 EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1241 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1242 return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1244 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1245 return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1247 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1248 return EmitGlobalConstantFP(CFP, AddrSpace, *this);
1250 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1251 return EmitGlobalConstantVector(V, AddrSpace, *this);
1253 printDataDirective(CV->getType(), AddrSpace);
1254 EmitConstantValueOnly(CV);
1258 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1259 // Target doesn't support this yet!
1260 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1263 /// PrintSpecial - Print information related to the specified machine instr
1264 /// that is independent of the operand, and may be independent of the instr
1265 /// itself. This can be useful for portably encoding the comment character
1266 /// or other bits of target-specific knowledge into the asmstrings. The
1267 /// syntax used is ${:comment}. Targets can override this to add support
1268 /// for their own strange codes.
1269 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1270 if (!strcmp(Code, "private")) {
1271 O << MAI->getPrivateGlobalPrefix();
1272 } else if (!strcmp(Code, "comment")) {
1274 O << MAI->getCommentString();
1275 } else if (!strcmp(Code, "uid")) {
1276 // Comparing the address of MI isn't sufficient, because machineinstrs may
1277 // be allocated to the same address across functions.
1278 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1280 // If this is a new LastFn instruction, bump the counter.
1281 if (LastMI != MI || LastFn != ThisF) {
1289 raw_string_ostream Msg(msg);
1290 Msg << "Unknown special formatter '" << Code
1291 << "' for machine instr: " << *MI;
1292 llvm_report_error(Msg.str());
1296 /// processDebugLoc - Processes the debug information of each machine
1297 /// instruction's DebugLoc.
1298 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1299 bool BeforePrintingInsn) {
1300 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1301 || !DW->ShouldEmitDwarfDebug())
1303 DebugLoc DL = MI->getDebugLoc();
1306 DILocation CurDLT = MF->getDILocation(DL);
1307 if (CurDLT.getScope().isNull())
1310 if (BeforePrintingInsn) {
1311 if (CurDLT.getNode() != PrevDLT) {
1312 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1313 CurDLT.getColumnNumber(),
1314 CurDLT.getScope().getNode());
1317 DW->BeginScope(MI, L);
1318 PrevDLT = CurDLT.getNode();
1321 // After printing instruction
1327 /// printInlineAsm - This method formats and prints the specified machine
1328 /// instruction that is an inline asm.
1329 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1330 unsigned NumOperands = MI->getNumOperands();
1332 // Count the number of register definitions.
1333 unsigned NumDefs = 0;
1334 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1336 assert(NumDefs != NumOperands-1 && "No asm string?");
1338 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1340 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1341 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1345 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1346 // These are useful to see where empty asm's wound up.
1347 if (AsmStr[0] == 0) {
1348 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1349 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1353 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1355 // The variant of the current asmprinter.
1356 int AsmPrinterVariant = MAI->getAssemblerDialect();
1358 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1359 const char *LastEmitted = AsmStr; // One past the last character emitted.
1361 while (*LastEmitted) {
1362 switch (*LastEmitted) {
1364 // Not a special case, emit the string section literally.
1365 const char *LiteralEnd = LastEmitted+1;
1366 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1367 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1369 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1370 O.write(LastEmitted, LiteralEnd-LastEmitted);
1371 LastEmitted = LiteralEnd;
1375 ++LastEmitted; // Consume newline character.
1376 O << '\n'; // Indent code with newline.
1379 ++LastEmitted; // Consume '$' character.
1383 switch (*LastEmitted) {
1384 default: Done = false; break;
1385 case '$': // $$ -> $
1386 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1388 ++LastEmitted; // Consume second '$' character.
1390 case '(': // $( -> same as GCC's { character.
1391 ++LastEmitted; // Consume '(' character.
1392 if (CurVariant != -1) {
1393 llvm_report_error("Nested variants found in inline asm string: '"
1394 + std::string(AsmStr) + "'");
1396 CurVariant = 0; // We're in the first variant now.
1399 ++LastEmitted; // consume '|' character.
1400 if (CurVariant == -1)
1401 O << '|'; // this is gcc's behavior for | outside a variant
1403 ++CurVariant; // We're in the next variant.
1405 case ')': // $) -> same as GCC's } char.
1406 ++LastEmitted; // consume ')' character.
1407 if (CurVariant == -1)
1408 O << '}'; // this is gcc's behavior for } outside a variant
1415 bool HasCurlyBraces = false;
1416 if (*LastEmitted == '{') { // ${variable}
1417 ++LastEmitted; // Consume '{' character.
1418 HasCurlyBraces = true;
1421 // If we have ${:foo}, then this is not a real operand reference, it is a
1422 // "magic" string reference, just like in .td files. Arrange to call
1424 if (HasCurlyBraces && *LastEmitted == ':') {
1426 const char *StrStart = LastEmitted;
1427 const char *StrEnd = strchr(StrStart, '}');
1429 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1430 + std::string(AsmStr) + "'");
1433 std::string Val(StrStart, StrEnd);
1434 PrintSpecial(MI, Val.c_str());
1435 LastEmitted = StrEnd+1;
1439 const char *IDStart = LastEmitted;
1442 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1443 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1444 llvm_report_error("Bad $ operand number in inline asm string: '"
1445 + std::string(AsmStr) + "'");
1447 LastEmitted = IDEnd;
1449 char Modifier[2] = { 0, 0 };
1451 if (HasCurlyBraces) {
1452 // If we have curly braces, check for a modifier character. This
1453 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1454 if (*LastEmitted == ':') {
1455 ++LastEmitted; // Consume ':' character.
1456 if (*LastEmitted == 0) {
1457 llvm_report_error("Bad ${:} expression in inline asm string: '"
1458 + std::string(AsmStr) + "'");
1461 Modifier[0] = *LastEmitted;
1462 ++LastEmitted; // Consume modifier character.
1465 if (*LastEmitted != '}') {
1466 llvm_report_error("Bad ${} expression in inline asm string: '"
1467 + std::string(AsmStr) + "'");
1469 ++LastEmitted; // Consume '}' character.
1472 if ((unsigned)Val >= NumOperands-1) {
1473 llvm_report_error("Invalid $ operand number in inline asm string: '"
1474 + std::string(AsmStr) + "'");
1477 // Okay, we finally have a value number. Ask the target to print this
1479 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1484 // Scan to find the machine operand number for the operand.
1485 for (; Val; --Val) {
1486 if (OpNo >= MI->getNumOperands()) break;
1487 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1488 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1491 if (OpNo >= MI->getNumOperands()) {
1494 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1495 ++OpNo; // Skip over the ID number.
1497 if (Modifier[0] == 'l') // labels are target independent
1498 O << *GetMBBSymbol(MI->getOperand(OpNo).getMBB()->getNumber());
1500 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1501 if ((OpFlags & 7) == 4) {
1502 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1503 Modifier[0] ? Modifier : 0);
1505 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1506 Modifier[0] ? Modifier : 0);
1512 raw_string_ostream Msg(msg);
1513 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1515 llvm_report_error(Msg.str());
1522 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1525 /// printImplicitDef - This method prints the specified machine instruction
1526 /// that is an implicit def.
1527 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1528 if (!VerboseAsm) return;
1529 O.PadToColumn(MAI->getCommentColumn());
1530 O << MAI->getCommentString() << " implicit-def: "
1531 << TRI->getName(MI->getOperand(0).getReg());
1534 void AsmPrinter::printKill(const MachineInstr *MI) const {
1535 if (!VerboseAsm) return;
1536 O.PadToColumn(MAI->getCommentColumn());
1537 O << MAI->getCommentString() << " kill:";
1538 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1539 const MachineOperand &op = MI->getOperand(n);
1540 assert(op.isReg() && "KILL instruction must have only register operands");
1541 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1545 /// printLabel - This method prints a local label used by debug and
1546 /// exception handling tables.
1547 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1548 printLabel(MI->getOperand(0).getImm());
1551 void AsmPrinter::printLabel(unsigned Id) const {
1552 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1555 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1556 /// instruction, using the specified assembler variant. Targets should
1557 /// override this to format as appropriate.
1558 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1559 unsigned AsmVariant, const char *ExtraCode) {
1560 // Target doesn't support this yet!
1564 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1565 unsigned AsmVariant,
1566 const char *ExtraCode) {
1567 // Target doesn't support this yet!
1571 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1572 const char *Suffix) const {
1573 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1576 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1577 const BasicBlock *BB,
1578 const char *Suffix) const {
1579 assert(BB->hasName() &&
1580 "Address of anonymous basic block not supported yet!");
1582 // This code must use the function name itself, and not the function number,
1583 // since it must be possible to generate the label name from within other
1585 SmallString<60> FnName;
1586 Mang->getNameWithPrefix(FnName, F, false);
1588 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1589 SmallString<60> NameResult;
1590 Mang->getNameWithPrefix(NameResult,
1591 StringRef("BA") + Twine((unsigned)FnName.size()) +
1592 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1595 return OutContext.GetOrCreateSymbol(NameResult.str());
1598 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1599 SmallString<60> Name;
1600 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1601 << getFunctionNumber() << '_' << MBBID;
1603 return OutContext.GetOrCreateSymbol(Name.str());
1606 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1608 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1609 SmallString<60> NameStr;
1610 Mang->getNameWithPrefix(NameStr, GV, false);
1611 return OutContext.GetOrCreateSymbol(NameStr.str());
1614 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1615 /// global value name as its base, with the specified suffix, and where the
1616 /// symbol is forced to have private linkage if ForcePrivate is true.
1617 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1619 bool ForcePrivate) const {
1620 SmallString<60> NameStr;
1621 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1622 NameStr.append(Suffix.begin(), Suffix.end());
1623 return OutContext.GetOrCreateSymbol(NameStr.str());
1626 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1628 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1629 SmallString<60> NameStr;
1630 Mang->getNameWithPrefix(NameStr, Sym);
1631 return OutContext.GetOrCreateSymbol(NameStr.str());
1635 /// EmitBasicBlockStart - This method prints the label for the specified
1636 /// MachineBasicBlock, an alignment (if present) and a comment describing
1637 /// it if appropriate.
1638 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1639 // Emit an alignment directive for this block, if needed.
1640 if (unsigned Align = MBB->getAlignment())
1641 EmitAlignment(Log2_32(Align));
1643 // If the block has its address taken, emit a special label to satisfy
1644 // references to the block. This is done so that we don't need to
1645 // remember the number of this label, and so that we can make
1646 // forward references to labels without knowing what their numbers
1648 if (MBB->hasAddressTaken()) {
1649 O << *GetBlockAddressSymbol(MBB->getBasicBlock()->getParent(),
1650 MBB->getBasicBlock());
1653 O.PadToColumn(MAI->getCommentColumn());
1654 O << MAI->getCommentString() << " Address Taken";
1659 // Print the main label for the block.
1660 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1662 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1664 O << *GetMBBSymbol(MBB->getNumber()) << ':';
1669 // Print some comments to accompany the label.
1671 if (const BasicBlock *BB = MBB->getBasicBlock())
1672 if (BB->hasName()) {
1673 O.PadToColumn(MAI->getCommentColumn());
1674 O << MAI->getCommentString() << ' ';
1675 WriteAsOperand(O, BB, /*PrintType=*/false);
1683 /// printPICJumpTableSetLabel - This method prints a set label for the
1684 /// specified MachineBasicBlock for a jumptable entry.
1685 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1686 const MachineBasicBlock *MBB) const {
1687 if (!MAI->getSetDirective())
1690 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1691 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ','
1692 << *GetMBBSymbol(MBB->getNumber())
1693 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1694 << '_' << uid << '\n';
1697 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1698 const MachineBasicBlock *MBB) const {
1699 if (!MAI->getSetDirective())
1702 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1703 << getFunctionNumber() << '_' << uid << '_' << uid2
1704 << "_set_" << MBB->getNumber() << ','
1705 << *GetMBBSymbol(MBB->getNumber())
1706 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1707 << '_' << uid << '_' << uid2 << '\n';
1710 /// printDataDirective - This method prints the asm directive for the
1712 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1713 const TargetData *TD = TM.getTargetData();
1714 switch (type->getTypeID()) {
1715 case Type::FloatTyID: case Type::DoubleTyID:
1716 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1717 assert(0 && "Should have already output floating point constant.");
1719 assert(0 && "Can't handle printing this type of thing");
1720 case Type::IntegerTyID: {
1721 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1723 O << MAI->getData8bitsDirective(AddrSpace);
1724 else if (BitWidth <= 16)
1725 O << MAI->getData16bitsDirective(AddrSpace);
1726 else if (BitWidth <= 32)
1727 O << MAI->getData32bitsDirective(AddrSpace);
1728 else if (BitWidth <= 64) {
1729 assert(MAI->getData64bitsDirective(AddrSpace) &&
1730 "Target cannot handle 64-bit constant exprs!");
1731 O << MAI->getData64bitsDirective(AddrSpace);
1733 llvm_unreachable("Target cannot handle given data directive width!");
1737 case Type::PointerTyID:
1738 if (TD->getPointerSize() == 8) {
1739 assert(MAI->getData64bitsDirective(AddrSpace) &&
1740 "Target cannot handle 64-bit pointer exprs!");
1741 O << MAI->getData64bitsDirective(AddrSpace);
1742 } else if (TD->getPointerSize() == 2) {
1743 O << MAI->getData16bitsDirective(AddrSpace);
1744 } else if (TD->getPointerSize() == 1) {
1745 O << MAI->getData8bitsDirective(AddrSpace);
1747 O << MAI->getData32bitsDirective(AddrSpace);
1753 void AsmPrinter::printVisibility(const MCSymbol *Sym,
1754 unsigned Visibility) const {
1755 if (Visibility == GlobalValue::HiddenVisibility) {
1756 if (const char *Directive = MAI->getHiddenDirective())
1757 O << Directive << *Sym << '\n';
1758 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1759 if (const char *Directive = MAI->getProtectedDirective())
1760 O << Directive << *Sym << '\n';
1764 void AsmPrinter::printOffset(int64_t Offset) const {
1767 else if (Offset < 0)
1771 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1772 if (!S->usesMetadata())
1775 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1776 if (GCPI != GCMetadataPrinters.end())
1777 return GCPI->second;
1779 const char *Name = S->getName().c_str();
1781 for (GCMetadataPrinterRegistry::iterator
1782 I = GCMetadataPrinterRegistry::begin(),
1783 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1784 if (strcmp(Name, I->getName()) == 0) {
1785 GCMetadataPrinter *GMP = I->instantiate();
1787 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1791 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1792 llvm_unreachable(0);
1795 /// EmitComments - Pretty-print comments for instructions
1796 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1800 bool Newline = false;
1802 if (!MI.getDebugLoc().isUnknown()) {
1803 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1805 // Print source line info.
1806 O.PadToColumn(MAI->getCommentColumn());
1807 O << MAI->getCommentString() << ' ';
1808 DIScope Scope = DLT.getScope();
1809 // Omit the directory, because it's likely to be long and uninteresting.
1810 if (!Scope.isNull())
1811 O << Scope.getFilename();
1814 O << ':' << DLT.getLineNumber();
1815 if (DLT.getColumnNumber() != 0)
1816 O << ':' << DLT.getColumnNumber();
1820 // Check for spills and reloads
1823 const MachineFrameInfo *FrameInfo =
1824 MI.getParent()->getParent()->getFrameInfo();
1826 // We assume a single instruction only has a spill or reload, not
1828 const MachineMemOperand *MMO;
1829 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1830 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1831 MMO = *MI.memoperands_begin();
1832 if (Newline) O << '\n';
1833 O.PadToColumn(MAI->getCommentColumn());
1834 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1838 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1839 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1840 if (Newline) O << '\n';
1841 O.PadToColumn(MAI->getCommentColumn());
1842 O << MAI->getCommentString() << ' '
1843 << MMO->getSize() << "-byte Folded Reload";
1847 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1848 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1849 MMO = *MI.memoperands_begin();
1850 if (Newline) O << '\n';
1851 O.PadToColumn(MAI->getCommentColumn());
1852 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1856 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1857 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1858 if (Newline) O << '\n';
1859 O.PadToColumn(MAI->getCommentColumn());
1860 O << MAI->getCommentString() << ' '
1861 << MMO->getSize() << "-byte Folded Spill";
1866 // Check for spill-induced copies
1867 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1868 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1869 SrcSubIdx, DstSubIdx)) {
1870 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1871 if (Newline) O << '\n';
1872 O.PadToColumn(MAI->getCommentColumn());
1873 O << MAI->getCommentString() << " Reload Reuse";
1878 /// PrintChildLoopComment - Print comments about child loops within
1879 /// the loop for this basic block, with nesting.
1881 static void PrintChildLoopComment(formatted_raw_ostream &O,
1882 const MachineLoop *loop,
1883 const MCAsmInfo *MAI,
1884 int FunctionNumber) {
1885 // Add child loop information
1886 for(MachineLoop::iterator cl = loop->begin(),
1887 clend = loop->end();
1890 MachineBasicBlock *Header = (*cl)->getHeader();
1891 assert(Header && "No header for loop");
1894 O.PadToColumn(MAI->getCommentColumn());
1896 O << MAI->getCommentString();
1897 O.indent(((*cl)->getLoopDepth()-1)*2)
1898 << " Child Loop BB" << FunctionNumber << "_"
1899 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
1901 PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
1905 /// EmitComments - Pretty-print comments for basic blocks
1906 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const {
1908 // Add loop depth information
1909 const MachineLoop *loop = LI->getLoopFor(&MBB);
1912 // Print a newline after bb# annotation.
1914 O.PadToColumn(MAI->getCommentColumn());
1915 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
1918 O.PadToColumn(MAI->getCommentColumn());
1920 MachineBasicBlock *Header = loop->getHeader();
1921 assert(Header && "No header for loop");
1923 if (Header == &MBB) {
1924 O << MAI->getCommentString() << " Loop Header";
1925 PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
1928 O << MAI->getCommentString() << " Loop Header is BB"
1929 << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
1932 if (loop->empty()) {
1934 O.PadToColumn(MAI->getCommentColumn());
1935 O << MAI->getCommentString() << " Inner Loop";
1938 // Add parent loop information
1939 for (const MachineLoop *CurLoop = loop->getParentLoop();
1941 CurLoop = CurLoop->getParentLoop()) {
1942 MachineBasicBlock *Header = CurLoop->getHeader();
1943 assert(Header && "No header for loop");
1946 O.PadToColumn(MAI->getCommentColumn());
1947 O << MAI->getCommentString();
1948 O.indent((CurLoop->getLoopDepth()-1)*2)
1949 << " Inside Loop BB" << getFunctionNumber() << "_"
1950 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();