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/MCExpr.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCSection.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/Target/Mangler.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Target/TargetRegisterInfo.h"
46 #include "llvm/ADT/SmallPtrSet.h"
47 #include "llvm/ADT/SmallString.h"
51 static cl::opt<cl::boolOrDefault>
52 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
53 cl::init(cl::BOU_UNSET));
55 static bool getVerboseAsm(bool VDef) {
58 case cl::BOU_UNSET: return VDef;
59 case cl::BOU_TRUE: return true;
60 case cl::BOU_FALSE: return false;
64 char AsmPrinter::ID = 0;
65 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
66 const MCAsmInfo *T, bool VDef)
67 : MachineFunctionPass(&ID), O(o),
68 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
70 OutContext(*new MCContext()),
71 // FIXME: Pass instprinter to streamer.
72 OutStreamer(*createAsmStreamer(OutContext, O, *T,
73 TM.getTargetData()->isLittleEndian(),
74 getVerboseAsm(VDef), 0)),
76 LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
78 VerboseAsm = getVerboseAsm(VDef);
81 AsmPrinter::~AsmPrinter() {
82 for (gcp_iterator I = GCMetadataPrinters.begin(),
83 E = GCMetadataPrinters.end(); I != E; ++I)
90 /// getFunctionNumber - Return a unique ID for the current function.
92 unsigned AsmPrinter::getFunctionNumber() const {
93 return MF->getFunctionNumber();
96 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
97 return TM.getTargetLowering()->getObjFileLowering();
100 /// getCurrentSection() - Return the current section we are emitting to.
101 const MCSection *AsmPrinter::getCurrentSection() const {
102 return OutStreamer.getCurrentSection();
106 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
107 AU.setPreservesAll();
108 MachineFunctionPass::getAnalysisUsage(AU);
109 AU.addRequired<GCModuleInfo>();
111 AU.addRequired<MachineLoopInfo>();
114 bool AsmPrinter::doInitialization(Module &M) {
115 // Initialize TargetLoweringObjectFile.
116 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
117 .Initialize(OutContext, TM);
119 Mang = new Mangler(*MAI);
121 // Allow the target to emit any magic that it wants at the start of the file.
122 EmitStartOfAsmFile(M);
124 // Very minimal debug info. It is ignored if we emit actual debug info. If we
125 // don't, this at least helps the user find where a global came from.
126 if (MAI->hasSingleParameterDotFile()) {
128 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
131 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
132 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
133 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
134 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
135 MP->beginAssembly(O, *this, *MAI);
137 if (!M.getModuleInlineAsm().empty())
138 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
139 << M.getModuleInlineAsm()
140 << '\n' << MAI->getCommentString()
141 << " End of file scope inline assembly\n";
143 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
145 MMI->AnalyzeModule(M);
146 DW = getAnalysisIfAvailable<DwarfWriter>();
148 DW->BeginModule(&M, MMI, O, this, MAI);
153 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
154 switch ((GlobalValue::LinkageTypes)Linkage) {
155 case GlobalValue::CommonLinkage:
156 case GlobalValue::LinkOnceAnyLinkage:
157 case GlobalValue::LinkOnceODRLinkage:
158 case GlobalValue::WeakAnyLinkage:
159 case GlobalValue::WeakODRLinkage:
160 case GlobalValue::LinkerPrivateLinkage:
161 if (MAI->getWeakDefDirective() != 0) {
163 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
164 // .weak_definition _foo
165 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
166 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
168 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
169 // FIXME: linkonce should be a section attribute, handled by COFF Section
171 // http://sourceware.org/binutils/docs-2.20/as/Linkonce.html#Linkonce
173 // FIXME: It would be nice to use .linkonce samesize for non-common
178 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
181 case GlobalValue::DLLExportLinkage:
182 case GlobalValue::AppendingLinkage:
183 // FIXME: appending linkage variables should go into a section of
184 // their name or something. For now, just emit them as external.
185 case GlobalValue::ExternalLinkage:
186 // If external or appending, declare as a global symbol.
188 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
190 case GlobalValue::PrivateLinkage:
191 case GlobalValue::InternalLinkage:
194 llvm_unreachable("Unknown linkage type!");
199 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
200 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
201 if (!GV->hasInitializer()) // External globals require no code.
204 // Check to see if this is a special global used by LLVM, if so, emit it.
205 if (EmitSpecialLLVMGlobal(GV))
208 MCSymbol *GVSym = GetGlobalValueSymbol(GV);
209 EmitVisibility(GVSym, GV->getVisibility());
211 if (MAI->hasDotTypeDotSizeDirective())
212 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
214 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
216 const TargetData *TD = TM.getTargetData();
217 unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
218 unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
220 // Handle common and BSS local symbols (.lcomm).
221 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
222 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
225 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
226 /*PrintType=*/false, GV->getParent());
227 OutStreamer.GetCommentOS() << '\n';
230 // Handle common symbols.
231 if (GVKind.isCommon()) {
233 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
237 // Handle local BSS symbols.
238 if (MAI->hasMachoZeroFillDirective()) {
239 const MCSection *TheSection =
240 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
241 // .zerofill __DATA, __bss, _foo, 400, 5
242 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
246 if (MAI->hasLCOMMDirective()) {
248 OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
253 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
255 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
259 const MCSection *TheSection =
260 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
262 // Handle the zerofill directive on darwin, which is a special form of BSS
264 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
266 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
267 // .zerofill __DATA, __common, _foo, 400, 5
268 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
272 OutStreamer.SwitchSection(TheSection);
274 EmitLinkage(GV->getLinkage(), GVSym);
275 EmitAlignment(AlignLog, GV);
278 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
279 /*PrintType=*/false, GV->getParent());
280 OutStreamer.GetCommentOS() << '\n';
282 OutStreamer.EmitLabel(GVSym);
284 EmitGlobalConstant(GV->getInitializer());
286 if (MAI->hasDotTypeDotSizeDirective())
288 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
290 OutStreamer.AddBlankLine();
293 /// EmitFunctionHeader - This method emits the header for the current
295 void AsmPrinter::EmitFunctionHeader() {
296 // Print out constants referenced by the function
299 // Print the 'header' of function.
300 const Function *F = MF->getFunction();
302 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
303 EmitVisibility(CurrentFnSym, F->getVisibility());
305 EmitLinkage(F->getLinkage(), CurrentFnSym);
306 EmitAlignment(MF->getAlignment(), F);
308 if (MAI->hasDotTypeDotSizeDirective())
309 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
312 WriteAsOperand(OutStreamer.GetCommentOS(), F,
313 /*PrintType=*/false, F->getParent());
314 OutStreamer.GetCommentOS() << '\n';
317 // Emit the CurrentFnSym. This is is a virtual function to allow targets to
318 // do their wild and crazy things as required.
319 EmitFunctionEntryLabel();
321 // Add some workaround for linkonce linkage on Cygwin\MinGW.
322 if (MAI->getLinkOnceDirective() != 0 &&
323 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
324 // FIXME: What is this?
325 O << "Lllvm$workaround$fake$stub$" << *CurrentFnSym << ":\n";
327 // Emit pre-function debug and/or EH information.
328 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
329 DW->BeginFunction(MF);
332 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
333 /// function. This can be overridden by targets as required to do custom stuff.
334 void AsmPrinter::EmitFunctionEntryLabel() {
335 OutStreamer.EmitLabel(CurrentFnSym);
339 bool AsmPrinter::doFinalization(Module &M) {
340 // Emit global variables.
341 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
343 EmitGlobalVariable(I);
345 // Emit final debug information.
346 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
349 // If the target wants to know about weak references, print them all.
350 if (MAI->getWeakRefDirective()) {
351 // FIXME: This is not lazy, it would be nice to only print weak references
352 // to stuff that is actually used. Note that doing so would require targets
353 // to notice uses in operands (due to constant exprs etc). This should
354 // happen with the MC stuff eventually.
356 // Print out module-level global variables here.
357 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
359 if (!I->hasExternalWeakLinkage()) continue;
360 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
364 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
365 if (!I->hasExternalWeakLinkage()) continue;
366 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
371 if (MAI->hasSetDirective()) {
372 OutStreamer.AddBlankLine();
373 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
375 MCSymbol *Name = GetGlobalValueSymbol(I);
377 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
378 MCSymbol *Target = GetGlobalValueSymbol(GV);
380 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
381 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
382 else if (I->hasWeakLinkage())
383 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
385 assert(I->hasLocalLinkage() && "Invalid alias linkage");
387 EmitVisibility(Name, I->getVisibility());
389 // Emit the directives as assignments aka .set:
390 OutStreamer.EmitAssignment(Name,
391 MCSymbolRefExpr::Create(Target, OutContext));
395 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
396 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
397 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
398 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
399 MP->finishAssembly(O, *this, *MAI);
401 // If we don't have any trampolines, then we don't require stack memory
402 // to be executable. Some targets have a directive to declare this.
403 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
404 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
405 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
406 OutStreamer.SwitchSection(S);
408 // Allow the target to emit any magic that it wants at the end of the file,
409 // after everything else has gone out.
412 delete Mang; Mang = 0;
415 OutStreamer.Finish();
419 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
421 // Get the function symbol.
422 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
425 LI = &getAnalysis<MachineLoopInfo>();
429 // SectionCPs - Keep track the alignment, constpool entries per Section.
433 SmallVector<unsigned, 4> CPEs;
434 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
438 /// EmitConstantPool - Print to the current output stream assembly
439 /// representations of the constants in the constant pool MCP. This is
440 /// used to print out constants which have been "spilled to memory" by
441 /// the code generator.
443 void AsmPrinter::EmitConstantPool() {
444 const MachineConstantPool *MCP = MF->getConstantPool();
445 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
446 if (CP.empty()) return;
448 // Calculate sections for constant pool entries. We collect entries to go into
449 // the same section together to reduce amount of section switch statements.
450 SmallVector<SectionCPs, 4> CPSections;
451 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
452 const MachineConstantPoolEntry &CPE = CP[i];
453 unsigned Align = CPE.getAlignment();
456 switch (CPE.getRelocationInfo()) {
457 default: llvm_unreachable("Unknown section kind");
458 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
460 Kind = SectionKind::getReadOnlyWithRelLocal();
463 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
464 case 4: Kind = SectionKind::getMergeableConst4(); break;
465 case 8: Kind = SectionKind::getMergeableConst8(); break;
466 case 16: Kind = SectionKind::getMergeableConst16();break;
467 default: Kind = SectionKind::getMergeableConst(); break;
471 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
473 // The number of sections are small, just do a linear search from the
474 // last section to the first.
476 unsigned SecIdx = CPSections.size();
477 while (SecIdx != 0) {
478 if (CPSections[--SecIdx].S == S) {
484 SecIdx = CPSections.size();
485 CPSections.push_back(SectionCPs(S, Align));
488 if (Align > CPSections[SecIdx].Alignment)
489 CPSections[SecIdx].Alignment = Align;
490 CPSections[SecIdx].CPEs.push_back(i);
493 // Now print stuff into the calculated sections.
494 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
495 OutStreamer.SwitchSection(CPSections[i].S);
496 EmitAlignment(Log2_32(CPSections[i].Alignment));
499 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
500 unsigned CPI = CPSections[i].CPEs[j];
501 MachineConstantPoolEntry CPE = CP[CPI];
503 // Emit inter-object padding for alignment.
504 unsigned AlignMask = CPE.getAlignment() - 1;
505 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
506 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
508 const Type *Ty = CPE.getType();
509 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
511 // Emit the label with a comment on it.
513 OutStreamer.GetCommentOS() << "constant pool ";
514 WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
515 MF->getFunction()->getParent());
516 OutStreamer.GetCommentOS() << '\n';
518 OutStreamer.EmitLabel(GetCPISymbol(CPI));
520 if (CPE.isMachineConstantPoolEntry())
521 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
523 EmitGlobalConstant(CPE.Val.ConstVal);
528 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
529 /// by the current function to the current output stream.
531 void AsmPrinter::EmitJumpTableInfo(MachineFunction &MF) {
532 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
533 if (MJTI == 0) return;
534 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
535 if (JT.empty()) return;
537 // Pick the directive to use to print the jump table entries, and switch to
538 // the appropriate section.
539 const Function *F = MF.getFunction();
540 bool JTInDiffSection = false;
541 if (// In PIC mode, we need to emit the jump table to the same section as the
542 // function body itself, otherwise the label differences won't make sense.
543 // FIXME: Need a better predicate for this: what about custom entries?
544 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
545 // We should also do if the section name is NULL or function is declared
546 // in discardable section
547 // FIXME: this isn't the right predicate, should be based on the MCSection
549 F->isWeakForLinker()) {
550 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
553 // Otherwise, drop it in the readonly section.
554 const MCSection *ReadOnlySection =
555 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
556 OutStreamer.SwitchSection(ReadOnlySection);
557 JTInDiffSection = true;
560 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
562 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
563 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
565 // If this jump table was deleted, ignore it.
566 if (JTBBs.empty()) continue;
568 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
569 // .set directive for each unique entry. This reduces the number of
570 // relocations the assembler will generate for the jump table.
571 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
572 MAI->hasSetDirective()) {
573 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
574 const TargetLowering *TLI = TM.getTargetLowering();
575 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(&MF, JTI,
577 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
578 const MachineBasicBlock *MBB = JTBBs[ii];
579 if (!EmittedSets.insert(MBB)) continue;
581 // .set LJTSet, LBB32-base
583 MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
584 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
585 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
589 // On some targets (e.g. Darwin) we want to emit two consequtive labels
590 // before each jump table. The first label is never referenced, but tells
591 // the assembler and linker the extents of the jump table object. The
592 // second label is actually referenced by the code.
593 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
594 // FIXME: This doesn't have to have any specific name, just any randomly
595 // named and numbered 'l' label would work. Simplify GetJTISymbol.
596 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
598 OutStreamer.EmitLabel(GetJTISymbol(JTI));
600 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
601 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
605 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
607 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
608 const MachineBasicBlock *MBB,
609 unsigned UID) const {
610 const MCExpr *Value = 0;
611 switch (MJTI->getEntryKind()) {
612 case MachineJumpTableInfo::EK_Custom32:
613 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
616 case MachineJumpTableInfo::EK_BlockAddress:
617 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
619 Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
621 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
622 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
623 // with a relocation as gp-relative, e.g.:
625 MCSymbol *MBBSym = MBB->getSymbol(OutContext);
626 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
630 case MachineJumpTableInfo::EK_LabelDifference32: {
631 // EK_LabelDifference32 - Each entry is the address of the block minus
632 // the address of the jump table. This is used for PIC jump tables where
633 // gprel32 is not supported. e.g.:
634 // .word LBB123 - LJTI1_2
635 // If the .set directive is supported, this is emitted as:
636 // .set L4_5_set_123, LBB123 - LJTI1_2
637 // .word L4_5_set_123
639 // If we have emitted set directives for the jump table entries, print
640 // them rather than the entries themselves. If we're emitting PIC, then
641 // emit the table entries as differences between two text section labels.
642 if (MAI->hasSetDirective()) {
643 // If we used .set, reference the .set's symbol.
644 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
648 // Otherwise, use the difference as the jump table entry.
649 Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
650 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
651 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
656 assert(Value && "Unknown entry kind!");
658 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
659 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
663 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
664 /// special global used by LLVM. If so, emit it and return true, otherwise
665 /// do nothing and return false.
666 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
667 if (GV->getName() == "llvm.used") {
668 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
669 EmitLLVMUsedList(GV->getInitializer());
673 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
674 if (GV->getSection() == "llvm.metadata" ||
675 GV->hasAvailableExternallyLinkage())
678 if (!GV->hasAppendingLinkage()) return false;
680 assert(GV->hasInitializer() && "Not a special LLVM global!");
682 const TargetData *TD = TM.getTargetData();
683 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
684 if (GV->getName() == "llvm.global_ctors") {
685 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
686 EmitAlignment(Align, 0);
687 EmitXXStructorList(GV->getInitializer());
689 if (TM.getRelocationModel() == Reloc::Static &&
690 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
691 StringRef Sym(".constructors_used");
692 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
698 if (GV->getName() == "llvm.global_dtors") {
699 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
700 EmitAlignment(Align, 0);
701 EmitXXStructorList(GV->getInitializer());
703 if (TM.getRelocationModel() == Reloc::Static &&
704 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
705 StringRef Sym(".destructors_used");
706 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
715 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
716 /// global in the specified llvm.used list for which emitUsedDirectiveFor
717 /// is true, as being used with this directive.
718 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
719 // Should be an array of 'i8*'.
720 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
721 if (InitList == 0) return;
723 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
724 const GlobalValue *GV =
725 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
726 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
727 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(GV),
732 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
733 /// function pointers, ignoring the init priority.
734 void AsmPrinter::EmitXXStructorList(Constant *List) {
735 // Should be an array of '{ int, void ()* }' structs. The first value is the
736 // init priority, which we ignore.
737 if (!isa<ConstantArray>(List)) return;
738 ConstantArray *InitList = cast<ConstantArray>(List);
739 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
740 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
741 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
743 if (CS->getOperand(1)->isNullValue())
744 return; // Found a null terminator, exit printing.
745 // Emit the function pointer.
746 EmitGlobalConstant(CS->getOperand(1));
750 //===--------------------------------------------------------------------===//
751 // Emission and print routines
754 /// EmitInt8 - Emit a byte directive and value.
756 void AsmPrinter::EmitInt8(int Value) const {
757 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
760 /// EmitInt16 - Emit a short directive and value.
762 void AsmPrinter::EmitInt16(int Value) const {
763 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
766 /// EmitInt32 - Emit a long directive and value.
768 void AsmPrinter::EmitInt32(int Value) const {
769 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
772 /// EmitInt64 - Emit a long long directive and value.
774 void AsmPrinter::EmitInt64(uint64_t Value) const {
775 OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
778 //===----------------------------------------------------------------------===//
780 // EmitAlignment - Emit an alignment directive to the specified power of
781 // two boundary. For example, if you pass in 3 here, you will get an 8
782 // byte alignment. If a global value is specified, and if that global has
783 // an explicit alignment requested, it will unconditionally override the
784 // alignment request. However, if ForcedAlignBits is specified, this value
785 // has final say: the ultimate alignment will be the max of ForcedAlignBits
786 // and the alignment computed with NumBits and the global.
790 // if (GV && GV->hasalignment) Align = GV->getalignment();
791 // Align = std::max(Align, ForcedAlignBits);
793 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
794 unsigned ForcedAlignBits,
795 bool UseFillExpr) const {
796 if (GV && GV->getAlignment())
797 NumBits = Log2_32(GV->getAlignment());
798 NumBits = std::max(NumBits, ForcedAlignBits);
800 if (NumBits == 0) return; // No need to emit alignment.
802 unsigned FillValue = 0;
803 if (getCurrentSection()->getKind().isText())
804 FillValue = MAI->getTextAlignFillValue();
806 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
809 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
811 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
812 MCContext &Ctx = AP.OutContext;
814 if (CV->isNullValue() || isa<UndefValue>(CV))
815 return MCConstantExpr::Create(0, Ctx);
817 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
818 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
820 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
821 return MCSymbolRefExpr::Create(AP.GetGlobalValueSymbol(GV), Ctx);
822 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
823 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
825 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
827 llvm_unreachable("Unknown constant value to lower!");
828 return MCConstantExpr::Create(0, Ctx);
831 switch (CE->getOpcode()) {
832 case Instruction::ZExt:
833 case Instruction::SExt:
834 case Instruction::FPTrunc:
835 case Instruction::FPExt:
836 case Instruction::UIToFP:
837 case Instruction::SIToFP:
838 case Instruction::FPToUI:
839 case Instruction::FPToSI:
840 default: llvm_unreachable("FIXME: Don't support this constant cast expr");
841 case Instruction::GetElementPtr: {
842 const TargetData &TD = *AP.TM.getTargetData();
843 // Generate a symbolic expression for the byte address
844 const Constant *PtrVal = CE->getOperand(0);
845 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
846 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
849 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
853 // Truncate/sext the offset to the pointer size.
854 if (TD.getPointerSizeInBits() != 64) {
855 int SExtAmount = 64-TD.getPointerSizeInBits();
856 Offset = (Offset << SExtAmount) >> SExtAmount;
859 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
863 case Instruction::Trunc:
864 // We emit the value and depend on the assembler to truncate the generated
865 // expression properly. This is important for differences between
866 // blockaddress labels. Since the two labels are in the same function, it
867 // is reasonable to treat their delta as a 32-bit value.
869 case Instruction::BitCast:
870 return LowerConstant(CE->getOperand(0), AP);
872 case Instruction::IntToPtr: {
873 const TargetData &TD = *AP.TM.getTargetData();
874 // Handle casts to pointers by changing them into casts to the appropriate
875 // integer type. This promotes constant folding and simplifies this code.
876 Constant *Op = CE->getOperand(0);
877 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
879 return LowerConstant(Op, AP);
882 case Instruction::PtrToInt: {
883 const TargetData &TD = *AP.TM.getTargetData();
884 // Support only foldable casts to/from pointers that can be eliminated by
885 // changing the pointer to the appropriately sized integer type.
886 Constant *Op = CE->getOperand(0);
887 const Type *Ty = CE->getType();
889 const MCExpr *OpExpr = LowerConstant(Op, AP);
891 // We can emit the pointer value into this slot if the slot is an
892 // integer slot equal to the size of the pointer.
893 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
896 // Otherwise the pointer is smaller than the resultant integer, mask off
897 // the high bits so we are sure to get a proper truncation if the input is
899 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
900 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
901 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
904 case Instruction::Add:
905 case Instruction::Sub:
906 case Instruction::And:
907 case Instruction::Or:
908 case Instruction::Xor: {
909 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
910 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
911 switch (CE->getOpcode()) {
912 default: llvm_unreachable("Unknown binary operator constant cast expr");
913 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
914 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
915 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
916 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
917 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
923 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
925 if (AddrSpace != 0 || !CA->isString()) {
926 // Not a string. Print the values in successive locations
927 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
928 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
932 // Otherwise, it can be emitted as .ascii.
933 SmallVector<char, 128> TmpVec;
934 TmpVec.reserve(CA->getNumOperands());
935 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
936 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
938 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
941 static void EmitGlobalConstantVector(const ConstantVector *CV,
942 unsigned AddrSpace, AsmPrinter &AP) {
943 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
944 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
947 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
948 unsigned AddrSpace, AsmPrinter &AP) {
949 // Print the fields in successive locations. Pad to align if needed!
950 const TargetData *TD = AP.TM.getTargetData();
951 unsigned Size = TD->getTypeAllocSize(CS->getType());
952 const StructLayout *Layout = TD->getStructLayout(CS->getType());
953 uint64_t SizeSoFar = 0;
954 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
955 const Constant *Field = CS->getOperand(i);
957 // Check if padding is needed and insert one or more 0s.
958 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
959 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
960 - Layout->getElementOffset(i)) - FieldSize;
961 SizeSoFar += FieldSize + PadSize;
963 // Now print the actual field value.
964 AP.EmitGlobalConstant(Field, AddrSpace);
966 // Insert padding - this may include padding to increase the size of the
967 // current field up to the ABI size (if the struct is not packed) as well
968 // as padding to ensure that the next field starts at the right offset.
969 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
971 assert(SizeSoFar == Layout->getSizeInBytes() &&
972 "Layout of constant struct may be incorrect!");
975 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
977 // FP Constants are printed as integer constants to avoid losing
979 if (CFP->getType()->isDoubleTy()) {
981 double Val = CFP->getValueAPF().convertToDouble();
982 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
985 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
986 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
990 if (CFP->getType()->isFloatTy()) {
992 float Val = CFP->getValueAPF().convertToFloat();
993 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
995 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
996 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1000 if (CFP->getType()->isX86_FP80Ty()) {
1001 // all long double variants are printed as hex
1002 // api needed to prevent premature destruction
1003 APInt API = CFP->getValueAPF().bitcastToAPInt();
1004 const uint64_t *p = API.getRawData();
1005 if (AP.VerboseAsm) {
1006 // Convert to double so we can print the approximate val as a comment.
1007 APFloat DoubleVal = CFP->getValueAPF();
1009 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1011 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1012 << DoubleVal.convertToDouble() << '\n';
1015 if (AP.TM.getTargetData()->isBigEndian()) {
1016 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1017 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1019 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1020 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1023 // Emit the tail padding for the long double.
1024 const TargetData &TD = *AP.TM.getTargetData();
1025 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1026 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1030 assert(CFP->getType()->isPPC_FP128Ty() &&
1031 "Floating point constant type not handled");
1032 // All long double variants are printed as hex api needed to prevent
1033 // premature destruction.
1034 APInt API = CFP->getValueAPF().bitcastToAPInt();
1035 const uint64_t *p = API.getRawData();
1036 if (AP.TM.getTargetData()->isBigEndian()) {
1037 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1038 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1040 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1041 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1045 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1046 unsigned AddrSpace, AsmPrinter &AP) {
1047 const TargetData *TD = AP.TM.getTargetData();
1048 unsigned BitWidth = CI->getBitWidth();
1049 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1051 // We don't expect assemblers to support integer data directives
1052 // for more than 64 bits, so we emit the data in at most 64-bit
1053 // quantities at a time.
1054 const uint64_t *RawData = CI->getValue().getRawData();
1055 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1056 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1057 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1061 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1062 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1063 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1064 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1065 return OutStreamer.EmitZeros(Size, AddrSpace);
1068 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1069 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1076 OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1077 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1080 EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1085 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1086 return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1088 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1089 return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1091 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1092 return EmitGlobalConstantFP(CFP, AddrSpace, *this);
1094 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1095 return EmitGlobalConstantVector(V, AddrSpace, *this);
1097 if (isa<ConstantPointerNull>(CV)) {
1098 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1099 OutStreamer.EmitIntValue(0, Size, AddrSpace);
1103 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1104 // thread the streamer with EmitValue.
1105 OutStreamer.EmitValue(LowerConstant(CV, *this),
1106 TM.getTargetData()->getTypeAllocSize(CV->getType()),
1110 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1111 // Target doesn't support this yet!
1112 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1115 /// PrintSpecial - Print information related to the specified machine instr
1116 /// that is independent of the operand, and may be independent of the instr
1117 /// itself. This can be useful for portably encoding the comment character
1118 /// or other bits of target-specific knowledge into the asmstrings. The
1119 /// syntax used is ${:comment}. Targets can override this to add support
1120 /// for their own strange codes.
1121 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1122 if (!strcmp(Code, "private")) {
1123 O << MAI->getPrivateGlobalPrefix();
1124 } else if (!strcmp(Code, "comment")) {
1126 O << MAI->getCommentString();
1127 } else if (!strcmp(Code, "uid")) {
1128 // Comparing the address of MI isn't sufficient, because machineinstrs may
1129 // be allocated to the same address across functions.
1130 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1132 // If this is a new LastFn instruction, bump the counter.
1133 if (LastMI != MI || LastFn != ThisF) {
1141 raw_string_ostream Msg(msg);
1142 Msg << "Unknown special formatter '" << Code
1143 << "' for machine instr: " << *MI;
1144 llvm_report_error(Msg.str());
1148 /// processDebugLoc - Processes the debug information of each machine
1149 /// instruction's DebugLoc.
1150 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1151 bool BeforePrintingInsn) {
1152 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1153 || !DW->ShouldEmitDwarfDebug())
1155 DebugLoc DL = MI->getDebugLoc();
1158 DILocation CurDLT = MF->getDILocation(DL);
1159 if (CurDLT.getScope().isNull())
1162 if (!BeforePrintingInsn) {
1163 // After printing instruction
1165 } else if (CurDLT.getNode() != PrevDLT) {
1166 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1167 CurDLT.getColumnNumber(),
1168 CurDLT.getScope().getNode());
1171 DW->BeginScope(MI, L);
1172 PrevDLT = CurDLT.getNode();
1177 /// printInlineAsm - This method formats and prints the specified machine
1178 /// instruction that is an inline asm.
1179 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1180 unsigned NumOperands = MI->getNumOperands();
1182 // Count the number of register definitions.
1183 unsigned NumDefs = 0;
1184 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1186 assert(NumDefs != NumOperands-1 && "No asm string?");
1188 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1190 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1191 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1195 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1196 // These are useful to see where empty asm's wound up.
1197 if (AsmStr[0] == 0) {
1198 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1199 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1203 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1205 // The variant of the current asmprinter.
1206 int AsmPrinterVariant = MAI->getAssemblerDialect();
1208 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1209 const char *LastEmitted = AsmStr; // One past the last character emitted.
1211 while (*LastEmitted) {
1212 switch (*LastEmitted) {
1214 // Not a special case, emit the string section literally.
1215 const char *LiteralEnd = LastEmitted+1;
1216 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1217 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1219 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1220 O.write(LastEmitted, LiteralEnd-LastEmitted);
1221 LastEmitted = LiteralEnd;
1225 ++LastEmitted; // Consume newline character.
1226 O << '\n'; // Indent code with newline.
1229 ++LastEmitted; // Consume '$' character.
1233 switch (*LastEmitted) {
1234 default: Done = false; break;
1235 case '$': // $$ -> $
1236 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1238 ++LastEmitted; // Consume second '$' character.
1240 case '(': // $( -> same as GCC's { character.
1241 ++LastEmitted; // Consume '(' character.
1242 if (CurVariant != -1) {
1243 llvm_report_error("Nested variants found in inline asm string: '"
1244 + std::string(AsmStr) + "'");
1246 CurVariant = 0; // We're in the first variant now.
1249 ++LastEmitted; // consume '|' character.
1250 if (CurVariant == -1)
1251 O << '|'; // this is gcc's behavior for | outside a variant
1253 ++CurVariant; // We're in the next variant.
1255 case ')': // $) -> same as GCC's } char.
1256 ++LastEmitted; // consume ')' character.
1257 if (CurVariant == -1)
1258 O << '}'; // this is gcc's behavior for } outside a variant
1265 bool HasCurlyBraces = false;
1266 if (*LastEmitted == '{') { // ${variable}
1267 ++LastEmitted; // Consume '{' character.
1268 HasCurlyBraces = true;
1271 // If we have ${:foo}, then this is not a real operand reference, it is a
1272 // "magic" string reference, just like in .td files. Arrange to call
1274 if (HasCurlyBraces && *LastEmitted == ':') {
1276 const char *StrStart = LastEmitted;
1277 const char *StrEnd = strchr(StrStart, '}');
1279 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1280 + std::string(AsmStr) + "'");
1283 std::string Val(StrStart, StrEnd);
1284 PrintSpecial(MI, Val.c_str());
1285 LastEmitted = StrEnd+1;
1289 const char *IDStart = LastEmitted;
1292 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1293 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1294 llvm_report_error("Bad $ operand number in inline asm string: '"
1295 + std::string(AsmStr) + "'");
1297 LastEmitted = IDEnd;
1299 char Modifier[2] = { 0, 0 };
1301 if (HasCurlyBraces) {
1302 // If we have curly braces, check for a modifier character. This
1303 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1304 if (*LastEmitted == ':') {
1305 ++LastEmitted; // Consume ':' character.
1306 if (*LastEmitted == 0) {
1307 llvm_report_error("Bad ${:} expression in inline asm string: '"
1308 + std::string(AsmStr) + "'");
1311 Modifier[0] = *LastEmitted;
1312 ++LastEmitted; // Consume modifier character.
1315 if (*LastEmitted != '}') {
1316 llvm_report_error("Bad ${} expression in inline asm string: '"
1317 + std::string(AsmStr) + "'");
1319 ++LastEmitted; // Consume '}' character.
1322 if ((unsigned)Val >= NumOperands-1) {
1323 llvm_report_error("Invalid $ operand number in inline asm string: '"
1324 + std::string(AsmStr) + "'");
1327 // Okay, we finally have a value number. Ask the target to print this
1329 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1334 // Scan to find the machine operand number for the operand.
1335 for (; Val; --Val) {
1336 if (OpNo >= MI->getNumOperands()) break;
1337 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1338 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1341 if (OpNo >= MI->getNumOperands()) {
1344 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1345 ++OpNo; // Skip over the ID number.
1347 if (Modifier[0] == 'l') // labels are target independent
1348 O << *MI->getOperand(OpNo).getMBB()->getSymbol(OutContext);
1350 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1351 if ((OpFlags & 7) == 4) {
1352 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1353 Modifier[0] ? Modifier : 0);
1355 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1356 Modifier[0] ? Modifier : 0);
1362 raw_string_ostream Msg(msg);
1363 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1365 llvm_report_error(Msg.str());
1372 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1375 /// printImplicitDef - This method prints the specified machine instruction
1376 /// that is an implicit def.
1377 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1378 if (!VerboseAsm) return;
1379 O.PadToColumn(MAI->getCommentColumn());
1380 O << MAI->getCommentString() << " implicit-def: "
1381 << TRI->getName(MI->getOperand(0).getReg());
1384 void AsmPrinter::printKill(const MachineInstr *MI) const {
1385 if (!VerboseAsm) return;
1386 O.PadToColumn(MAI->getCommentColumn());
1387 O << MAI->getCommentString() << " kill:";
1388 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1389 const MachineOperand &op = MI->getOperand(n);
1390 assert(op.isReg() && "KILL instruction must have only register operands");
1391 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1395 /// printLabel - This method prints a local label used by debug and
1396 /// exception handling tables.
1397 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1398 printLabel(MI->getOperand(0).getImm());
1401 void AsmPrinter::printLabel(unsigned Id) const {
1402 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1405 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1406 /// instruction, using the specified assembler variant. Targets should
1407 /// override this to format as appropriate.
1408 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1409 unsigned AsmVariant, const char *ExtraCode) {
1410 // Target doesn't support this yet!
1414 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1415 unsigned AsmVariant,
1416 const char *ExtraCode) {
1417 // Target doesn't support this yet!
1421 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1422 const char *Suffix) const {
1423 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1426 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1427 const BasicBlock *BB,
1428 const char *Suffix) const {
1429 assert(BB->hasName() &&
1430 "Address of anonymous basic block not supported yet!");
1432 // This code must use the function name itself, and not the function number,
1433 // since it must be possible to generate the label name from within other
1435 SmallString<60> FnName;
1436 Mang->getNameWithPrefix(FnName, F, false);
1438 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1439 SmallString<60> NameResult;
1440 Mang->getNameWithPrefix(NameResult,
1441 StringRef("BA") + Twine((unsigned)FnName.size()) +
1442 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1445 return OutContext.GetOrCreateSymbol(NameResult.str());
1448 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1449 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1450 SmallString<60> Name;
1451 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "CPI"
1452 << getFunctionNumber() << '_' << CPID;
1453 return OutContext.GetOrCreateSymbol(Name.str());
1456 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1457 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1458 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1461 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1462 /// FIXME: privatize to AsmPrinter.
1463 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1464 SmallString<60> Name;
1465 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix()
1466 << getFunctionNumber() << '_' << UID << "_set_" << MBBID;
1467 return OutContext.GetOrCreateSymbol(Name.str());
1470 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1472 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1473 SmallString<60> NameStr;
1474 Mang->getNameWithPrefix(NameStr, GV, false);
1475 return OutContext.GetOrCreateSymbol(NameStr.str());
1478 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1479 /// global value name as its base, with the specified suffix, and where the
1480 /// symbol is forced to have private linkage if ForcePrivate is true.
1481 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1483 bool ForcePrivate) const {
1484 SmallString<60> NameStr;
1485 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1486 NameStr.append(Suffix.begin(), Suffix.end());
1487 return OutContext.GetOrCreateSymbol(NameStr.str());
1490 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1492 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1493 SmallString<60> NameStr;
1494 Mang->getNameWithPrefix(NameStr, Sym);
1495 return OutContext.GetOrCreateSymbol(NameStr.str());
1500 /// PrintParentLoopComment - Print comments about parent loops of this one.
1501 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1502 unsigned FunctionNumber) {
1503 if (Loop == 0) return;
1504 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1505 OS.indent(Loop->getLoopDepth()*2)
1506 << "Parent Loop BB" << FunctionNumber << "_"
1507 << Loop->getHeader()->getNumber()
1508 << " Depth=" << Loop->getLoopDepth() << '\n';
1512 /// PrintChildLoopComment - Print comments about child loops within
1513 /// the loop for this basic block, with nesting.
1514 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1515 unsigned FunctionNumber) {
1516 // Add child loop information
1517 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1518 OS.indent((*CL)->getLoopDepth()*2)
1519 << "Child Loop BB" << FunctionNumber << "_"
1520 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1522 PrintChildLoopComment(OS, *CL, FunctionNumber);
1526 /// EmitComments - Pretty-print comments for basic blocks.
1527 static void PrintBasicBlockLoopComments(const MachineBasicBlock &MBB,
1528 const MachineLoopInfo *LI,
1529 const AsmPrinter &AP) {
1530 // Add loop depth information
1531 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1532 if (Loop == 0) return;
1534 MachineBasicBlock *Header = Loop->getHeader();
1535 assert(Header && "No header for loop");
1537 // If this block is not a loop header, just print out what is the loop header
1539 if (Header != &MBB) {
1540 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1541 Twine(AP.getFunctionNumber())+"_" +
1542 Twine(Loop->getHeader()->getNumber())+
1543 " Depth="+Twine(Loop->getLoopDepth()));
1547 // Otherwise, it is a loop header. Print out information about child and
1549 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1551 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1554 OS.indent(Loop->getLoopDepth()*2-2);
1559 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1561 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1565 /// EmitBasicBlockStart - This method prints the label for the specified
1566 /// MachineBasicBlock, an alignment (if present) and a comment describing
1567 /// it if appropriate.
1568 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1569 // Emit an alignment directive for this block, if needed.
1570 if (unsigned Align = MBB->getAlignment())
1571 EmitAlignment(Log2_32(Align));
1573 // If the block has its address taken, emit a special label to satisfy
1574 // references to the block. This is done so that we don't need to
1575 // remember the number of this label, and so that we can make
1576 // forward references to labels without knowing what their numbers
1578 if (MBB->hasAddressTaken()) {
1579 const BasicBlock *BB = MBB->getBasicBlock();
1581 OutStreamer.AddComment("Address Taken");
1582 OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB));
1585 // Print the main label for the block.
1586 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1588 // NOTE: Want this comment at start of line.
1589 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1590 if (const BasicBlock *BB = MBB->getBasicBlock())
1592 OutStreamer.AddComment("%" + BB->getName());
1594 PrintBasicBlockLoopComments(*MBB, LI, *this);
1595 OutStreamer.AddBlankLine();
1599 if (const BasicBlock *BB = MBB->getBasicBlock())
1601 OutStreamer.AddComment("%" + BB->getName());
1602 PrintBasicBlockLoopComments(*MBB, LI, *this);
1605 OutStreamer.EmitLabel(MBB->getSymbol(OutContext));
1609 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility) const {
1610 MCSymbolAttr Attr = MCSA_Invalid;
1612 switch (Visibility) {
1614 case GlobalValue::HiddenVisibility:
1615 Attr = MAI->getHiddenVisibilityAttr();
1617 case GlobalValue::ProtectedVisibility:
1618 Attr = MAI->getProtectedVisibilityAttr();
1622 if (Attr != MCSA_Invalid)
1623 OutStreamer.EmitSymbolAttribute(Sym, Attr);
1626 void AsmPrinter::printOffset(int64_t Offset) const {
1629 else if (Offset < 0)
1633 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1634 if (!S->usesMetadata())
1637 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1638 if (GCPI != GCMetadataPrinters.end())
1639 return GCPI->second;
1641 const char *Name = S->getName().c_str();
1643 for (GCMetadataPrinterRegistry::iterator
1644 I = GCMetadataPrinterRegistry::begin(),
1645 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1646 if (strcmp(Name, I->getName()) == 0) {
1647 GCMetadataPrinter *GMP = I->instantiate();
1649 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1653 llvm_report_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
1657 /// EmitComments - Pretty-print comments for instructions
1658 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1662 bool Newline = false;
1664 if (!MI.getDebugLoc().isUnknown()) {
1665 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1667 // Print source line info.
1668 O.PadToColumn(MAI->getCommentColumn());
1669 O << MAI->getCommentString() << ' ';
1670 DIScope Scope = DLT.getScope();
1671 // Omit the directory, because it's likely to be long and uninteresting.
1672 if (!Scope.isNull())
1673 O << Scope.getFilename();
1676 O << ':' << DLT.getLineNumber();
1677 if (DLT.getColumnNumber() != 0)
1678 O << ':' << DLT.getColumnNumber();
1682 // Check for spills and reloads
1685 const MachineFrameInfo *FrameInfo =
1686 MI.getParent()->getParent()->getFrameInfo();
1688 // We assume a single instruction only has a spill or reload, not
1690 const MachineMemOperand *MMO;
1691 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1692 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1693 MMO = *MI.memoperands_begin();
1694 if (Newline) O << '\n';
1695 O.PadToColumn(MAI->getCommentColumn());
1696 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1700 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1701 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1702 if (Newline) O << '\n';
1703 O.PadToColumn(MAI->getCommentColumn());
1704 O << MAI->getCommentString() << ' '
1705 << MMO->getSize() << "-byte Folded Reload";
1709 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1710 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1711 MMO = *MI.memoperands_begin();
1712 if (Newline) O << '\n';
1713 O.PadToColumn(MAI->getCommentColumn());
1714 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1718 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1719 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1720 if (Newline) O << '\n';
1721 O.PadToColumn(MAI->getCommentColumn());
1722 O << MAI->getCommentString() << ' '
1723 << MMO->getSize() << "-byte Folded Spill";
1728 // Check for spill-induced copies
1729 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1730 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1731 SrcSubIdx, DstSubIdx)) {
1732 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1733 if (Newline) O << '\n';
1734 O.PadToColumn(MAI->getCommentColumn());
1735 O << MAI->getCommentString() << " Reload Reuse";