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) {
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 printVisibility(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
297 EmitConstantPool(MF->getConstantPool());
299 // Print the 'header' of function.
300 const Function *F = MF->getFunction();
302 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
303 printVisibility(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 printVisibility(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(const MachineConstantPool *MCP) {
444 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
445 if (CP.empty()) return;
447 // Calculate sections for constant pool entries. We collect entries to go into
448 // the same section together to reduce amount of section switch statements.
449 SmallVector<SectionCPs, 4> CPSections;
450 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
451 const MachineConstantPoolEntry &CPE = CP[i];
452 unsigned Align = CPE.getAlignment();
455 switch (CPE.getRelocationInfo()) {
456 default: llvm_unreachable("Unknown section kind");
457 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
459 Kind = SectionKind::getReadOnlyWithRelLocal();
462 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
463 case 4: Kind = SectionKind::getMergeableConst4(); break;
464 case 8: Kind = SectionKind::getMergeableConst8(); break;
465 case 16: Kind = SectionKind::getMergeableConst16();break;
466 default: Kind = SectionKind::getMergeableConst(); break;
470 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
472 // The number of sections are small, just do a linear search from the
473 // last section to the first.
475 unsigned SecIdx = CPSections.size();
476 while (SecIdx != 0) {
477 if (CPSections[--SecIdx].S == S) {
483 SecIdx = CPSections.size();
484 CPSections.push_back(SectionCPs(S, Align));
487 if (Align > CPSections[SecIdx].Alignment)
488 CPSections[SecIdx].Alignment = Align;
489 CPSections[SecIdx].CPEs.push_back(i);
492 // Now print stuff into the calculated sections.
493 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
494 OutStreamer.SwitchSection(CPSections[i].S);
495 EmitAlignment(Log2_32(CPSections[i].Alignment));
498 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
499 unsigned CPI = CPSections[i].CPEs[j];
500 MachineConstantPoolEntry CPE = CP[CPI];
502 // Emit inter-object padding for alignment.
503 unsigned AlignMask = CPE.getAlignment() - 1;
504 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
505 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
507 const Type *Ty = CPE.getType();
508 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
510 // Emit the label with a comment on it.
512 OutStreamer.GetCommentOS() << "constant pool ";
513 WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
514 MF->getFunction()->getParent());
515 OutStreamer.GetCommentOS() << '\n';
517 OutStreamer.EmitLabel(GetCPISymbol(CPI));
519 if (CPE.isMachineConstantPoolEntry())
520 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
522 EmitGlobalConstant(CPE.Val.ConstVal);
527 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
528 /// by the current function to the current output stream.
530 void AsmPrinter::EmitJumpTableInfo(MachineFunction &MF) {
531 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
532 if (MJTI == 0) return;
533 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
534 if (JT.empty()) return;
536 // Pick the directive to use to print the jump table entries, and switch to
537 // the appropriate section.
538 const Function *F = MF.getFunction();
539 bool JTInDiffSection = false;
540 if (// In PIC mode, we need to emit the jump table to the same section as the
541 // function body itself, otherwise the label differences won't make sense.
542 // FIXME: Need a better predicate for this: what about custom entries?
543 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
544 // We should also do if the section name is NULL or function is declared
545 // in discardable section
546 // FIXME: this isn't the right predicate, should be based on the MCSection
548 F->isWeakForLinker()) {
549 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
552 // Otherwise, drop it in the readonly section.
553 const MCSection *ReadOnlySection =
554 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
555 OutStreamer.SwitchSection(ReadOnlySection);
556 JTInDiffSection = true;
559 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
561 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
562 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
564 // If this jump table was deleted, ignore it.
565 if (JTBBs.empty()) continue;
567 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
568 // .set directive for each unique entry. This reduces the number of
569 // relocations the assembler will generate for the jump table.
570 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
571 MAI->hasSetDirective()) {
572 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
573 const TargetLowering *TLI = TM.getTargetLowering();
574 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(&MF, JTI,
576 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
577 const MachineBasicBlock *MBB = JTBBs[ii];
578 if (!EmittedSets.insert(MBB)) continue;
580 // .set LJTSet, LBB32-base
582 MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
583 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
584 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
588 // On some targets (e.g. Darwin) we want to emit two consequtive labels
589 // before each jump table. The first label is never referenced, but tells
590 // the assembler and linker the extents of the jump table object. The
591 // second label is actually referenced by the code.
592 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
593 // FIXME: This doesn't have to have any specific name, just any randomly
594 // named and numbered 'l' label would work. Simplify GetJTISymbol.
595 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
597 OutStreamer.EmitLabel(GetJTISymbol(JTI));
599 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
600 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
604 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
606 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
607 const MachineBasicBlock *MBB,
608 unsigned UID) const {
609 const MCExpr *Value = 0;
610 switch (MJTI->getEntryKind()) {
611 case MachineJumpTableInfo::EK_Custom32:
612 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
615 case MachineJumpTableInfo::EK_BlockAddress:
616 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
618 Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
620 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
621 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
622 // with a relocation as gp-relative, e.g.:
624 MCSymbol *MBBSym = MBB->getSymbol(OutContext);
625 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
629 case MachineJumpTableInfo::EK_LabelDifference32: {
630 // EK_LabelDifference32 - Each entry is the address of the block minus
631 // the address of the jump table. This is used for PIC jump tables where
632 // gprel32 is not supported. e.g.:
633 // .word LBB123 - LJTI1_2
634 // If the .set directive is supported, this is emitted as:
635 // .set L4_5_set_123, LBB123 - LJTI1_2
636 // .word L4_5_set_123
638 // If we have emitted set directives for the jump table entries, print
639 // them rather than the entries themselves. If we're emitting PIC, then
640 // emit the table entries as differences between two text section labels.
641 if (MAI->hasSetDirective()) {
642 // If we used .set, reference the .set's symbol.
643 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
647 // Otherwise, use the difference as the jump table entry.
648 Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
649 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
650 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
655 assert(Value && "Unknown entry kind!");
657 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
658 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
662 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
663 /// special global used by LLVM. If so, emit it and return true, otherwise
664 /// do nothing and return false.
665 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
666 if (GV->getName() == "llvm.used") {
667 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
668 EmitLLVMUsedList(GV->getInitializer());
672 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
673 if (GV->getSection() == "llvm.metadata" ||
674 GV->hasAvailableExternallyLinkage())
677 if (!GV->hasAppendingLinkage()) return false;
679 assert(GV->hasInitializer() && "Not a special LLVM global!");
681 const TargetData *TD = TM.getTargetData();
682 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
683 if (GV->getName() == "llvm.global_ctors") {
684 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
685 EmitAlignment(Align, 0);
686 EmitXXStructorList(GV->getInitializer());
688 if (TM.getRelocationModel() == Reloc::Static &&
689 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
690 StringRef Sym(".constructors_used");
691 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
697 if (GV->getName() == "llvm.global_dtors") {
698 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
699 EmitAlignment(Align, 0);
700 EmitXXStructorList(GV->getInitializer());
702 if (TM.getRelocationModel() == Reloc::Static &&
703 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
704 StringRef Sym(".destructors_used");
705 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
714 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
715 /// global in the specified llvm.used list for which emitUsedDirectiveFor
716 /// is true, as being used with this directive.
717 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
718 // Should be an array of 'i8*'.
719 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
720 if (InitList == 0) return;
722 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
723 const GlobalValue *GV =
724 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
725 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
726 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(GV),
731 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
732 /// function pointers, ignoring the init priority.
733 void AsmPrinter::EmitXXStructorList(Constant *List) {
734 // Should be an array of '{ int, void ()* }' structs. The first value is the
735 // init priority, which we ignore.
736 if (!isa<ConstantArray>(List)) return;
737 ConstantArray *InitList = cast<ConstantArray>(List);
738 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
739 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
740 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
742 if (CS->getOperand(1)->isNullValue())
743 return; // Found a null terminator, exit printing.
744 // Emit the function pointer.
745 EmitGlobalConstant(CS->getOperand(1));
749 //===--------------------------------------------------------------------===//
750 // Emission and print routines
753 /// EmitInt8 - Emit a byte directive and value.
755 void AsmPrinter::EmitInt8(int Value) const {
756 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
759 /// EmitInt16 - Emit a short directive and value.
761 void AsmPrinter::EmitInt16(int Value) const {
762 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
765 /// EmitInt32 - Emit a long directive and value.
767 void AsmPrinter::EmitInt32(int Value) const {
768 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
771 /// EmitInt64 - Emit a long long directive and value.
773 void AsmPrinter::EmitInt64(uint64_t Value) const {
774 OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
777 //===----------------------------------------------------------------------===//
779 // EmitAlignment - Emit an alignment directive to the specified power of
780 // two boundary. For example, if you pass in 3 here, you will get an 8
781 // byte alignment. If a global value is specified, and if that global has
782 // an explicit alignment requested, it will unconditionally override the
783 // alignment request. However, if ForcedAlignBits is specified, this value
784 // has final say: the ultimate alignment will be the max of ForcedAlignBits
785 // and the alignment computed with NumBits and the global.
789 // if (GV && GV->hasalignment) Align = GV->getalignment();
790 // Align = std::max(Align, ForcedAlignBits);
792 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
793 unsigned ForcedAlignBits,
794 bool UseFillExpr) const {
795 if (GV && GV->getAlignment())
796 NumBits = Log2_32(GV->getAlignment());
797 NumBits = std::max(NumBits, ForcedAlignBits);
799 if (NumBits == 0) return; // No need to emit alignment.
801 unsigned FillValue = 0;
802 if (getCurrentSection()->getKind().isText())
803 FillValue = MAI->getTextAlignFillValue();
805 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
808 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
810 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
811 MCContext &Ctx = AP.OutContext;
813 if (CV->isNullValue() || isa<UndefValue>(CV))
814 return MCConstantExpr::Create(0, Ctx);
816 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
817 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
819 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
820 return MCSymbolRefExpr::Create(AP.GetGlobalValueSymbol(GV), Ctx);
821 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
822 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
824 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
826 llvm_unreachable("Unknown constant value to lower!");
827 return MCConstantExpr::Create(0, Ctx);
830 switch (CE->getOpcode()) {
831 case Instruction::ZExt:
832 case Instruction::SExt:
833 case Instruction::FPTrunc:
834 case Instruction::FPExt:
835 case Instruction::UIToFP:
836 case Instruction::SIToFP:
837 case Instruction::FPToUI:
838 case Instruction::FPToSI:
839 default: llvm_unreachable("FIXME: Don't support this constant cast expr");
840 case Instruction::GetElementPtr: {
841 const TargetData &TD = *AP.TM.getTargetData();
842 // Generate a symbolic expression for the byte address
843 const Constant *PtrVal = CE->getOperand(0);
844 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
845 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
848 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
852 // Truncate/sext the offset to the pointer size.
853 if (TD.getPointerSizeInBits() != 64) {
854 int SExtAmount = 64-TD.getPointerSizeInBits();
855 Offset = (Offset << SExtAmount) >> SExtAmount;
858 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
862 case Instruction::Trunc:
863 // We emit the value and depend on the assembler to truncate the generated
864 // expression properly. This is important for differences between
865 // blockaddress labels. Since the two labels are in the same function, it
866 // is reasonable to treat their delta as a 32-bit value.
868 case Instruction::BitCast:
869 return LowerConstant(CE->getOperand(0), AP);
871 case Instruction::IntToPtr: {
872 const TargetData &TD = *AP.TM.getTargetData();
873 // Handle casts to pointers by changing them into casts to the appropriate
874 // integer type. This promotes constant folding and simplifies this code.
875 Constant *Op = CE->getOperand(0);
876 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
878 return LowerConstant(Op, AP);
881 case Instruction::PtrToInt: {
882 const TargetData &TD = *AP.TM.getTargetData();
883 // Support only foldable casts to/from pointers that can be eliminated by
884 // changing the pointer to the appropriately sized integer type.
885 Constant *Op = CE->getOperand(0);
886 const Type *Ty = CE->getType();
888 const MCExpr *OpExpr = LowerConstant(Op, AP);
890 // We can emit the pointer value into this slot if the slot is an
891 // integer slot equal to the size of the pointer.
892 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
895 // Otherwise the pointer is smaller than the resultant integer, mask off
896 // the high bits so we are sure to get a proper truncation if the input is
898 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
899 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
900 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
903 case Instruction::Add:
904 case Instruction::Sub:
905 case Instruction::And:
906 case Instruction::Or:
907 case Instruction::Xor: {
908 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
909 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
910 switch (CE->getOpcode()) {
911 default: llvm_unreachable("Unknown binary operator constant cast expr");
912 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
913 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
914 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
915 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
916 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
922 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
924 if (AddrSpace != 0 || !CA->isString()) {
925 // Not a string. Print the values in successive locations
926 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
927 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
931 // Otherwise, it can be emitted as .ascii.
932 SmallVector<char, 128> TmpVec;
933 TmpVec.reserve(CA->getNumOperands());
934 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
935 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
937 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
940 static void EmitGlobalConstantVector(const ConstantVector *CV,
941 unsigned AddrSpace, AsmPrinter &AP) {
942 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
943 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
946 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
947 unsigned AddrSpace, AsmPrinter &AP) {
948 // Print the fields in successive locations. Pad to align if needed!
949 const TargetData *TD = AP.TM.getTargetData();
950 unsigned Size = TD->getTypeAllocSize(CS->getType());
951 const StructLayout *Layout = TD->getStructLayout(CS->getType());
952 uint64_t SizeSoFar = 0;
953 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
954 const Constant *Field = CS->getOperand(i);
956 // Check if padding is needed and insert one or more 0s.
957 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
958 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
959 - Layout->getElementOffset(i)) - FieldSize;
960 SizeSoFar += FieldSize + PadSize;
962 // Now print the actual field value.
963 AP.EmitGlobalConstant(Field, AddrSpace);
965 // Insert padding - this may include padding to increase the size of the
966 // current field up to the ABI size (if the struct is not packed) as well
967 // as padding to ensure that the next field starts at the right offset.
968 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
970 assert(SizeSoFar == Layout->getSizeInBytes() &&
971 "Layout of constant struct may be incorrect!");
974 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
976 // FP Constants are printed as integer constants to avoid losing
978 if (CFP->getType()->isDoubleTy()) {
980 double Val = CFP->getValueAPF().convertToDouble();
981 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
984 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
985 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
989 if (CFP->getType()->isFloatTy()) {
991 float Val = CFP->getValueAPF().convertToFloat();
992 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
994 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
995 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
999 if (CFP->getType()->isX86_FP80Ty()) {
1000 // all long double variants are printed as hex
1001 // api needed to prevent premature destruction
1002 APInt API = CFP->getValueAPF().bitcastToAPInt();
1003 const uint64_t *p = API.getRawData();
1004 if (AP.VerboseAsm) {
1005 // Convert to double so we can print the approximate val as a comment.
1006 APFloat DoubleVal = CFP->getValueAPF();
1008 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1010 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1011 << DoubleVal.convertToDouble() << '\n';
1014 if (AP.TM.getTargetData()->isBigEndian()) {
1015 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1016 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1018 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1019 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1022 // Emit the tail padding for the long double.
1023 const TargetData &TD = *AP.TM.getTargetData();
1024 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1025 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1029 assert(CFP->getType()->isPPC_FP128Ty() &&
1030 "Floating point constant type not handled");
1031 // All long double variants are printed as hex api needed to prevent
1032 // premature destruction.
1033 APInt API = CFP->getValueAPF().bitcastToAPInt();
1034 const uint64_t *p = API.getRawData();
1035 if (AP.TM.getTargetData()->isBigEndian()) {
1036 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1037 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1039 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1040 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1044 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1045 unsigned AddrSpace, AsmPrinter &AP) {
1046 const TargetData *TD = AP.TM.getTargetData();
1047 unsigned BitWidth = CI->getBitWidth();
1048 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1050 // We don't expect assemblers to support integer data directives
1051 // for more than 64 bits, so we emit the data in at most 64-bit
1052 // quantities at a time.
1053 const uint64_t *RawData = CI->getValue().getRawData();
1054 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1055 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1056 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1060 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1061 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1062 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1063 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1064 return OutStreamer.EmitZeros(Size, AddrSpace);
1067 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1068 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1075 OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1076 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1079 EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1084 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1085 return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1087 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1088 return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1090 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1091 return EmitGlobalConstantFP(CFP, AddrSpace, *this);
1093 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1094 return EmitGlobalConstantVector(V, AddrSpace, *this);
1096 if (isa<ConstantPointerNull>(CV)) {
1097 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1098 OutStreamer.EmitIntValue(0, Size, AddrSpace);
1102 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1103 // thread the streamer with EmitValue.
1104 OutStreamer.EmitValue(LowerConstant(CV, *this),
1105 TM.getTargetData()->getTypeAllocSize(CV->getType()),
1109 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1110 // Target doesn't support this yet!
1111 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1114 /// PrintSpecial - Print information related to the specified machine instr
1115 /// that is independent of the operand, and may be independent of the instr
1116 /// itself. This can be useful for portably encoding the comment character
1117 /// or other bits of target-specific knowledge into the asmstrings. The
1118 /// syntax used is ${:comment}. Targets can override this to add support
1119 /// for their own strange codes.
1120 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1121 if (!strcmp(Code, "private")) {
1122 O << MAI->getPrivateGlobalPrefix();
1123 } else if (!strcmp(Code, "comment")) {
1125 O << MAI->getCommentString();
1126 } else if (!strcmp(Code, "uid")) {
1127 // Comparing the address of MI isn't sufficient, because machineinstrs may
1128 // be allocated to the same address across functions.
1129 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1131 // If this is a new LastFn instruction, bump the counter.
1132 if (LastMI != MI || LastFn != ThisF) {
1140 raw_string_ostream Msg(msg);
1141 Msg << "Unknown special formatter '" << Code
1142 << "' for machine instr: " << *MI;
1143 llvm_report_error(Msg.str());
1147 /// processDebugLoc - Processes the debug information of each machine
1148 /// instruction's DebugLoc.
1149 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1150 bool BeforePrintingInsn) {
1151 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1152 || !DW->ShouldEmitDwarfDebug())
1154 DebugLoc DL = MI->getDebugLoc();
1157 DILocation CurDLT = MF->getDILocation(DL);
1158 if (CurDLT.getScope().isNull())
1161 if (!BeforePrintingInsn) {
1162 // After printing instruction
1164 } else if (CurDLT.getNode() != PrevDLT) {
1165 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1166 CurDLT.getColumnNumber(),
1167 CurDLT.getScope().getNode());
1170 DW->BeginScope(MI, L);
1171 PrevDLT = CurDLT.getNode();
1176 /// printInlineAsm - This method formats and prints the specified machine
1177 /// instruction that is an inline asm.
1178 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1179 unsigned NumOperands = MI->getNumOperands();
1181 // Count the number of register definitions.
1182 unsigned NumDefs = 0;
1183 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1185 assert(NumDefs != NumOperands-1 && "No asm string?");
1187 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1189 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1190 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1194 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1195 // These are useful to see where empty asm's wound up.
1196 if (AsmStr[0] == 0) {
1197 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1198 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1202 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1204 // The variant of the current asmprinter.
1205 int AsmPrinterVariant = MAI->getAssemblerDialect();
1207 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1208 const char *LastEmitted = AsmStr; // One past the last character emitted.
1210 while (*LastEmitted) {
1211 switch (*LastEmitted) {
1213 // Not a special case, emit the string section literally.
1214 const char *LiteralEnd = LastEmitted+1;
1215 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1216 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1218 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1219 O.write(LastEmitted, LiteralEnd-LastEmitted);
1220 LastEmitted = LiteralEnd;
1224 ++LastEmitted; // Consume newline character.
1225 O << '\n'; // Indent code with newline.
1228 ++LastEmitted; // Consume '$' character.
1232 switch (*LastEmitted) {
1233 default: Done = false; break;
1234 case '$': // $$ -> $
1235 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1237 ++LastEmitted; // Consume second '$' character.
1239 case '(': // $( -> same as GCC's { character.
1240 ++LastEmitted; // Consume '(' character.
1241 if (CurVariant != -1) {
1242 llvm_report_error("Nested variants found in inline asm string: '"
1243 + std::string(AsmStr) + "'");
1245 CurVariant = 0; // We're in the first variant now.
1248 ++LastEmitted; // consume '|' character.
1249 if (CurVariant == -1)
1250 O << '|'; // this is gcc's behavior for | outside a variant
1252 ++CurVariant; // We're in the next variant.
1254 case ')': // $) -> same as GCC's } char.
1255 ++LastEmitted; // consume ')' character.
1256 if (CurVariant == -1)
1257 O << '}'; // this is gcc's behavior for } outside a variant
1264 bool HasCurlyBraces = false;
1265 if (*LastEmitted == '{') { // ${variable}
1266 ++LastEmitted; // Consume '{' character.
1267 HasCurlyBraces = true;
1270 // If we have ${:foo}, then this is not a real operand reference, it is a
1271 // "magic" string reference, just like in .td files. Arrange to call
1273 if (HasCurlyBraces && *LastEmitted == ':') {
1275 const char *StrStart = LastEmitted;
1276 const char *StrEnd = strchr(StrStart, '}');
1278 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1279 + std::string(AsmStr) + "'");
1282 std::string Val(StrStart, StrEnd);
1283 PrintSpecial(MI, Val.c_str());
1284 LastEmitted = StrEnd+1;
1288 const char *IDStart = LastEmitted;
1291 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1292 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1293 llvm_report_error("Bad $ operand number in inline asm string: '"
1294 + std::string(AsmStr) + "'");
1296 LastEmitted = IDEnd;
1298 char Modifier[2] = { 0, 0 };
1300 if (HasCurlyBraces) {
1301 // If we have curly braces, check for a modifier character. This
1302 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1303 if (*LastEmitted == ':') {
1304 ++LastEmitted; // Consume ':' character.
1305 if (*LastEmitted == 0) {
1306 llvm_report_error("Bad ${:} expression in inline asm string: '"
1307 + std::string(AsmStr) + "'");
1310 Modifier[0] = *LastEmitted;
1311 ++LastEmitted; // Consume modifier character.
1314 if (*LastEmitted != '}') {
1315 llvm_report_error("Bad ${} expression in inline asm string: '"
1316 + std::string(AsmStr) + "'");
1318 ++LastEmitted; // Consume '}' character.
1321 if ((unsigned)Val >= NumOperands-1) {
1322 llvm_report_error("Invalid $ operand number in inline asm string: '"
1323 + std::string(AsmStr) + "'");
1326 // Okay, we finally have a value number. Ask the target to print this
1328 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1333 // Scan to find the machine operand number for the operand.
1334 for (; Val; --Val) {
1335 if (OpNo >= MI->getNumOperands()) break;
1336 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1337 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1340 if (OpNo >= MI->getNumOperands()) {
1343 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1344 ++OpNo; // Skip over the ID number.
1346 if (Modifier[0] == 'l') // labels are target independent
1347 O << *MI->getOperand(OpNo).getMBB()->getSymbol(OutContext);
1349 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1350 if ((OpFlags & 7) == 4) {
1351 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1352 Modifier[0] ? Modifier : 0);
1354 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1355 Modifier[0] ? Modifier : 0);
1361 raw_string_ostream Msg(msg);
1362 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1364 llvm_report_error(Msg.str());
1371 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1374 /// printImplicitDef - This method prints the specified machine instruction
1375 /// that is an implicit def.
1376 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1377 if (!VerboseAsm) return;
1378 O.PadToColumn(MAI->getCommentColumn());
1379 O << MAI->getCommentString() << " implicit-def: "
1380 << TRI->getName(MI->getOperand(0).getReg());
1383 void AsmPrinter::printKill(const MachineInstr *MI) const {
1384 if (!VerboseAsm) return;
1385 O.PadToColumn(MAI->getCommentColumn());
1386 O << MAI->getCommentString() << " kill:";
1387 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1388 const MachineOperand &op = MI->getOperand(n);
1389 assert(op.isReg() && "KILL instruction must have only register operands");
1390 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1394 /// printLabel - This method prints a local label used by debug and
1395 /// exception handling tables.
1396 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1397 printLabel(MI->getOperand(0).getImm());
1400 void AsmPrinter::printLabel(unsigned Id) const {
1401 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1404 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1405 /// instruction, using the specified assembler variant. Targets should
1406 /// override this to format as appropriate.
1407 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1408 unsigned AsmVariant, const char *ExtraCode) {
1409 // Target doesn't support this yet!
1413 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1414 unsigned AsmVariant,
1415 const char *ExtraCode) {
1416 // Target doesn't support this yet!
1420 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1421 const char *Suffix) const {
1422 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1425 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1426 const BasicBlock *BB,
1427 const char *Suffix) const {
1428 assert(BB->hasName() &&
1429 "Address of anonymous basic block not supported yet!");
1431 // This code must use the function name itself, and not the function number,
1432 // since it must be possible to generate the label name from within other
1434 SmallString<60> FnName;
1435 Mang->getNameWithPrefix(FnName, F, false);
1437 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1438 SmallString<60> NameResult;
1439 Mang->getNameWithPrefix(NameResult,
1440 StringRef("BA") + Twine((unsigned)FnName.size()) +
1441 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1444 return OutContext.GetOrCreateSymbol(NameResult.str());
1447 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1448 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1449 SmallString<60> Name;
1450 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "CPI"
1451 << getFunctionNumber() << '_' << CPID;
1452 return OutContext.GetOrCreateSymbol(Name.str());
1455 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1456 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1457 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1460 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1461 /// FIXME: privatize to AsmPrinter.
1462 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1463 SmallString<60> Name;
1464 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix()
1465 << getFunctionNumber() << '_' << UID << "_set_" << MBBID;
1466 return OutContext.GetOrCreateSymbol(Name.str());
1469 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1471 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1472 SmallString<60> NameStr;
1473 Mang->getNameWithPrefix(NameStr, GV, false);
1474 return OutContext.GetOrCreateSymbol(NameStr.str());
1477 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1478 /// global value name as its base, with the specified suffix, and where the
1479 /// symbol is forced to have private linkage if ForcePrivate is true.
1480 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1482 bool ForcePrivate) const {
1483 SmallString<60> NameStr;
1484 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1485 NameStr.append(Suffix.begin(), Suffix.end());
1486 return OutContext.GetOrCreateSymbol(NameStr.str());
1489 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1491 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1492 SmallString<60> NameStr;
1493 Mang->getNameWithPrefix(NameStr, Sym);
1494 return OutContext.GetOrCreateSymbol(NameStr.str());
1499 /// PrintParentLoopComment - Print comments about parent loops of this one.
1500 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1501 unsigned FunctionNumber) {
1502 if (Loop == 0) return;
1503 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1504 OS.indent(Loop->getLoopDepth()*2)
1505 << "Parent Loop BB" << FunctionNumber << "_"
1506 << Loop->getHeader()->getNumber()
1507 << " Depth=" << Loop->getLoopDepth() << '\n';
1511 /// PrintChildLoopComment - Print comments about child loops within
1512 /// the loop for this basic block, with nesting.
1513 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1514 unsigned FunctionNumber) {
1515 // Add child loop information
1516 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1517 OS.indent((*CL)->getLoopDepth()*2)
1518 << "Child Loop BB" << FunctionNumber << "_"
1519 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1521 PrintChildLoopComment(OS, *CL, FunctionNumber);
1525 /// EmitComments - Pretty-print comments for basic blocks.
1526 static void PrintBasicBlockLoopComments(const MachineBasicBlock &MBB,
1527 const MachineLoopInfo *LI,
1528 const AsmPrinter &AP) {
1529 // Add loop depth information
1530 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1531 if (Loop == 0) return;
1533 MachineBasicBlock *Header = Loop->getHeader();
1534 assert(Header && "No header for loop");
1536 // If this block is not a loop header, just print out what is the loop header
1538 if (Header != &MBB) {
1539 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1540 Twine(AP.getFunctionNumber())+"_" +
1541 Twine(Loop->getHeader()->getNumber())+
1542 " Depth="+Twine(Loop->getLoopDepth()));
1546 // Otherwise, it is a loop header. Print out information about child and
1548 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1550 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1553 OS.indent(Loop->getLoopDepth()*2-2);
1558 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1560 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1564 /// EmitBasicBlockStart - This method prints the label for the specified
1565 /// MachineBasicBlock, an alignment (if present) and a comment describing
1566 /// it if appropriate.
1567 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1568 // Emit an alignment directive for this block, if needed.
1569 if (unsigned Align = MBB->getAlignment())
1570 EmitAlignment(Log2_32(Align));
1572 // If the block has its address taken, emit a special label to satisfy
1573 // references to the block. This is done so that we don't need to
1574 // remember the number of this label, and so that we can make
1575 // forward references to labels without knowing what their numbers
1577 if (MBB->hasAddressTaken()) {
1578 const BasicBlock *BB = MBB->getBasicBlock();
1580 OutStreamer.AddComment("Address Taken");
1581 OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB));
1584 // Print the main label for the block.
1585 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1587 // NOTE: Want this comment at start of line.
1588 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1589 if (const BasicBlock *BB = MBB->getBasicBlock())
1591 OutStreamer.AddComment("%" + BB->getName());
1593 PrintBasicBlockLoopComments(*MBB, LI, *this);
1594 OutStreamer.AddBlankLine();
1598 if (const BasicBlock *BB = MBB->getBasicBlock())
1600 OutStreamer.AddComment("%" + BB->getName());
1601 PrintBasicBlockLoopComments(*MBB, LI, *this);
1604 OutStreamer.EmitLabel(MBB->getSymbol(OutContext));
1608 void AsmPrinter::printVisibility(MCSymbol *Sym, unsigned Visibility) const {
1609 // FIXME: RENAME TO EmitVisibility.
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";