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);
311 O << *CurrentFnSym << ':';
313 O.PadToColumn(MAI->getCommentColumn());
314 O << MAI->getCommentString() << ' ';
315 WriteAsOperand(O, F, /*PrintType=*/false, F->getParent());
319 // Add some workaround for linkonce linkage on Cygwin\MinGW.
320 if (MAI->getLinkOnceDirective() != 0 &&
321 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
322 O << "Lllvm$workaround$fake$stub$" << *CurrentFnSym << ":\n";
324 // Emit pre-function debug and/or EH information.
325 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
326 DW->BeginFunction(MF);
332 bool AsmPrinter::doFinalization(Module &M) {
333 // Emit global variables.
334 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
336 EmitGlobalVariable(I);
338 // Emit final debug information.
339 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
342 // If the target wants to know about weak references, print them all.
343 if (MAI->getWeakRefDirective()) {
344 // FIXME: This is not lazy, it would be nice to only print weak references
345 // to stuff that is actually used. Note that doing so would require targets
346 // to notice uses in operands (due to constant exprs etc). This should
347 // happen with the MC stuff eventually.
349 // Print out module-level global variables here.
350 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
352 if (!I->hasExternalWeakLinkage()) continue;
353 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
357 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
358 if (!I->hasExternalWeakLinkage()) continue;
359 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
364 if (MAI->hasSetDirective()) {
365 OutStreamer.AddBlankLine();
366 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
368 MCSymbol *Name = GetGlobalValueSymbol(I);
370 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
371 MCSymbol *Target = GetGlobalValueSymbol(GV);
373 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
374 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
375 else if (I->hasWeakLinkage())
376 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
378 assert(I->hasLocalLinkage() && "Invalid alias linkage");
380 printVisibility(Name, I->getVisibility());
382 // Emit the directives as assignments aka .set:
383 OutStreamer.EmitAssignment(Name,
384 MCSymbolRefExpr::Create(Target, OutContext));
388 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
389 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
390 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
391 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
392 MP->finishAssembly(O, *this, *MAI);
394 // If we don't have any trampolines, then we don't require stack memory
395 // to be executable. Some targets have a directive to declare this.
396 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
397 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
398 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
399 OutStreamer.SwitchSection(S);
401 // Allow the target to emit any magic that it wants at the end of the file,
402 // after everything else has gone out.
405 delete Mang; Mang = 0;
408 OutStreamer.Finish();
412 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
414 // Get the function symbol.
415 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
418 LI = &getAnalysis<MachineLoopInfo>();
422 // SectionCPs - Keep track the alignment, constpool entries per Section.
426 SmallVector<unsigned, 4> CPEs;
427 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
431 /// EmitConstantPool - Print to the current output stream assembly
432 /// representations of the constants in the constant pool MCP. This is
433 /// used to print out constants which have been "spilled to memory" by
434 /// the code generator.
436 void AsmPrinter::EmitConstantPool(const MachineConstantPool *MCP) {
437 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
438 if (CP.empty()) return;
440 // Calculate sections for constant pool entries. We collect entries to go into
441 // the same section together to reduce amount of section switch statements.
442 SmallVector<SectionCPs, 4> CPSections;
443 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
444 const MachineConstantPoolEntry &CPE = CP[i];
445 unsigned Align = CPE.getAlignment();
448 switch (CPE.getRelocationInfo()) {
449 default: llvm_unreachable("Unknown section kind");
450 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
452 Kind = SectionKind::getReadOnlyWithRelLocal();
455 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
456 case 4: Kind = SectionKind::getMergeableConst4(); break;
457 case 8: Kind = SectionKind::getMergeableConst8(); break;
458 case 16: Kind = SectionKind::getMergeableConst16();break;
459 default: Kind = SectionKind::getMergeableConst(); break;
463 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
465 // The number of sections are small, just do a linear search from the
466 // last section to the first.
468 unsigned SecIdx = CPSections.size();
469 while (SecIdx != 0) {
470 if (CPSections[--SecIdx].S == S) {
476 SecIdx = CPSections.size();
477 CPSections.push_back(SectionCPs(S, Align));
480 if (Align > CPSections[SecIdx].Alignment)
481 CPSections[SecIdx].Alignment = Align;
482 CPSections[SecIdx].CPEs.push_back(i);
485 // Now print stuff into the calculated sections.
486 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
487 OutStreamer.SwitchSection(CPSections[i].S);
488 EmitAlignment(Log2_32(CPSections[i].Alignment));
491 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
492 unsigned CPI = CPSections[i].CPEs[j];
493 MachineConstantPoolEntry CPE = CP[CPI];
495 // Emit inter-object padding for alignment.
496 unsigned AlignMask = CPE.getAlignment() - 1;
497 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
498 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
500 const Type *Ty = CPE.getType();
501 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
503 // Emit the label with a comment on it.
505 OutStreamer.GetCommentOS() << "constant pool ";
506 WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
507 MF->getFunction()->getParent());
508 OutStreamer.GetCommentOS() << '\n';
510 OutStreamer.EmitLabel(GetCPISymbol(CPI));
512 if (CPE.isMachineConstantPoolEntry())
513 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
515 EmitGlobalConstant(CPE.Val.ConstVal);
520 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
521 /// by the current function to the current output stream.
523 void AsmPrinter::EmitJumpTableInfo(MachineFunction &MF) {
524 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
525 if (MJTI == 0) return;
526 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
527 if (JT.empty()) return;
529 // Pick the directive to use to print the jump table entries, and switch to
530 // the appropriate section.
531 const Function *F = MF.getFunction();
532 bool JTInDiffSection = false;
533 if (// In PIC mode, we need to emit the jump table to the same section as the
534 // function body itself, otherwise the label differences won't make sense.
535 // FIXME: Need a better predicate for this: what about custom entries?
536 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
537 // We should also do if the section name is NULL or function is declared
538 // in discardable section
539 // FIXME: this isn't the right predicate, should be based on the MCSection
541 F->isWeakForLinker()) {
542 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
545 // Otherwise, drop it in the readonly section.
546 const MCSection *ReadOnlySection =
547 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
548 OutStreamer.SwitchSection(ReadOnlySection);
549 JTInDiffSection = true;
552 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
554 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
555 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
557 // If this jump table was deleted, ignore it.
558 if (JTBBs.empty()) continue;
560 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
561 // .set directive for each unique entry. This reduces the number of
562 // relocations the assembler will generate for the jump table.
563 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
564 MAI->hasSetDirective()) {
565 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
566 const TargetLowering *TLI = TM.getTargetLowering();
567 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(&MF, JTI,
569 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
570 const MachineBasicBlock *MBB = JTBBs[ii];
571 if (!EmittedSets.insert(MBB)) continue;
573 // .set LJTSet, LBB32-base
575 MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
576 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
577 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
581 // On some targets (e.g. Darwin) we want to emit two consequtive labels
582 // before each jump table. The first label is never referenced, but tells
583 // the assembler and linker the extents of the jump table object. The
584 // second label is actually referenced by the code.
585 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
586 // FIXME: This doesn't have to have any specific name, just any randomly
587 // named and numbered 'l' label would work. Simplify GetJTISymbol.
588 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
590 OutStreamer.EmitLabel(GetJTISymbol(JTI));
592 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
593 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
597 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
599 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
600 const MachineBasicBlock *MBB,
601 unsigned UID) const {
602 const MCExpr *Value = 0;
603 switch (MJTI->getEntryKind()) {
604 case MachineJumpTableInfo::EK_Custom32:
605 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
608 case MachineJumpTableInfo::EK_BlockAddress:
609 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
611 Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
613 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
614 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
615 // with a relocation as gp-relative, e.g.:
617 MCSymbol *MBBSym = MBB->getSymbol(OutContext);
618 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
622 case MachineJumpTableInfo::EK_LabelDifference32: {
623 // EK_LabelDifference32 - Each entry is the address of the block minus
624 // the address of the jump table. This is used for PIC jump tables where
625 // gprel32 is not supported. e.g.:
626 // .word LBB123 - LJTI1_2
627 // If the .set directive is supported, this is emitted as:
628 // .set L4_5_set_123, LBB123 - LJTI1_2
629 // .word L4_5_set_123
631 // If we have emitted set directives for the jump table entries, print
632 // them rather than the entries themselves. If we're emitting PIC, then
633 // emit the table entries as differences between two text section labels.
634 if (MAI->hasSetDirective()) {
635 // If we used .set, reference the .set's symbol.
636 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
640 // Otherwise, use the difference as the jump table entry.
641 Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
642 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
643 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
648 assert(Value && "Unknown entry kind!");
650 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
651 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
655 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
656 /// special global used by LLVM. If so, emit it and return true, otherwise
657 /// do nothing and return false.
658 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
659 if (GV->getName() == "llvm.used") {
660 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
661 EmitLLVMUsedList(GV->getInitializer());
665 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
666 if (GV->getSection() == "llvm.metadata" ||
667 GV->hasAvailableExternallyLinkage())
670 if (!GV->hasAppendingLinkage()) return false;
672 assert(GV->hasInitializer() && "Not a special LLVM global!");
674 const TargetData *TD = TM.getTargetData();
675 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
676 if (GV->getName() == "llvm.global_ctors") {
677 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
678 EmitAlignment(Align, 0);
679 EmitXXStructorList(GV->getInitializer());
681 if (TM.getRelocationModel() == Reloc::Static &&
682 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
683 StringRef Sym(".constructors_used");
684 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
690 if (GV->getName() == "llvm.global_dtors") {
691 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
692 EmitAlignment(Align, 0);
693 EmitXXStructorList(GV->getInitializer());
695 if (TM.getRelocationModel() == Reloc::Static &&
696 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
697 StringRef Sym(".destructors_used");
698 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
707 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
708 /// global in the specified llvm.used list for which emitUsedDirectiveFor
709 /// is true, as being used with this directive.
710 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
711 // Should be an array of 'i8*'.
712 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
713 if (InitList == 0) return;
715 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
716 const GlobalValue *GV =
717 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
718 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
719 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(GV),
724 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
725 /// function pointers, ignoring the init priority.
726 void AsmPrinter::EmitXXStructorList(Constant *List) {
727 // Should be an array of '{ int, void ()* }' structs. The first value is the
728 // init priority, which we ignore.
729 if (!isa<ConstantArray>(List)) return;
730 ConstantArray *InitList = cast<ConstantArray>(List);
731 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
732 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
733 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
735 if (CS->getOperand(1)->isNullValue())
736 return; // Found a null terminator, exit printing.
737 // Emit the function pointer.
738 EmitGlobalConstant(CS->getOperand(1));
742 //===--------------------------------------------------------------------===//
743 // Emission and print routines
746 /// EmitInt8 - Emit a byte directive and value.
748 void AsmPrinter::EmitInt8(int Value) const {
749 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
752 /// EmitInt16 - Emit a short directive and value.
754 void AsmPrinter::EmitInt16(int Value) const {
755 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
758 /// EmitInt32 - Emit a long directive and value.
760 void AsmPrinter::EmitInt32(int Value) const {
761 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
764 /// EmitInt64 - Emit a long long directive and value.
766 void AsmPrinter::EmitInt64(uint64_t Value) const {
767 OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
770 //===----------------------------------------------------------------------===//
772 // EmitAlignment - Emit an alignment directive to the specified power of
773 // two boundary. For example, if you pass in 3 here, you will get an 8
774 // byte alignment. If a global value is specified, and if that global has
775 // an explicit alignment requested, it will unconditionally override the
776 // alignment request. However, if ForcedAlignBits is specified, this value
777 // has final say: the ultimate alignment will be the max of ForcedAlignBits
778 // and the alignment computed with NumBits and the global.
782 // if (GV && GV->hasalignment) Align = GV->getalignment();
783 // Align = std::max(Align, ForcedAlignBits);
785 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
786 unsigned ForcedAlignBits,
787 bool UseFillExpr) const {
788 if (GV && GV->getAlignment())
789 NumBits = Log2_32(GV->getAlignment());
790 NumBits = std::max(NumBits, ForcedAlignBits);
792 if (NumBits == 0) return; // No need to emit alignment.
794 unsigned FillValue = 0;
795 if (getCurrentSection()->getKind().isText())
796 FillValue = MAI->getTextAlignFillValue();
798 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
801 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
803 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
804 MCContext &Ctx = AP.OutContext;
806 if (CV->isNullValue() || isa<UndefValue>(CV))
807 return MCConstantExpr::Create(0, Ctx);
809 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
810 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
812 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
813 return MCSymbolRefExpr::Create(AP.GetGlobalValueSymbol(GV), Ctx);
814 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
815 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
817 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
819 llvm_unreachable("Unknown constant value to lower!");
820 return MCConstantExpr::Create(0, Ctx);
823 switch (CE->getOpcode()) {
824 case Instruction::ZExt:
825 case Instruction::SExt:
826 case Instruction::FPTrunc:
827 case Instruction::FPExt:
828 case Instruction::UIToFP:
829 case Instruction::SIToFP:
830 case Instruction::FPToUI:
831 case Instruction::FPToSI:
832 default: llvm_unreachable("FIXME: Don't support this constant cast expr");
833 case Instruction::GetElementPtr: {
834 const TargetData &TD = *AP.TM.getTargetData();
835 // Generate a symbolic expression for the byte address
836 const Constant *PtrVal = CE->getOperand(0);
837 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
838 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
841 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
845 // Truncate/sext the offset to the pointer size.
846 if (TD.getPointerSizeInBits() != 64) {
847 int SExtAmount = 64-TD.getPointerSizeInBits();
848 Offset = (Offset << SExtAmount) >> SExtAmount;
851 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
855 case Instruction::Trunc:
856 // We emit the value and depend on the assembler to truncate the generated
857 // expression properly. This is important for differences between
858 // blockaddress labels. Since the two labels are in the same function, it
859 // is reasonable to treat their delta as a 32-bit value.
861 case Instruction::BitCast:
862 return LowerConstant(CE->getOperand(0), AP);
864 case Instruction::IntToPtr: {
865 const TargetData &TD = *AP.TM.getTargetData();
866 // Handle casts to pointers by changing them into casts to the appropriate
867 // integer type. This promotes constant folding and simplifies this code.
868 Constant *Op = CE->getOperand(0);
869 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
871 return LowerConstant(Op, AP);
874 case Instruction::PtrToInt: {
875 const TargetData &TD = *AP.TM.getTargetData();
876 // Support only foldable casts to/from pointers that can be eliminated by
877 // changing the pointer to the appropriately sized integer type.
878 Constant *Op = CE->getOperand(0);
879 const Type *Ty = CE->getType();
881 const MCExpr *OpExpr = LowerConstant(Op, AP);
883 // We can emit the pointer value into this slot if the slot is an
884 // integer slot equal to the size of the pointer.
885 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
888 // Otherwise the pointer is smaller than the resultant integer, mask off
889 // the high bits so we are sure to get a proper truncation if the input is
891 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
892 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
893 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
896 case Instruction::Add:
897 case Instruction::Sub:
898 case Instruction::And:
899 case Instruction::Or:
900 case Instruction::Xor: {
901 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
902 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
903 switch (CE->getOpcode()) {
904 default: llvm_unreachable("Unknown binary operator constant cast expr");
905 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
906 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
907 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
908 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
909 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
915 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
917 if (AddrSpace != 0 || !CA->isString()) {
918 // Not a string. Print the values in successive locations
919 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
920 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
924 // Otherwise, it can be emitted as .ascii.
925 SmallVector<char, 128> TmpVec;
926 TmpVec.reserve(CA->getNumOperands());
927 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
928 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
930 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
933 static void EmitGlobalConstantVector(const ConstantVector *CV,
934 unsigned AddrSpace, AsmPrinter &AP) {
935 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
936 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
939 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
940 unsigned AddrSpace, AsmPrinter &AP) {
941 // Print the fields in successive locations. Pad to align if needed!
942 const TargetData *TD = AP.TM.getTargetData();
943 unsigned Size = TD->getTypeAllocSize(CS->getType());
944 const StructLayout *Layout = TD->getStructLayout(CS->getType());
945 uint64_t SizeSoFar = 0;
946 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
947 const Constant *Field = CS->getOperand(i);
949 // Check if padding is needed and insert one or more 0s.
950 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
951 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
952 - Layout->getElementOffset(i)) - FieldSize;
953 SizeSoFar += FieldSize + PadSize;
955 // Now print the actual field value.
956 AP.EmitGlobalConstant(Field, AddrSpace);
958 // Insert padding - this may include padding to increase the size of the
959 // current field up to the ABI size (if the struct is not packed) as well
960 // as padding to ensure that the next field starts at the right offset.
961 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
963 assert(SizeSoFar == Layout->getSizeInBytes() &&
964 "Layout of constant struct may be incorrect!");
967 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
969 // FP Constants are printed as integer constants to avoid losing
971 if (CFP->getType()->isDoubleTy()) {
973 double Val = CFP->getValueAPF().convertToDouble();
974 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
977 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
978 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
982 if (CFP->getType()->isFloatTy()) {
984 float Val = CFP->getValueAPF().convertToFloat();
985 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
987 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
988 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
992 if (CFP->getType()->isX86_FP80Ty()) {
993 // all long double variants are printed as hex
994 // api needed to prevent premature destruction
995 APInt API = CFP->getValueAPF().bitcastToAPInt();
996 const uint64_t *p = API.getRawData();
998 // Convert to double so we can print the approximate val as a comment.
999 APFloat DoubleVal = CFP->getValueAPF();
1001 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1003 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1004 << DoubleVal.convertToDouble() << '\n';
1007 if (AP.TM.getTargetData()->isBigEndian()) {
1008 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1009 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1011 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1012 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1015 // Emit the tail padding for the long double.
1016 const TargetData &TD = *AP.TM.getTargetData();
1017 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1018 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1022 assert(CFP->getType()->isPPC_FP128Ty() &&
1023 "Floating point constant type not handled");
1024 // All long double variants are printed as hex api needed to prevent
1025 // premature destruction.
1026 APInt API = CFP->getValueAPF().bitcastToAPInt();
1027 const uint64_t *p = API.getRawData();
1028 if (AP.TM.getTargetData()->isBigEndian()) {
1029 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1030 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1032 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1033 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1037 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1038 unsigned AddrSpace, AsmPrinter &AP) {
1039 const TargetData *TD = AP.TM.getTargetData();
1040 unsigned BitWidth = CI->getBitWidth();
1041 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1043 // We don't expect assemblers to support integer data directives
1044 // for more than 64 bits, so we emit the data in at most 64-bit
1045 // quantities at a time.
1046 const uint64_t *RawData = CI->getValue().getRawData();
1047 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1048 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1049 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1053 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1054 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1055 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1056 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1057 return OutStreamer.EmitZeros(Size, AddrSpace);
1060 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1061 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1068 OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1069 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1072 EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1077 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1078 return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1080 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1081 return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1083 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1084 return EmitGlobalConstantFP(CFP, AddrSpace, *this);
1086 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1087 return EmitGlobalConstantVector(V, AddrSpace, *this);
1089 if (isa<ConstantPointerNull>(CV)) {
1090 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1091 OutStreamer.EmitIntValue(0, Size, AddrSpace);
1095 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1096 // thread the streamer with EmitValue.
1097 OutStreamer.EmitValue(LowerConstant(CV, *this),
1098 TM.getTargetData()->getTypeAllocSize(CV->getType()),
1102 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1103 // Target doesn't support this yet!
1104 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1107 /// PrintSpecial - Print information related to the specified machine instr
1108 /// that is independent of the operand, and may be independent of the instr
1109 /// itself. This can be useful for portably encoding the comment character
1110 /// or other bits of target-specific knowledge into the asmstrings. The
1111 /// syntax used is ${:comment}. Targets can override this to add support
1112 /// for their own strange codes.
1113 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1114 if (!strcmp(Code, "private")) {
1115 O << MAI->getPrivateGlobalPrefix();
1116 } else if (!strcmp(Code, "comment")) {
1118 O << MAI->getCommentString();
1119 } else if (!strcmp(Code, "uid")) {
1120 // Comparing the address of MI isn't sufficient, because machineinstrs may
1121 // be allocated to the same address across functions.
1122 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1124 // If this is a new LastFn instruction, bump the counter.
1125 if (LastMI != MI || LastFn != ThisF) {
1133 raw_string_ostream Msg(msg);
1134 Msg << "Unknown special formatter '" << Code
1135 << "' for machine instr: " << *MI;
1136 llvm_report_error(Msg.str());
1140 /// processDebugLoc - Processes the debug information of each machine
1141 /// instruction's DebugLoc.
1142 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1143 bool BeforePrintingInsn) {
1144 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1145 || !DW->ShouldEmitDwarfDebug())
1147 DebugLoc DL = MI->getDebugLoc();
1150 DILocation CurDLT = MF->getDILocation(DL);
1151 if (CurDLT.getScope().isNull())
1154 if (!BeforePrintingInsn) {
1155 // After printing instruction
1157 } else if (CurDLT.getNode() != PrevDLT) {
1158 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1159 CurDLT.getColumnNumber(),
1160 CurDLT.getScope().getNode());
1163 DW->BeginScope(MI, L);
1164 PrevDLT = CurDLT.getNode();
1169 /// printInlineAsm - This method formats and prints the specified machine
1170 /// instruction that is an inline asm.
1171 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1172 unsigned NumOperands = MI->getNumOperands();
1174 // Count the number of register definitions.
1175 unsigned NumDefs = 0;
1176 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1178 assert(NumDefs != NumOperands-1 && "No asm string?");
1180 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1182 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1183 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1187 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1188 // These are useful to see where empty asm's wound up.
1189 if (AsmStr[0] == 0) {
1190 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1191 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1195 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1197 // The variant of the current asmprinter.
1198 int AsmPrinterVariant = MAI->getAssemblerDialect();
1200 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1201 const char *LastEmitted = AsmStr; // One past the last character emitted.
1203 while (*LastEmitted) {
1204 switch (*LastEmitted) {
1206 // Not a special case, emit the string section literally.
1207 const char *LiteralEnd = LastEmitted+1;
1208 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1209 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1211 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1212 O.write(LastEmitted, LiteralEnd-LastEmitted);
1213 LastEmitted = LiteralEnd;
1217 ++LastEmitted; // Consume newline character.
1218 O << '\n'; // Indent code with newline.
1221 ++LastEmitted; // Consume '$' character.
1225 switch (*LastEmitted) {
1226 default: Done = false; break;
1227 case '$': // $$ -> $
1228 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1230 ++LastEmitted; // Consume second '$' character.
1232 case '(': // $( -> same as GCC's { character.
1233 ++LastEmitted; // Consume '(' character.
1234 if (CurVariant != -1) {
1235 llvm_report_error("Nested variants found in inline asm string: '"
1236 + std::string(AsmStr) + "'");
1238 CurVariant = 0; // We're in the first variant now.
1241 ++LastEmitted; // consume '|' character.
1242 if (CurVariant == -1)
1243 O << '|'; // this is gcc's behavior for | outside a variant
1245 ++CurVariant; // We're in the next variant.
1247 case ')': // $) -> same as GCC's } char.
1248 ++LastEmitted; // consume ')' character.
1249 if (CurVariant == -1)
1250 O << '}'; // this is gcc's behavior for } outside a variant
1257 bool HasCurlyBraces = false;
1258 if (*LastEmitted == '{') { // ${variable}
1259 ++LastEmitted; // Consume '{' character.
1260 HasCurlyBraces = true;
1263 // If we have ${:foo}, then this is not a real operand reference, it is a
1264 // "magic" string reference, just like in .td files. Arrange to call
1266 if (HasCurlyBraces && *LastEmitted == ':') {
1268 const char *StrStart = LastEmitted;
1269 const char *StrEnd = strchr(StrStart, '}');
1271 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1272 + std::string(AsmStr) + "'");
1275 std::string Val(StrStart, StrEnd);
1276 PrintSpecial(MI, Val.c_str());
1277 LastEmitted = StrEnd+1;
1281 const char *IDStart = LastEmitted;
1284 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1285 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1286 llvm_report_error("Bad $ operand number in inline asm string: '"
1287 + std::string(AsmStr) + "'");
1289 LastEmitted = IDEnd;
1291 char Modifier[2] = { 0, 0 };
1293 if (HasCurlyBraces) {
1294 // If we have curly braces, check for a modifier character. This
1295 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1296 if (*LastEmitted == ':') {
1297 ++LastEmitted; // Consume ':' character.
1298 if (*LastEmitted == 0) {
1299 llvm_report_error("Bad ${:} expression in inline asm string: '"
1300 + std::string(AsmStr) + "'");
1303 Modifier[0] = *LastEmitted;
1304 ++LastEmitted; // Consume modifier character.
1307 if (*LastEmitted != '}') {
1308 llvm_report_error("Bad ${} expression in inline asm string: '"
1309 + std::string(AsmStr) + "'");
1311 ++LastEmitted; // Consume '}' character.
1314 if ((unsigned)Val >= NumOperands-1) {
1315 llvm_report_error("Invalid $ operand number in inline asm string: '"
1316 + std::string(AsmStr) + "'");
1319 // Okay, we finally have a value number. Ask the target to print this
1321 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1326 // Scan to find the machine operand number for the operand.
1327 for (; Val; --Val) {
1328 if (OpNo >= MI->getNumOperands()) break;
1329 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1330 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1333 if (OpNo >= MI->getNumOperands()) {
1336 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1337 ++OpNo; // Skip over the ID number.
1339 if (Modifier[0] == 'l') // labels are target independent
1340 O << *MI->getOperand(OpNo).getMBB()->getSymbol(OutContext);
1342 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1343 if ((OpFlags & 7) == 4) {
1344 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1345 Modifier[0] ? Modifier : 0);
1347 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1348 Modifier[0] ? Modifier : 0);
1354 raw_string_ostream Msg(msg);
1355 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1357 llvm_report_error(Msg.str());
1364 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1367 /// printImplicitDef - This method prints the specified machine instruction
1368 /// that is an implicit def.
1369 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1370 if (!VerboseAsm) return;
1371 O.PadToColumn(MAI->getCommentColumn());
1372 O << MAI->getCommentString() << " implicit-def: "
1373 << TRI->getName(MI->getOperand(0).getReg());
1376 void AsmPrinter::printKill(const MachineInstr *MI) const {
1377 if (!VerboseAsm) return;
1378 O.PadToColumn(MAI->getCommentColumn());
1379 O << MAI->getCommentString() << " kill:";
1380 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1381 const MachineOperand &op = MI->getOperand(n);
1382 assert(op.isReg() && "KILL instruction must have only register operands");
1383 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1387 /// printLabel - This method prints a local label used by debug and
1388 /// exception handling tables.
1389 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1390 printLabel(MI->getOperand(0).getImm());
1393 void AsmPrinter::printLabel(unsigned Id) const {
1394 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1397 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1398 /// instruction, using the specified assembler variant. Targets should
1399 /// override this to format as appropriate.
1400 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1401 unsigned AsmVariant, const char *ExtraCode) {
1402 // Target doesn't support this yet!
1406 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1407 unsigned AsmVariant,
1408 const char *ExtraCode) {
1409 // Target doesn't support this yet!
1413 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1414 const char *Suffix) const {
1415 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1418 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1419 const BasicBlock *BB,
1420 const char *Suffix) const {
1421 assert(BB->hasName() &&
1422 "Address of anonymous basic block not supported yet!");
1424 // This code must use the function name itself, and not the function number,
1425 // since it must be possible to generate the label name from within other
1427 SmallString<60> FnName;
1428 Mang->getNameWithPrefix(FnName, F, false);
1430 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1431 SmallString<60> NameResult;
1432 Mang->getNameWithPrefix(NameResult,
1433 StringRef("BA") + Twine((unsigned)FnName.size()) +
1434 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1437 return OutContext.GetOrCreateSymbol(NameResult.str());
1440 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1441 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1442 SmallString<60> Name;
1443 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "CPI"
1444 << getFunctionNumber() << '_' << CPID;
1445 return OutContext.GetOrCreateSymbol(Name.str());
1448 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1449 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1450 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1453 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1454 /// FIXME: privatize to AsmPrinter.
1455 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1456 SmallString<60> Name;
1457 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix()
1458 << getFunctionNumber() << '_' << UID << "_set_" << MBBID;
1459 return OutContext.GetOrCreateSymbol(Name.str());
1462 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1464 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1465 SmallString<60> NameStr;
1466 Mang->getNameWithPrefix(NameStr, GV, false);
1467 return OutContext.GetOrCreateSymbol(NameStr.str());
1470 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1471 /// global value name as its base, with the specified suffix, and where the
1472 /// symbol is forced to have private linkage if ForcePrivate is true.
1473 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1475 bool ForcePrivate) const {
1476 SmallString<60> NameStr;
1477 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1478 NameStr.append(Suffix.begin(), Suffix.end());
1479 return OutContext.GetOrCreateSymbol(NameStr.str());
1482 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1484 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1485 SmallString<60> NameStr;
1486 Mang->getNameWithPrefix(NameStr, Sym);
1487 return OutContext.GetOrCreateSymbol(NameStr.str());
1492 /// PrintParentLoopComment - Print comments about parent loops of this one.
1493 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1494 unsigned FunctionNumber) {
1495 if (Loop == 0) return;
1496 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1497 OS.indent(Loop->getLoopDepth()*2)
1498 << "Parent Loop BB" << FunctionNumber << "_"
1499 << Loop->getHeader()->getNumber()
1500 << " Depth=" << Loop->getLoopDepth() << '\n';
1504 /// PrintChildLoopComment - Print comments about child loops within
1505 /// the loop for this basic block, with nesting.
1506 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1507 unsigned FunctionNumber) {
1508 // Add child loop information
1509 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1510 OS.indent((*CL)->getLoopDepth()*2)
1511 << "Child Loop BB" << FunctionNumber << "_"
1512 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1514 PrintChildLoopComment(OS, *CL, FunctionNumber);
1518 /// EmitComments - Pretty-print comments for basic blocks.
1519 static void PrintBasicBlockLoopComments(const MachineBasicBlock &MBB,
1520 const MachineLoopInfo *LI,
1521 const AsmPrinter &AP) {
1522 // Add loop depth information
1523 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1524 if (Loop == 0) return;
1526 MachineBasicBlock *Header = Loop->getHeader();
1527 assert(Header && "No header for loop");
1529 // If this block is not a loop header, just print out what is the loop header
1531 if (Header != &MBB) {
1532 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1533 Twine(AP.getFunctionNumber())+"_" +
1534 Twine(Loop->getHeader()->getNumber())+
1535 " Depth="+Twine(Loop->getLoopDepth()));
1539 // Otherwise, it is a loop header. Print out information about child and
1541 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1543 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1546 OS.indent(Loop->getLoopDepth()*2-2);
1551 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1553 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1557 /// EmitBasicBlockStart - This method prints the label for the specified
1558 /// MachineBasicBlock, an alignment (if present) and a comment describing
1559 /// it if appropriate.
1560 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1561 // Emit an alignment directive for this block, if needed.
1562 if (unsigned Align = MBB->getAlignment())
1563 EmitAlignment(Log2_32(Align));
1565 // If the block has its address taken, emit a special label to satisfy
1566 // references to the block. This is done so that we don't need to
1567 // remember the number of this label, and so that we can make
1568 // forward references to labels without knowing what their numbers
1570 if (MBB->hasAddressTaken()) {
1571 const BasicBlock *BB = MBB->getBasicBlock();
1573 OutStreamer.AddComment("Address Taken");
1574 OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB));
1577 // Print the main label for the block.
1578 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1580 // NOTE: Want this comment at start of line.
1581 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1582 if (const BasicBlock *BB = MBB->getBasicBlock())
1584 OutStreamer.AddComment("%" + BB->getName());
1586 PrintBasicBlockLoopComments(*MBB, LI, *this);
1587 OutStreamer.AddBlankLine();
1591 if (const BasicBlock *BB = MBB->getBasicBlock())
1593 OutStreamer.AddComment("%" + BB->getName());
1594 PrintBasicBlockLoopComments(*MBB, LI, *this);
1597 OutStreamer.EmitLabel(MBB->getSymbol(OutContext));
1601 void AsmPrinter::printVisibility(MCSymbol *Sym, unsigned Visibility) const {
1602 // FIXME: RENAME TO EmitVisibility.
1603 MCSymbolAttr Attr = MCSA_Invalid;
1605 switch (Visibility) {
1607 case GlobalValue::HiddenVisibility:
1608 Attr = MAI->getHiddenVisibilityAttr();
1610 case GlobalValue::ProtectedVisibility:
1611 Attr = MAI->getProtectedVisibilityAttr();
1615 if (Attr != MCSA_Invalid)
1616 OutStreamer.EmitSymbolAttribute(Sym, Attr);
1619 void AsmPrinter::printOffset(int64_t Offset) const {
1622 else if (Offset < 0)
1626 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1627 if (!S->usesMetadata())
1630 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1631 if (GCPI != GCMetadataPrinters.end())
1632 return GCPI->second;
1634 const char *Name = S->getName().c_str();
1636 for (GCMetadataPrinterRegistry::iterator
1637 I = GCMetadataPrinterRegistry::begin(),
1638 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1639 if (strcmp(Name, I->getName()) == 0) {
1640 GCMetadataPrinter *GMP = I->instantiate();
1642 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1646 llvm_report_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
1650 /// EmitComments - Pretty-print comments for instructions
1651 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1655 bool Newline = false;
1657 if (!MI.getDebugLoc().isUnknown()) {
1658 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1660 // Print source line info.
1661 O.PadToColumn(MAI->getCommentColumn());
1662 O << MAI->getCommentString() << ' ';
1663 DIScope Scope = DLT.getScope();
1664 // Omit the directory, because it's likely to be long and uninteresting.
1665 if (!Scope.isNull())
1666 O << Scope.getFilename();
1669 O << ':' << DLT.getLineNumber();
1670 if (DLT.getColumnNumber() != 0)
1671 O << ':' << DLT.getColumnNumber();
1675 // Check for spills and reloads
1678 const MachineFrameInfo *FrameInfo =
1679 MI.getParent()->getParent()->getFrameInfo();
1681 // We assume a single instruction only has a spill or reload, not
1683 const MachineMemOperand *MMO;
1684 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1685 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1686 MMO = *MI.memoperands_begin();
1687 if (Newline) O << '\n';
1688 O.PadToColumn(MAI->getCommentColumn());
1689 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1693 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1694 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1695 if (Newline) O << '\n';
1696 O.PadToColumn(MAI->getCommentColumn());
1697 O << MAI->getCommentString() << ' '
1698 << MMO->getSize() << "-byte Folded Reload";
1702 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1703 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1704 MMO = *MI.memoperands_begin();
1705 if (Newline) O << '\n';
1706 O.PadToColumn(MAI->getCommentColumn());
1707 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1711 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1712 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1713 if (Newline) O << '\n';
1714 O.PadToColumn(MAI->getCommentColumn());
1715 O << MAI->getCommentString() << ' '
1716 << MMO->getSize() << "-byte Folded Spill";
1721 // Check for spill-induced copies
1722 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1723 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1724 SrcSubIdx, DstSubIdx)) {
1725 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1726 if (Newline) O << '\n';
1727 O.PadToColumn(MAI->getCommentColumn());
1728 O << MAI->getCommentString() << " Reload Reuse";