1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the AsmPrinter class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "llvm/Assembly/Writer.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/DwarfWriter.h"
20 #include "llvm/CodeGen/GCMetadataPrinter.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/Analysis/DebugInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCInst.h"
30 #include "llvm/MC/MCSection.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/Format.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/Target/Mangler.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetLoweringObjectFile.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/ADT/SmallPtrSet.h"
46 #include "llvm/ADT/SmallString.h"
50 static cl::opt<cl::boolOrDefault>
51 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
52 cl::init(cl::BOU_UNSET));
54 static bool getVerboseAsm(bool VDef) {
57 case cl::BOU_UNSET: return VDef;
58 case cl::BOU_TRUE: return true;
59 case cl::BOU_FALSE: return false;
63 char AsmPrinter::ID = 0;
64 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
65 const MCAsmInfo *T, bool VDef)
66 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
67 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
69 OutContext(*new MCContext()),
70 // FIXME: Pass instprinter to streamer.
71 OutStreamer(*createAsmStreamer(OutContext, O, *T,
72 TM.getTargetData()->isLittleEndian(),
73 getVerboseAsm(VDef), 0)),
75 LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
77 VerboseAsm = getVerboseAsm(VDef);
80 AsmPrinter::~AsmPrinter() {
81 for (gcp_iterator I = GCMetadataPrinters.begin(),
82 E = GCMetadataPrinters.end(); I != E; ++I)
89 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
90 return TM.getTargetLowering()->getObjFileLowering();
93 /// getCurrentSection() - Return the current section we are emitting to.
94 const MCSection *AsmPrinter::getCurrentSection() const {
95 return OutStreamer.getCurrentSection();
99 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
100 AU.setPreservesAll();
101 MachineFunctionPass::getAnalysisUsage(AU);
102 AU.addRequired<GCModuleInfo>();
104 AU.addRequired<MachineLoopInfo>();
107 bool AsmPrinter::doInitialization(Module &M) {
108 // Initialize TargetLoweringObjectFile.
109 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
110 .Initialize(OutContext, TM);
112 Mang = new Mangler(*MAI);
114 // Allow the target to emit any magic that it wants at the start of the file.
115 EmitStartOfAsmFile(M);
117 if (MAI->hasSingleParameterDotFile()) {
118 /* Very minimal debug info. It is ignored if we emit actual
119 debug info. If we don't, this at least helps the user find where
120 a function came from. */
121 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
124 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
125 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
126 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
127 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
128 MP->beginAssembly(O, *this, *MAI);
130 if (!M.getModuleInlineAsm().empty())
131 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
132 << M.getModuleInlineAsm()
133 << '\n' << MAI->getCommentString()
134 << " End of file scope inline assembly\n";
136 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
138 MMI->AnalyzeModule(M);
139 DW = getAnalysisIfAvailable<DwarfWriter>();
141 DW->BeginModule(&M, MMI, O, this, MAI);
146 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
147 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
148 if (!GV->hasInitializer()) // External globals require no code.
151 // Check to see if this is a special global used by LLVM, if so, emit it.
152 if (EmitSpecialLLVMGlobal(GV))
155 MCSymbol *GVSym = GetGlobalValueSymbol(GV);
156 printVisibility(GVSym, GV->getVisibility());
158 if (MAI->hasDotTypeDotSizeDirective()) {
159 O << "\t.type\t" << *GVSym;
160 if (MAI->getCommentString()[0] != '@')
166 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
168 const TargetData *TD = TM.getTargetData();
169 unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
170 unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
172 // Handle common and BSS local symbols (.lcomm).
173 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
174 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
177 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
178 /*PrintType=*/false, GV->getParent());
179 OutStreamer.GetCommentOS() << '\n';
182 // Handle common symbols.
183 if (GVKind.isCommon()) {
185 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
189 // Handle local BSS symbols.
190 if (MAI->hasMachoZeroFillDirective()) {
191 const MCSection *TheSection =
192 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
193 // .zerofill __DATA, __bss, _foo, 400, 5
194 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
198 if (const char *LComm = MAI->getLCOMMDirective()) {
200 O << LComm << *GVSym << ',' << Size;
206 O << "\t.local\t" << *GVSym << '\n';
208 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
212 const MCSection *TheSection =
213 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
215 // Handle the zerofill directive on darwin, which is a special form of BSS
217 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
219 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
220 // .zerofill __DATA, __common, _foo, 400, 5
221 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
225 OutStreamer.SwitchSection(TheSection);
227 // TODO: Factor into an 'emit linkage' thing that is shared with function
229 switch (GV->getLinkage()) {
230 case GlobalValue::CommonLinkage:
231 case GlobalValue::LinkOnceAnyLinkage:
232 case GlobalValue::LinkOnceODRLinkage:
233 case GlobalValue::WeakAnyLinkage:
234 case GlobalValue::WeakODRLinkage:
235 case GlobalValue::LinkerPrivateLinkage:
236 if (MAI->getWeakDefDirective() != 0) {
238 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
239 // .weak_definition _foo
240 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::WeakDefinition);
241 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
243 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
244 // .linkonce same_size
248 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Weak);
251 case GlobalValue::DLLExportLinkage:
252 case GlobalValue::AppendingLinkage:
253 // FIXME: appending linkage variables should go into a section of
254 // their name or something. For now, just emit them as external.
255 case GlobalValue::ExternalLinkage:
256 // If external or appending, declare as a global symbol.
258 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
260 case GlobalValue::PrivateLinkage:
261 case GlobalValue::InternalLinkage:
264 llvm_unreachable("Unknown linkage type!");
267 EmitAlignment(AlignLog, GV);
269 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
270 /*PrintType=*/false, GV->getParent());
271 OutStreamer.GetCommentOS() << '\n';
273 OutStreamer.EmitLabel(GVSym);
275 EmitGlobalConstant(GV->getInitializer());
277 if (MAI->hasDotTypeDotSizeDirective())
278 O << "\t.size\t" << *GVSym << ", " << Size << '\n';
280 OutStreamer.AddBlankLine();
284 bool AsmPrinter::doFinalization(Module &M) {
285 // Emit global variables.
286 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
288 EmitGlobalVariable(I);
290 // Emit final debug information.
291 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
294 // If the target wants to know about weak references, print them all.
295 if (MAI->getWeakRefDirective()) {
296 // FIXME: This is not lazy, it would be nice to only print weak references
297 // to stuff that is actually used. Note that doing so would require targets
298 // to notice uses in operands (due to constant exprs etc). This should
299 // happen with the MC stuff eventually.
301 // Print out module-level global variables here.
302 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
304 if (!I->hasExternalWeakLinkage()) continue;
305 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n';
308 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
309 if (!I->hasExternalWeakLinkage()) continue;
310 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n';
314 if (MAI->getSetDirective()) {
316 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
318 MCSymbol *Name = GetGlobalValueSymbol(I);
320 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
321 MCSymbol *Target = GetGlobalValueSymbol(GV);
323 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
324 O << "\t.globl\t" << *Name << '\n';
325 else if (I->hasWeakLinkage())
326 O << MAI->getWeakRefDirective() << *Name << '\n';
328 assert(I->hasLocalLinkage() && "Invalid alias linkage");
330 printVisibility(Name, I->getVisibility());
332 O << MAI->getSetDirective() << ' ' << *Name << ", " << *Target << '\n';
336 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
337 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
338 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
339 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
340 MP->finishAssembly(O, *this, *MAI);
342 // If we don't have any trampolines, then we don't require stack memory
343 // to be executable. Some targets have a directive to declare this.
344 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
345 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
346 if (MAI->getNonexecutableStackDirective())
347 O << MAI->getNonexecutableStackDirective() << '\n';
350 // Allow the target to emit any magic that it wants at the end of the file,
351 // after everything else has gone out.
354 delete Mang; Mang = 0;
357 OutStreamer.Finish();
361 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
362 // Get the function symbol.
363 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
364 IncrementFunctionNumber();
367 LI = &getAnalysis<MachineLoopInfo>();
371 // SectionCPs - Keep track the alignment, constpool entries per Section.
375 SmallVector<unsigned, 4> CPEs;
376 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
380 /// EmitConstantPool - Print to the current output stream assembly
381 /// representations of the constants in the constant pool MCP. This is
382 /// used to print out constants which have been "spilled to memory" by
383 /// the code generator.
385 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
386 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
387 if (CP.empty()) return;
389 // Calculate sections for constant pool entries. We collect entries to go into
390 // the same section together to reduce amount of section switch statements.
391 SmallVector<SectionCPs, 4> CPSections;
392 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
393 const MachineConstantPoolEntry &CPE = CP[i];
394 unsigned Align = CPE.getAlignment();
397 switch (CPE.getRelocationInfo()) {
398 default: llvm_unreachable("Unknown section kind");
399 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
401 Kind = SectionKind::getReadOnlyWithRelLocal();
404 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
405 case 4: Kind = SectionKind::getMergeableConst4(); break;
406 case 8: Kind = SectionKind::getMergeableConst8(); break;
407 case 16: Kind = SectionKind::getMergeableConst16();break;
408 default: Kind = SectionKind::getMergeableConst(); break;
412 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
414 // The number of sections are small, just do a linear search from the
415 // last section to the first.
417 unsigned SecIdx = CPSections.size();
418 while (SecIdx != 0) {
419 if (CPSections[--SecIdx].S == S) {
425 SecIdx = CPSections.size();
426 CPSections.push_back(SectionCPs(S, Align));
429 if (Align > CPSections[SecIdx].Alignment)
430 CPSections[SecIdx].Alignment = Align;
431 CPSections[SecIdx].CPEs.push_back(i);
434 // Now print stuff into the calculated sections.
435 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
436 OutStreamer.SwitchSection(CPSections[i].S);
437 EmitAlignment(Log2_32(CPSections[i].Alignment));
440 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
441 unsigned CPI = CPSections[i].CPEs[j];
442 MachineConstantPoolEntry CPE = CP[CPI];
444 // Emit inter-object padding for alignment.
445 unsigned AlignMask = CPE.getAlignment() - 1;
446 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
447 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
449 const Type *Ty = CPE.getType();
450 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
452 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
455 O.PadToColumn(MAI->getCommentColumn());
456 O << MAI->getCommentString() << " constant ";
457 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
460 if (CPE.isMachineConstantPoolEntry())
461 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
463 EmitGlobalConstant(CPE.Val.ConstVal);
468 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
469 /// by the current function to the current output stream.
471 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
472 MachineFunction &MF) {
473 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
474 if (JT.empty()) return;
476 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
478 // Pick the directive to use to print the jump table entries, and switch to
479 // the appropriate section.
480 TargetLowering *LoweringInfo = TM.getTargetLowering();
482 const Function *F = MF.getFunction();
483 bool JTInDiffSection = false;
484 if (F->isWeakForLinker() ||
485 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
486 // In PIC mode, we need to emit the jump table to the same section as the
487 // function body itself, otherwise the label differences won't make sense.
488 // We should also do if the section name is NULL or function is declared in
489 // discardable section.
490 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
493 // Otherwise, drop it in the readonly section.
494 const MCSection *ReadOnlySection =
495 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
496 OutStreamer.SwitchSection(ReadOnlySection);
497 JTInDiffSection = true;
500 EmitAlignment(Log2_32(MJTI->getAlignment()));
502 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
503 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
505 // If this jump table was deleted, ignore it.
506 if (JTBBs.empty()) continue;
508 // For PIC codegen, if possible we want to use the SetDirective to reduce
509 // the number of relocations the assembler will generate for the jump table.
510 // Set directives are all printed before the jump table itself.
511 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
512 if (MAI->getSetDirective() && IsPic)
513 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
514 if (EmittedSets.insert(JTBBs[ii]))
515 printPICJumpTableSetLabel(i, JTBBs[ii]);
517 // On some targets (e.g. Darwin) we want to emit two consequtive labels
518 // before each jump table. The first label is never referenced, but tells
519 // the assembler and linker the extents of the jump table object. The
520 // second label is actually referenced by the code.
521 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
522 O << MAI->getLinkerPrivateGlobalPrefix()
523 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
526 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
527 << '_' << i << ":\n";
529 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
530 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
536 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
537 const MachineBasicBlock *MBB,
538 unsigned uid) const {
539 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
541 // Use JumpTableDirective otherwise honor the entry size from the jump table
543 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
544 bool HadJTEntryDirective = JTEntryDirective != NULL;
545 if (!HadJTEntryDirective) {
546 JTEntryDirective = MJTI->getEntrySize() == 4 ?
547 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
550 O << JTEntryDirective << ' ';
552 // If we have emitted set directives for the jump table entries, print
553 // them rather than the entries themselves. If we're emitting PIC, then
554 // emit the table entries as differences between two text section labels.
555 // If we're emitting non-PIC code, then emit the entries as direct
556 // references to the target basic blocks.
558 O << *GetMBBSymbol(MBB->getNumber());
559 } else if (MAI->getSetDirective()) {
560 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
561 << '_' << uid << "_set_" << MBB->getNumber();
563 O << *GetMBBSymbol(MBB->getNumber());
564 // If the arch uses custom Jump Table directives, don't calc relative to
566 if (!HadJTEntryDirective)
567 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
568 << getFunctionNumber() << '_' << uid;
573 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
574 /// special global used by LLVM. If so, emit it and return true, otherwise
575 /// do nothing and return false.
576 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
577 if (GV->getName() == "llvm.used") {
578 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
579 EmitLLVMUsedList(GV->getInitializer());
583 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
584 if (GV->getSection() == "llvm.metadata" ||
585 GV->hasAvailableExternallyLinkage())
588 if (!GV->hasAppendingLinkage()) return false;
590 assert(GV->hasInitializer() && "Not a special LLVM global!");
592 const TargetData *TD = TM.getTargetData();
593 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
594 if (GV->getName() == "llvm.global_ctors") {
595 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
596 EmitAlignment(Align, 0);
597 EmitXXStructorList(GV->getInitializer());
599 if (TM.getRelocationModel() == Reloc::Static &&
600 MAI->hasStaticCtorDtorReferenceInStaticMode())
601 O << ".reference .constructors_used\n";
605 if (GV->getName() == "llvm.global_dtors") {
606 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
607 EmitAlignment(Align, 0);
608 EmitXXStructorList(GV->getInitializer());
610 if (TM.getRelocationModel() == Reloc::Static &&
611 MAI->hasStaticCtorDtorReferenceInStaticMode())
612 O << ".reference .destructors_used\n";
619 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
620 /// global in the specified llvm.used list for which emitUsedDirectiveFor
621 /// is true, as being used with this directive.
622 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
623 const char *Directive = MAI->getUsedDirective();
625 // Should be an array of 'i8*'.
626 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
627 if (InitList == 0) return;
629 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
630 const GlobalValue *GV =
631 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
632 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
634 EmitConstantValueOnly(InitList->getOperand(i));
640 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
641 /// function pointers, ignoring the init priority.
642 void AsmPrinter::EmitXXStructorList(Constant *List) {
643 // Should be an array of '{ int, void ()* }' structs. The first value is the
644 // init priority, which we ignore.
645 if (!isa<ConstantArray>(List)) return;
646 ConstantArray *InitList = cast<ConstantArray>(List);
647 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
648 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
649 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
651 if (CS->getOperand(1)->isNullValue())
652 return; // Found a null terminator, exit printing.
653 // Emit the function pointer.
654 EmitGlobalConstant(CS->getOperand(1));
659 //===----------------------------------------------------------------------===//
660 /// LEB 128 number encoding.
662 /// PrintULEB128 - Print a series of hexadecimal values (separated by commas)
663 /// representing an unsigned leb128 value.
664 void AsmPrinter::PrintULEB128(unsigned Value) const {
666 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
668 if (Value) Byte |= 0x80;
671 if (Value) O << ", ";
676 //===--------------------------------------------------------------------===//
677 // Emission and print routines
680 /// EOL - Print a newline character to asm stream. If a comment is present
681 /// then it will be printed first. Comments should not contain '\n'.
682 void AsmPrinter::EOL(const Twine &Comment) const {
683 if (VerboseAsm && !Comment.isTriviallyEmpty()) {
684 O.PadToColumn(MAI->getCommentColumn());
685 O << MAI->getCommentString() << ' ' << Comment;
690 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
691 /// unsigned leb128 value.
692 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
693 if (MAI->hasLEB128()) {
694 O << "\t.uleb128\t" << Value;
696 O << MAI->getData8bitsDirective();
701 /// EmitInt8 - Emit a byte directive and value.
703 void AsmPrinter::EmitInt8(int Value) const {
704 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
707 /// EmitInt16 - Emit a short directive and value.
709 void AsmPrinter::EmitInt16(int Value) const {
710 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
713 /// EmitInt32 - Emit a long directive and value.
715 void AsmPrinter::EmitInt32(int Value) const {
716 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
719 /// EmitInt64 - Emit a long long directive and value.
721 void AsmPrinter::EmitInt64(uint64_t Value) const {
722 OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
725 /// toOctal - Convert the low order bits of X into an octal digit.
727 static inline char toOctal(int X) {
731 /// printStringChar - Print a char, escaped if necessary.
733 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
736 } else if (C == '\\') {
738 } else if (isprint((unsigned char)C)) {
742 case '\b': O << "\\b"; break;
743 case '\f': O << "\\f"; break;
744 case '\n': O << "\\n"; break;
745 case '\r': O << "\\r"; break;
746 case '\t': O << "\\t"; break;
749 O << toOctal(C >> 6);
750 O << toOctal(C >> 3);
751 O << toOctal(C >> 0);
757 /// EmitString - Emit a string with quotes and a null terminator.
758 /// Special characters are emitted properly.
759 /// \literal (Eg. '\t') \endliteral
760 void AsmPrinter::EmitString(const StringRef String) const {
761 EmitString(String.data(), String.size());
764 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
765 const char* AscizDirective = MAI->getAscizDirective();
769 O << MAI->getAsciiDirective();
771 for (unsigned i = 0; i < Size; ++i)
772 printStringChar(O, String[i]);
780 /// EmitFile - Emit a .file directive.
781 void AsmPrinter::EmitFile(unsigned Number, StringRef Name) const {
782 O << "\t.file\t" << Number << " \"";
783 for (unsigned i = 0, N = Name.size(); i < N; ++i)
784 printStringChar(O, Name[i]);
789 //===----------------------------------------------------------------------===//
791 // EmitAlignment - Emit an alignment directive to the specified power of
792 // two boundary. For example, if you pass in 3 here, you will get an 8
793 // byte alignment. If a global value is specified, and if that global has
794 // an explicit alignment requested, it will unconditionally override the
795 // alignment request. However, if ForcedAlignBits is specified, this value
796 // has final say: the ultimate alignment will be the max of ForcedAlignBits
797 // and the alignment computed with NumBits and the global.
801 // if (GV && GV->hasalignment) Align = GV->getalignment();
802 // Align = std::max(Align, ForcedAlignBits);
804 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
805 unsigned ForcedAlignBits,
806 bool UseFillExpr) const {
807 if (GV && GV->getAlignment())
808 NumBits = Log2_32(GV->getAlignment());
809 NumBits = std::max(NumBits, ForcedAlignBits);
811 if (NumBits == 0) return; // No need to emit alignment.
813 unsigned FillValue = 0;
814 if (getCurrentSection()->getKind().isText())
815 FillValue = MAI->getTextAlignFillValue();
817 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
820 // Print out the specified constant, without a storage class. Only the
821 // constants valid in constant expressions can occur here.
822 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
823 if (CV->isNullValue() || isa<UndefValue>(CV)) {
828 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
829 O << CI->getZExtValue();
833 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
834 // This is a constant address for a global variable or function. Use the
835 // name of the variable or function as the address value.
836 O << *GetGlobalValueSymbol(GV);
840 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
841 O << *GetBlockAddressSymbol(BA);
845 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
847 llvm_unreachable("Unknown constant value!");
852 switch (CE->getOpcode()) {
853 case Instruction::ZExt:
854 case Instruction::SExt:
855 case Instruction::FPTrunc:
856 case Instruction::FPExt:
857 case Instruction::UIToFP:
858 case Instruction::SIToFP:
859 case Instruction::FPToUI:
860 case Instruction::FPToSI:
862 llvm_unreachable("FIXME: Don't support this constant cast expr");
863 case Instruction::GetElementPtr: {
864 // generate a symbolic expression for the byte address
865 const TargetData *TD = TM.getTargetData();
866 const Constant *ptrVal = CE->getOperand(0);
867 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
868 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
871 return EmitConstantValueOnly(ptrVal);
873 // Truncate/sext the offset to the pointer size.
874 if (TD->getPointerSizeInBits() != 64) {
875 int SExtAmount = 64-TD->getPointerSizeInBits();
876 Offset = (Offset << SExtAmount) >> SExtAmount;
881 EmitConstantValueOnly(ptrVal);
883 O << ") + " << Offset;
885 O << ") - " << -Offset;
888 case Instruction::BitCast:
889 return EmitConstantValueOnly(CE->getOperand(0));
891 case Instruction::IntToPtr: {
892 // Handle casts to pointers by changing them into casts to the appropriate
893 // integer type. This promotes constant folding and simplifies this code.
894 const TargetData *TD = TM.getTargetData();
895 Constant *Op = CE->getOperand(0);
896 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
898 return EmitConstantValueOnly(Op);
901 case Instruction::PtrToInt: {
902 // Support only foldable casts to/from pointers that can be eliminated by
903 // changing the pointer to the appropriately sized integer type.
904 Constant *Op = CE->getOperand(0);
905 const Type *Ty = CE->getType();
906 const TargetData *TD = TM.getTargetData();
908 // We can emit the pointer value into this slot if the slot is an
909 // integer slot greater or equal to the size of the pointer.
910 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
911 return EmitConstantValueOnly(Op);
914 EmitConstantValueOnly(Op);
916 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
919 ptrMask.toStringUnsigned(S);
920 O << ") & " << S.str() << ')';
924 case Instruction::Trunc:
925 // We emit the value and depend on the assembler to truncate the generated
926 // expression properly. This is important for differences between
927 // blockaddress labels. Since the two labels are in the same function, it
928 // is reasonable to treat their delta as a 32-bit value.
929 return EmitConstantValueOnly(CE->getOperand(0));
931 case Instruction::Add:
932 case Instruction::Sub:
933 case Instruction::And:
934 case Instruction::Or:
935 case Instruction::Xor:
937 EmitConstantValueOnly(CE->getOperand(0));
939 switch (CE->getOpcode()) {
940 case Instruction::Add:
943 case Instruction::Sub:
946 case Instruction::And:
949 case Instruction::Or:
952 case Instruction::Xor:
959 EmitConstantValueOnly(CE->getOperand(1));
965 /// printAsCString - Print the specified array as a C compatible string, only if
966 /// the predicate isString is true.
968 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
970 assert(CVA->isString() && "Array is not string compatible!");
973 for (unsigned i = 0; i != LastElt; ++i) {
975 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
976 printStringChar(O, C);
981 /// EmitString - Emit a zero-byte-terminated string constant.
983 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
984 unsigned NumElts = CVA->getNumOperands();
985 if (MAI->getAscizDirective() && NumElts &&
986 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
987 O << MAI->getAscizDirective();
988 printAsCString(O, CVA, NumElts-1);
990 O << MAI->getAsciiDirective();
991 printAsCString(O, CVA, NumElts);
996 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
998 if (AddrSpace == 0 && CA->isString()) {
1000 } else { // Not a string. Print the values in successive locations
1001 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1002 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
1006 static void EmitGlobalConstantVector(const ConstantVector *CV,
1007 unsigned AddrSpace, AsmPrinter &AP) {
1008 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1009 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
1012 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1013 unsigned AddrSpace, AsmPrinter &AP) {
1014 // Print the fields in successive locations. Pad to align if needed!
1015 const TargetData *TD = AP.TM.getTargetData();
1016 unsigned Size = TD->getTypeAllocSize(CS->getType());
1017 const StructLayout *Layout = TD->getStructLayout(CS->getType());
1018 uint64_t SizeSoFar = 0;
1019 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1020 const Constant *Field = CS->getOperand(i);
1022 // Check if padding is needed and insert one or more 0s.
1023 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1024 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1025 - Layout->getElementOffset(i)) - FieldSize;
1026 SizeSoFar += FieldSize + PadSize;
1028 // Now print the actual field value.
1029 AP.EmitGlobalConstant(Field, AddrSpace);
1031 // Insert padding - this may include padding to increase the size of the
1032 // current field up to the ABI size (if the struct is not packed) as well
1033 // as padding to ensure that the next field starts at the right offset.
1034 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1036 assert(SizeSoFar == Layout->getSizeInBytes() &&
1037 "Layout of constant struct may be incorrect!");
1040 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1042 // FP Constants are printed as integer constants to avoid losing
1044 if (CFP->getType()->isDoubleTy()) {
1045 if (AP.VerboseAsm) {
1046 double Val = CFP->getValueAPF().convertToDouble();
1047 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1050 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1051 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1055 if (CFP->getType()->isFloatTy()) {
1056 if (AP.VerboseAsm) {
1057 float Val = CFP->getValueAPF().convertToFloat();
1058 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1060 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1061 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1065 if (CFP->getType()->isX86_FP80Ty()) {
1066 // all long double variants are printed as hex
1067 // api needed to prevent premature destruction
1068 APInt API = CFP->getValueAPF().bitcastToAPInt();
1069 const uint64_t *p = API.getRawData();
1070 if (AP.VerboseAsm) {
1071 // Convert to double so we can print the approximate val as a comment.
1072 APFloat DoubleVal = CFP->getValueAPF();
1074 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1076 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1077 << DoubleVal.convertToDouble() << '\n';
1080 if (AP.TM.getTargetData()->isBigEndian()) {
1081 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1082 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1084 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1085 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1088 // Emit the tail padding for the long double.
1089 const TargetData &TD = *AP.TM.getTargetData();
1090 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1091 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1095 assert(CFP->getType()->isPPC_FP128Ty() &&
1096 "Floating point constant type not handled");
1097 // All long double variants are printed as hex api needed to prevent
1098 // premature destruction.
1099 APInt API = CFP->getValueAPF().bitcastToAPInt();
1100 const uint64_t *p = API.getRawData();
1101 if (AP.TM.getTargetData()->isBigEndian()) {
1102 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1103 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1105 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1106 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1110 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1111 unsigned AddrSpace, AsmPrinter &AP) {
1112 const TargetData *TD = AP.TM.getTargetData();
1113 unsigned BitWidth = CI->getBitWidth();
1114 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1116 // We don't expect assemblers to support integer data directives
1117 // for more than 64 bits, so we emit the data in at most 64-bit
1118 // quantities at a time.
1119 const uint64_t *RawData = CI->getValue().getRawData();
1120 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1121 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1122 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1126 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1127 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1128 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1129 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1130 return OutStreamer.EmitZeros(Size, AddrSpace);
1133 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1134 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1141 OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1142 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1145 EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1150 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1151 return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1153 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1154 return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1156 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1157 return EmitGlobalConstantFP(CFP, AddrSpace, *this);
1159 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1160 return EmitGlobalConstantVector(V, AddrSpace, *this);
1162 if (isa<ConstantPointerNull>(CV)) {
1163 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1164 OutStreamer.EmitIntValue(0, Size, AddrSpace);
1168 // Otherwise, it must be a ConstantExpr. Emit the data directive, then emit
1169 // the expression value.
1170 switch (TM.getTargetData()->getTypeAllocSize(CV->getType())) {
1172 case 1: O << MAI->getData8bitsDirective(AddrSpace); break;
1173 case 2: O << MAI->getData16bitsDirective(AddrSpace); break;
1174 case 4: O << MAI->getData32bitsDirective(AddrSpace); break;
1176 if (const char *Dir = MAI->getData64bitsDirective(AddrSpace)) {
1182 llvm_unreachable("Target cannot handle given data directive width!");
1186 EmitConstantValueOnly(CV);
1190 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1191 // Target doesn't support this yet!
1192 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1195 /// PrintSpecial - Print information related to the specified machine instr
1196 /// that is independent of the operand, and may be independent of the instr
1197 /// itself. This can be useful for portably encoding the comment character
1198 /// or other bits of target-specific knowledge into the asmstrings. The
1199 /// syntax used is ${:comment}. Targets can override this to add support
1200 /// for their own strange codes.
1201 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1202 if (!strcmp(Code, "private")) {
1203 O << MAI->getPrivateGlobalPrefix();
1204 } else if (!strcmp(Code, "comment")) {
1206 O << MAI->getCommentString();
1207 } else if (!strcmp(Code, "uid")) {
1208 // Comparing the address of MI isn't sufficient, because machineinstrs may
1209 // be allocated to the same address across functions.
1210 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1212 // If this is a new LastFn instruction, bump the counter.
1213 if (LastMI != MI || LastFn != ThisF) {
1221 raw_string_ostream Msg(msg);
1222 Msg << "Unknown special formatter '" << Code
1223 << "' for machine instr: " << *MI;
1224 llvm_report_error(Msg.str());
1228 /// processDebugLoc - Processes the debug information of each machine
1229 /// instruction's DebugLoc.
1230 void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1231 bool BeforePrintingInsn) {
1232 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1233 || !DW->ShouldEmitDwarfDebug())
1235 DebugLoc DL = MI->getDebugLoc();
1238 DILocation CurDLT = MF->getDILocation(DL);
1239 if (CurDLT.getScope().isNull())
1242 if (!BeforePrintingInsn) {
1243 // After printing instruction
1245 } else if (CurDLT.getNode() != PrevDLT) {
1246 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1247 CurDLT.getColumnNumber(),
1248 CurDLT.getScope().getNode());
1251 DW->BeginScope(MI, L);
1252 PrevDLT = CurDLT.getNode();
1257 /// printInlineAsm - This method formats and prints the specified machine
1258 /// instruction that is an inline asm.
1259 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1260 unsigned NumOperands = MI->getNumOperands();
1262 // Count the number of register definitions.
1263 unsigned NumDefs = 0;
1264 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1266 assert(NumDefs != NumOperands-1 && "No asm string?");
1268 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1270 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1271 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1275 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1276 // These are useful to see where empty asm's wound up.
1277 if (AsmStr[0] == 0) {
1278 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1279 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1283 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1285 // The variant of the current asmprinter.
1286 int AsmPrinterVariant = MAI->getAssemblerDialect();
1288 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1289 const char *LastEmitted = AsmStr; // One past the last character emitted.
1291 while (*LastEmitted) {
1292 switch (*LastEmitted) {
1294 // Not a special case, emit the string section literally.
1295 const char *LiteralEnd = LastEmitted+1;
1296 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1297 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1299 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1300 O.write(LastEmitted, LiteralEnd-LastEmitted);
1301 LastEmitted = LiteralEnd;
1305 ++LastEmitted; // Consume newline character.
1306 O << '\n'; // Indent code with newline.
1309 ++LastEmitted; // Consume '$' character.
1313 switch (*LastEmitted) {
1314 default: Done = false; break;
1315 case '$': // $$ -> $
1316 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1318 ++LastEmitted; // Consume second '$' character.
1320 case '(': // $( -> same as GCC's { character.
1321 ++LastEmitted; // Consume '(' character.
1322 if (CurVariant != -1) {
1323 llvm_report_error("Nested variants found in inline asm string: '"
1324 + std::string(AsmStr) + "'");
1326 CurVariant = 0; // We're in the first variant now.
1329 ++LastEmitted; // consume '|' character.
1330 if (CurVariant == -1)
1331 O << '|'; // this is gcc's behavior for | outside a variant
1333 ++CurVariant; // We're in the next variant.
1335 case ')': // $) -> same as GCC's } char.
1336 ++LastEmitted; // consume ')' character.
1337 if (CurVariant == -1)
1338 O << '}'; // this is gcc's behavior for } outside a variant
1345 bool HasCurlyBraces = false;
1346 if (*LastEmitted == '{') { // ${variable}
1347 ++LastEmitted; // Consume '{' character.
1348 HasCurlyBraces = true;
1351 // If we have ${:foo}, then this is not a real operand reference, it is a
1352 // "magic" string reference, just like in .td files. Arrange to call
1354 if (HasCurlyBraces && *LastEmitted == ':') {
1356 const char *StrStart = LastEmitted;
1357 const char *StrEnd = strchr(StrStart, '}');
1359 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1360 + std::string(AsmStr) + "'");
1363 std::string Val(StrStart, StrEnd);
1364 PrintSpecial(MI, Val.c_str());
1365 LastEmitted = StrEnd+1;
1369 const char *IDStart = LastEmitted;
1372 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1373 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1374 llvm_report_error("Bad $ operand number in inline asm string: '"
1375 + std::string(AsmStr) + "'");
1377 LastEmitted = IDEnd;
1379 char Modifier[2] = { 0, 0 };
1381 if (HasCurlyBraces) {
1382 // If we have curly braces, check for a modifier character. This
1383 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1384 if (*LastEmitted == ':') {
1385 ++LastEmitted; // Consume ':' character.
1386 if (*LastEmitted == 0) {
1387 llvm_report_error("Bad ${:} expression in inline asm string: '"
1388 + std::string(AsmStr) + "'");
1391 Modifier[0] = *LastEmitted;
1392 ++LastEmitted; // Consume modifier character.
1395 if (*LastEmitted != '}') {
1396 llvm_report_error("Bad ${} expression in inline asm string: '"
1397 + std::string(AsmStr) + "'");
1399 ++LastEmitted; // Consume '}' character.
1402 if ((unsigned)Val >= NumOperands-1) {
1403 llvm_report_error("Invalid $ operand number in inline asm string: '"
1404 + std::string(AsmStr) + "'");
1407 // Okay, we finally have a value number. Ask the target to print this
1409 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1414 // Scan to find the machine operand number for the operand.
1415 for (; Val; --Val) {
1416 if (OpNo >= MI->getNumOperands()) break;
1417 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1418 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1421 if (OpNo >= MI->getNumOperands()) {
1424 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1425 ++OpNo; // Skip over the ID number.
1427 if (Modifier[0] == 'l') // labels are target independent
1428 O << *GetMBBSymbol(MI->getOperand(OpNo).getMBB()->getNumber());
1430 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1431 if ((OpFlags & 7) == 4) {
1432 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1433 Modifier[0] ? Modifier : 0);
1435 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1436 Modifier[0] ? Modifier : 0);
1442 raw_string_ostream Msg(msg);
1443 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1445 llvm_report_error(Msg.str());
1452 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1455 /// printImplicitDef - This method prints the specified machine instruction
1456 /// that is an implicit def.
1457 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1458 if (!VerboseAsm) return;
1459 O.PadToColumn(MAI->getCommentColumn());
1460 O << MAI->getCommentString() << " implicit-def: "
1461 << TRI->getName(MI->getOperand(0).getReg());
1464 void AsmPrinter::printKill(const MachineInstr *MI) const {
1465 if (!VerboseAsm) return;
1466 O.PadToColumn(MAI->getCommentColumn());
1467 O << MAI->getCommentString() << " kill:";
1468 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1469 const MachineOperand &op = MI->getOperand(n);
1470 assert(op.isReg() && "KILL instruction must have only register operands");
1471 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1475 /// printLabel - This method prints a local label used by debug and
1476 /// exception handling tables.
1477 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1478 printLabel(MI->getOperand(0).getImm());
1481 void AsmPrinter::printLabel(unsigned Id) const {
1482 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1485 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1486 /// instruction, using the specified assembler variant. Targets should
1487 /// override this to format as appropriate.
1488 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1489 unsigned AsmVariant, const char *ExtraCode) {
1490 // Target doesn't support this yet!
1494 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1495 unsigned AsmVariant,
1496 const char *ExtraCode) {
1497 // Target doesn't support this yet!
1501 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1502 const char *Suffix) const {
1503 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1506 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1507 const BasicBlock *BB,
1508 const char *Suffix) const {
1509 assert(BB->hasName() &&
1510 "Address of anonymous basic block not supported yet!");
1512 // This code must use the function name itself, and not the function number,
1513 // since it must be possible to generate the label name from within other
1515 SmallString<60> FnName;
1516 Mang->getNameWithPrefix(FnName, F, false);
1518 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1519 SmallString<60> NameResult;
1520 Mang->getNameWithPrefix(NameResult,
1521 StringRef("BA") + Twine((unsigned)FnName.size()) +
1522 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1525 return OutContext.GetOrCreateSymbol(NameResult.str());
1528 MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1529 SmallString<60> Name;
1530 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1531 << getFunctionNumber() << '_' << MBBID;
1533 return OutContext.GetOrCreateSymbol(Name.str());
1536 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1538 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1539 SmallString<60> NameStr;
1540 Mang->getNameWithPrefix(NameStr, GV, false);
1541 return OutContext.GetOrCreateSymbol(NameStr.str());
1544 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1545 /// global value name as its base, with the specified suffix, and where the
1546 /// symbol is forced to have private linkage if ForcePrivate is true.
1547 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1549 bool ForcePrivate) const {
1550 SmallString<60> NameStr;
1551 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1552 NameStr.append(Suffix.begin(), Suffix.end());
1553 return OutContext.GetOrCreateSymbol(NameStr.str());
1556 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1558 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1559 SmallString<60> NameStr;
1560 Mang->getNameWithPrefix(NameStr, Sym);
1561 return OutContext.GetOrCreateSymbol(NameStr.str());
1566 /// PrintParentLoopComment - Print comments about parent loops of this one.
1567 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1568 unsigned FunctionNumber) {
1569 if (Loop == 0) return;
1570 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1571 OS.indent(Loop->getLoopDepth()*2)
1572 << "Parent Loop BB" << FunctionNumber << "_"
1573 << Loop->getHeader()->getNumber()
1574 << " Depth=" << Loop->getLoopDepth() << '\n';
1578 /// PrintChildLoopComment - Print comments about child loops within
1579 /// the loop for this basic block, with nesting.
1580 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1581 unsigned FunctionNumber) {
1582 // Add child loop information
1583 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1584 OS.indent((*CL)->getLoopDepth()*2)
1585 << "Child Loop BB" << FunctionNumber << "_"
1586 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1588 PrintChildLoopComment(OS, *CL, FunctionNumber);
1592 /// EmitComments - Pretty-print comments for basic blocks.
1593 static void PrintBasicBlockLoopComments(const MachineBasicBlock &MBB,
1594 const MachineLoopInfo *LI,
1595 const AsmPrinter &AP) {
1596 // Add loop depth information
1597 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1598 if (Loop == 0) return;
1600 MachineBasicBlock *Header = Loop->getHeader();
1601 assert(Header && "No header for loop");
1603 // If this block is not a loop header, just print out what is the loop header
1605 if (Header != &MBB) {
1606 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1607 Twine(AP.getFunctionNumber())+"_" +
1608 Twine(Loop->getHeader()->getNumber())+
1609 " Depth="+Twine(Loop->getLoopDepth()));
1613 // Otherwise, it is a loop header. Print out information about child and
1615 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1617 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1620 OS.indent(Loop->getLoopDepth()*2-2);
1625 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1627 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1631 /// EmitBasicBlockStart - This method prints the label for the specified
1632 /// MachineBasicBlock, an alignment (if present) and a comment describing
1633 /// it if appropriate.
1634 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1635 // Emit an alignment directive for this block, if needed.
1636 if (unsigned Align = MBB->getAlignment())
1637 EmitAlignment(Log2_32(Align));
1639 // If the block has its address taken, emit a special label to satisfy
1640 // references to the block. This is done so that we don't need to
1641 // remember the number of this label, and so that we can make
1642 // forward references to labels without knowing what their numbers
1644 if (MBB->hasAddressTaken()) {
1645 const BasicBlock *BB = MBB->getBasicBlock();
1647 OutStreamer.AddComment("Address Taken");
1648 OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB));
1651 // Print the main label for the block.
1652 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1654 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1655 if (const BasicBlock *BB = MBB->getBasicBlock())
1657 OutStreamer.AddComment("%" + BB->getName());
1659 PrintBasicBlockLoopComments(*MBB, LI, *this);
1660 OutStreamer.AddBlankLine();
1664 if (const BasicBlock *BB = MBB->getBasicBlock())
1666 OutStreamer.AddComment("%" + BB->getName());
1667 PrintBasicBlockLoopComments(*MBB, LI, *this);
1670 OutStreamer.EmitLabel(GetMBBSymbol(MBB->getNumber()));
1674 /// printPICJumpTableSetLabel - This method prints a set label for the
1675 /// specified MachineBasicBlock for a jumptable entry.
1676 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1677 const MachineBasicBlock *MBB) const {
1678 if (!MAI->getSetDirective())
1681 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1682 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ','
1683 << *GetMBBSymbol(MBB->getNumber())
1684 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1685 << '_' << uid << '\n';
1688 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1689 const MachineBasicBlock *MBB) const {
1690 if (!MAI->getSetDirective())
1693 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1694 << getFunctionNumber() << '_' << uid << '_' << uid2
1695 << "_set_" << MBB->getNumber() << ','
1696 << *GetMBBSymbol(MBB->getNumber())
1697 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1698 << '_' << uid << '_' << uid2 << '\n';
1701 void AsmPrinter::printVisibility(const MCSymbol *Sym,
1702 unsigned Visibility) const {
1703 if (Visibility == GlobalValue::HiddenVisibility) {
1704 if (const char *Directive = MAI->getHiddenDirective())
1705 O << Directive << *Sym << '\n';
1706 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1707 if (const char *Directive = MAI->getProtectedDirective())
1708 O << Directive << *Sym << '\n';
1712 void AsmPrinter::printOffset(int64_t Offset) const {
1715 else if (Offset < 0)
1719 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1720 if (!S->usesMetadata())
1723 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1724 if (GCPI != GCMetadataPrinters.end())
1725 return GCPI->second;
1727 const char *Name = S->getName().c_str();
1729 for (GCMetadataPrinterRegistry::iterator
1730 I = GCMetadataPrinterRegistry::begin(),
1731 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1732 if (strcmp(Name, I->getName()) == 0) {
1733 GCMetadataPrinter *GMP = I->instantiate();
1735 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1739 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1740 llvm_unreachable(0);
1743 /// EmitComments - Pretty-print comments for instructions
1744 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1748 bool Newline = false;
1750 if (!MI.getDebugLoc().isUnknown()) {
1751 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1753 // Print source line info.
1754 O.PadToColumn(MAI->getCommentColumn());
1755 O << MAI->getCommentString() << ' ';
1756 DIScope Scope = DLT.getScope();
1757 // Omit the directory, because it's likely to be long and uninteresting.
1758 if (!Scope.isNull())
1759 O << Scope.getFilename();
1762 O << ':' << DLT.getLineNumber();
1763 if (DLT.getColumnNumber() != 0)
1764 O << ':' << DLT.getColumnNumber();
1768 // Check for spills and reloads
1771 const MachineFrameInfo *FrameInfo =
1772 MI.getParent()->getParent()->getFrameInfo();
1774 // We assume a single instruction only has a spill or reload, not
1776 const MachineMemOperand *MMO;
1777 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1778 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1779 MMO = *MI.memoperands_begin();
1780 if (Newline) O << '\n';
1781 O.PadToColumn(MAI->getCommentColumn());
1782 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1786 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1787 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1788 if (Newline) O << '\n';
1789 O.PadToColumn(MAI->getCommentColumn());
1790 O << MAI->getCommentString() << ' '
1791 << MMO->getSize() << "-byte Folded Reload";
1795 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1796 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1797 MMO = *MI.memoperands_begin();
1798 if (Newline) O << '\n';
1799 O.PadToColumn(MAI->getCommentColumn());
1800 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1804 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1805 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1806 if (Newline) O << '\n';
1807 O.PadToColumn(MAI->getCommentColumn());
1808 O << MAI->getCommentString() << ' '
1809 << MMO->getSize() << "-byte Folded Spill";
1814 // Check for spill-induced copies
1815 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1816 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1817 SrcSubIdx, DstSubIdx)) {
1818 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1819 if (Newline) O << '\n';
1820 O.PadToColumn(MAI->getCommentColumn());
1821 O << MAI->getCommentString() << " Reload Reuse";