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 #define DEBUG_TYPE "asm-printer"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #ifndef ANDROID_TARGET_BUILD
17 # include "DwarfDebug.h"
18 # include "DwarfException.h"
19 #endif // ANDROID_TARGET_BUILD
20 #include "llvm/Module.h"
21 #include "llvm/CodeGen/GCMetadataPrinter.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineJumpTableInfo.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/Analysis/ConstantFolding.h"
29 #include "llvm/Analysis/DebugInfo.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCContext.h"
32 #include "llvm/MC/MCExpr.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Target/Mangler.h"
38 #include "llvm/Target/TargetAsmInfo.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/Assembly/Writer.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Statistic.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/Format.h"
50 #include "llvm/Support/Timer.h"
54 static const char *DWARFGroupName = "DWARF Emission";
55 static const char *DbgTimerName = "DWARF Debug Writer";
56 static const char *EHTimerName = "DWARF Exception Writer";
58 STATISTIC(EmittedInsts, "Number of machine instrs printed");
60 char AsmPrinter::ID = 0;
62 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
63 static gcp_map_type &getGCMap(void *&P) {
65 P = new gcp_map_type();
66 return *(gcp_map_type*)P;
70 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
71 /// value in log2 form. This rounds up to the preferred alignment if possible
73 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const TargetData &TD,
74 unsigned InBits = 0) {
76 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
77 NumBits = TD.getPreferredAlignmentLog(GVar);
79 // If InBits is specified, round it to it.
83 // If the GV has a specified alignment, take it into account.
84 if (GV->getAlignment() == 0)
87 unsigned GVAlign = Log2_32(GV->getAlignment());
89 // If the GVAlign is larger than NumBits, or if we are required to obey
90 // NumBits because the GV has an assigned section, obey it.
91 if (GVAlign > NumBits || GV->hasSection())
99 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
100 : MachineFunctionPass(ID),
101 TM(tm), MAI(tm.getMCAsmInfo()),
102 OutContext(Streamer.getContext()),
103 OutStreamer(Streamer),
104 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
105 DD = 0; DE = 0; MMI = 0; LI = 0;
106 GCMetadataPrinters = 0;
107 VerboseAsm = Streamer.isVerboseAsm();
110 AsmPrinter::~AsmPrinter() {
111 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
113 if (GCMetadataPrinters != 0) {
114 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
116 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
119 GCMetadataPrinters = 0;
125 /// getFunctionNumber - Return a unique ID for the current function.
127 unsigned AsmPrinter::getFunctionNumber() const {
128 return MF->getFunctionNumber();
131 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
132 return TM.getTargetLowering()->getObjFileLowering();
136 /// getTargetData - Return information about data layout.
137 const TargetData &AsmPrinter::getTargetData() const {
138 return *TM.getTargetData();
141 /// getCurrentSection() - Return the current section we are emitting to.
142 const MCSection *AsmPrinter::getCurrentSection() const {
143 return OutStreamer.getCurrentSection();
148 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
149 AU.setPreservesAll();
150 MachineFunctionPass::getAnalysisUsage(AU);
151 AU.addRequired<MachineModuleInfo>();
152 AU.addRequired<GCModuleInfo>();
154 AU.addRequired<MachineLoopInfo>();
157 bool AsmPrinter::doInitialization(Module &M) {
158 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
159 MMI->AnalyzeModule(M);
161 // Initialize TargetLoweringObjectFile.
162 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
163 .Initialize(OutContext, TM);
165 Mang = new Mangler(OutContext, *TM.getTargetData());
167 // Allow the target to emit any magic that it wants at the start of the file.
168 EmitStartOfAsmFile(M);
170 // Very minimal debug info. It is ignored if we emit actual debug info. If we
171 // don't, this at least helps the user find where a global came from.
172 if (MAI->hasSingleParameterDotFile()) {
174 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
177 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
178 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
179 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
180 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
181 MP->beginAssembly(*this);
183 // Emit module-level inline asm if it exists.
184 if (!M.getModuleInlineAsm().empty()) {
185 OutStreamer.AddComment("Start of file scope inline assembly");
186 OutStreamer.AddBlankLine();
187 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
188 OutStreamer.AddComment("End of file scope inline assembly");
189 OutStreamer.AddBlankLine();
192 #ifndef ANDROID_TARGET_BUILD
193 if (MAI->doesSupportDebugInformation())
194 DD = new DwarfDebug(this, &M);
196 switch (MAI->getExceptionHandlingType()) {
197 case ExceptionHandling::None:
199 case ExceptionHandling::SjLj:
200 case ExceptionHandling::DwarfCFI:
201 DE = new DwarfCFIException(this);
203 case ExceptionHandling::ARM:
204 DE = new ARMException(this);
206 case ExceptionHandling::Win64:
207 DE = new Win64Exception(this);
212 #endif // ANDROID_TARGET_BUILD
214 llvm_unreachable("Unknown exception type.");
217 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
218 switch ((GlobalValue::LinkageTypes)Linkage) {
219 case GlobalValue::CommonLinkage:
220 case GlobalValue::LinkOnceAnyLinkage:
221 case GlobalValue::LinkOnceODRLinkage:
222 case GlobalValue::WeakAnyLinkage:
223 case GlobalValue::WeakODRLinkage:
224 case GlobalValue::LinkerPrivateWeakLinkage:
225 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
226 if (MAI->getWeakDefDirective() != 0) {
228 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
230 if ((GlobalValue::LinkageTypes)Linkage !=
231 GlobalValue::LinkerPrivateWeakDefAutoLinkage)
232 // .weak_definition _foo
233 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
235 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
236 } else if (MAI->getLinkOnceDirective() != 0) {
238 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
239 //NOTE: linkonce is handled by the section the symbol was assigned to.
242 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
245 case GlobalValue::DLLExportLinkage:
246 case GlobalValue::AppendingLinkage:
247 // FIXME: appending linkage variables should go into a section of
248 // their name or something. For now, just emit them as external.
249 case GlobalValue::ExternalLinkage:
250 // If external or appending, declare as a global symbol.
252 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
254 case GlobalValue::PrivateLinkage:
255 case GlobalValue::InternalLinkage:
256 case GlobalValue::LinkerPrivateLinkage:
259 llvm_unreachable("Unknown linkage type!");
264 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
265 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
266 if (GV->hasInitializer()) {
267 // Check to see if this is a special global used by LLVM, if so, emit it.
268 if (EmitSpecialLLVMGlobal(GV))
272 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
273 /*PrintType=*/false, GV->getParent());
274 OutStreamer.GetCommentOS() << '\n';
278 MCSymbol *GVSym = Mang->getSymbol(GV);
279 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
281 if (!GV->hasInitializer()) // External globals require no extra code.
284 if (MAI->hasDotTypeDotSizeDirective())
285 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
287 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
289 const TargetData *TD = TM.getTargetData();
290 uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
292 // If the alignment is specified, we *must* obey it. Overaligning a global
293 // with a specified alignment is a prompt way to break globals emitted to
294 // sections and expected to be contiguous (e.g. ObjC metadata).
295 unsigned AlignLog = getGVAlignmentLog2(GV, *TD);
297 // Handle common and BSS local symbols (.lcomm).
298 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
299 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
301 // Handle common symbols.
302 if (GVKind.isCommon()) {
303 unsigned Align = 1 << AlignLog;
304 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
308 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
312 // Handle local BSS symbols.
313 if (MAI->hasMachoZeroFillDirective()) {
314 const MCSection *TheSection =
315 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
316 // .zerofill __DATA, __bss, _foo, 400, 5
317 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
321 if (MAI->hasLCOMMDirective()) {
323 OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
327 unsigned Align = 1 << AlignLog;
328 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
332 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
334 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
338 const MCSection *TheSection =
339 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
341 // Handle the zerofill directive on darwin, which is a special form of BSS
343 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
344 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
347 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
348 // .zerofill __DATA, __common, _foo, 400, 5
349 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
353 // Handle thread local data for mach-o which requires us to output an
354 // additional structure of data and mangle the original symbol so that we
355 // can reference it later.
357 // TODO: This should become an "emit thread local global" method on TLOF.
358 // All of this macho specific stuff should be sunk down into TLOFMachO and
359 // stuff like "TLSExtraDataSection" should no longer be part of the parent
360 // TLOF class. This will also make it more obvious that stuff like
361 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
363 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
364 // Emit the .tbss symbol
366 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
368 if (GVKind.isThreadBSS())
369 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
370 else if (GVKind.isThreadData()) {
371 OutStreamer.SwitchSection(TheSection);
373 EmitAlignment(AlignLog, GV);
374 OutStreamer.EmitLabel(MangSym);
376 EmitGlobalConstant(GV->getInitializer());
379 OutStreamer.AddBlankLine();
381 // Emit the variable struct for the runtime.
382 const MCSection *TLVSect
383 = getObjFileLowering().getTLSExtraDataSection();
385 OutStreamer.SwitchSection(TLVSect);
386 // Emit the linkage here.
387 EmitLinkage(GV->getLinkage(), GVSym);
388 OutStreamer.EmitLabel(GVSym);
390 // Three pointers in size:
391 // - __tlv_bootstrap - used to make sure support exists
392 // - spare pointer, used when mapped by the runtime
393 // - pointer to mangled symbol above with initializer
394 unsigned PtrSize = TD->getPointerSizeInBits()/8;
395 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
397 OutStreamer.EmitIntValue(0, PtrSize, 0);
398 OutStreamer.EmitSymbolValue(MangSym, PtrSize, 0);
400 OutStreamer.AddBlankLine();
404 OutStreamer.SwitchSection(TheSection);
406 EmitLinkage(GV->getLinkage(), GVSym);
407 EmitAlignment(AlignLog, GV);
409 OutStreamer.EmitLabel(GVSym);
411 EmitGlobalConstant(GV->getInitializer());
413 if (MAI->hasDotTypeDotSizeDirective())
415 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
417 OutStreamer.AddBlankLine();
420 /// EmitFunctionHeader - This method emits the header for the current
422 void AsmPrinter::EmitFunctionHeader() {
423 // Print out constants referenced by the function
426 // Print the 'header' of function.
427 const Function *F = MF->getFunction();
429 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
430 EmitVisibility(CurrentFnSym, F->getVisibility());
432 EmitLinkage(F->getLinkage(), CurrentFnSym);
433 EmitAlignment(MF->getAlignment(), F);
435 if (MAI->hasDotTypeDotSizeDirective())
436 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
439 WriteAsOperand(OutStreamer.GetCommentOS(), F,
440 /*PrintType=*/false, F->getParent());
441 OutStreamer.GetCommentOS() << '\n';
444 // Emit the CurrentFnSym. This is a virtual function to allow targets to
445 // do their wild and crazy things as required.
446 EmitFunctionEntryLabel();
448 // If the function had address-taken blocks that got deleted, then we have
449 // references to the dangling symbols. Emit them at the start of the function
450 // so that we don't get references to undefined symbols.
451 std::vector<MCSymbol*> DeadBlockSyms;
452 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
453 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
454 OutStreamer.AddComment("Address taken block that was later removed");
455 OutStreamer.EmitLabel(DeadBlockSyms[i]);
458 // Add some workaround for linkonce linkage on Cygwin\MinGW.
459 if (MAI->getLinkOnceDirective() != 0 &&
460 (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
461 // FIXME: What is this?
463 OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
464 CurrentFnSym->getName());
465 OutStreamer.EmitLabel(FakeStub);
468 // Emit pre-function debug and/or EH information.
469 #ifndef ANDROID_TARGET_BUILD
471 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
472 DE->BeginFunction(MF);
475 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
476 DD->beginFunction(MF);
478 #endif // ANDROID_TARGET_BUILD
481 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
482 /// function. This can be overridden by targets as required to do custom stuff.
483 void AsmPrinter::EmitFunctionEntryLabel() {
484 // The function label could have already been emitted if two symbols end up
485 // conflicting due to asm renaming. Detect this and emit an error.
486 if (CurrentFnSym->isUndefined())
487 return OutStreamer.EmitLabel(CurrentFnSym);
489 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
490 "' label emitted multiple times to assembly file");
494 /// EmitComments - Pretty-print comments for instructions.
495 static void EmitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
496 const MachineFunction *MF = MI.getParent()->getParent();
497 const TargetMachine &TM = MF->getTarget();
499 // Check for spills and reloads
502 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
504 // We assume a single instruction only has a spill or reload, not
506 const MachineMemOperand *MMO;
507 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
508 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
509 MMO = *MI.memoperands_begin();
510 CommentOS << MMO->getSize() << "-byte Reload\n";
512 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
513 if (FrameInfo->isSpillSlotObjectIndex(FI))
514 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
515 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
516 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
517 MMO = *MI.memoperands_begin();
518 CommentOS << MMO->getSize() << "-byte Spill\n";
520 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
521 if (FrameInfo->isSpillSlotObjectIndex(FI))
522 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
525 // Check for spill-induced copies
526 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
527 CommentOS << " Reload Reuse\n";
530 /// EmitImplicitDef - This method emits the specified machine instruction
531 /// that is an implicit def.
532 static void EmitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
533 unsigned RegNo = MI->getOperand(0).getReg();
534 AP.OutStreamer.AddComment(Twine("implicit-def: ") +
535 AP.TM.getRegisterInfo()->getName(RegNo));
536 AP.OutStreamer.AddBlankLine();
539 static void EmitKill(const MachineInstr *MI, AsmPrinter &AP) {
540 std::string Str = "kill:";
541 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
542 const MachineOperand &Op = MI->getOperand(i);
543 assert(Op.isReg() && "KILL instruction must have only register operands");
545 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
546 Str += (Op.isDef() ? "<def>" : "<kill>");
548 AP.OutStreamer.AddComment(Str);
549 AP.OutStreamer.AddBlankLine();
552 /// EmitDebugValueComment - This method handles the target-independent form
553 /// of DBG_VALUE, returning true if it was able to do so. A false return
554 /// means the target will need to handle MI in EmitInstruction.
555 static bool EmitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
556 // This code handles only the 3-operand target-independent form.
557 if (MI->getNumOperands() != 3)
560 SmallString<128> Str;
561 raw_svector_ostream OS(Str);
562 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
564 // cast away const; DIetc do not take const operands for some reason.
565 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
566 if (V.getContext().isSubprogram())
567 OS << DISubprogram(V.getContext()).getDisplayName() << ":";
568 OS << V.getName() << " <- ";
570 // Register or immediate value. Register 0 means undef.
571 if (MI->getOperand(0).isFPImm()) {
572 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
573 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
574 OS << (double)APF.convertToFloat();
575 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
576 OS << APF.convertToDouble();
578 // There is no good way to print long double. Convert a copy to
579 // double. Ah well, it's only a comment.
581 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
583 OS << "(long double) " << APF.convertToDouble();
585 } else if (MI->getOperand(0).isImm()) {
586 OS << MI->getOperand(0).getImm();
587 } else if (MI->getOperand(0).isCImm()) {
588 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
590 assert(MI->getOperand(0).isReg() && "Unknown operand type");
591 if (MI->getOperand(0).getReg() == 0) {
592 // Suppress offset, it is not meaningful here.
594 // NOTE: Want this comment at start of line, don't emit with AddComment.
595 AP.OutStreamer.EmitRawText(OS.str());
598 OS << AP.TM.getRegisterInfo()->getName(MI->getOperand(0).getReg());
601 OS << '+' << MI->getOperand(1).getImm();
602 // NOTE: Want this comment at start of line, don't emit with AddComment.
603 AP.OutStreamer.EmitRawText(OS.str());
607 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
608 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
609 MF->getFunction()->needsUnwindTableEntry())
612 if (MMI->hasDebugInfo())
618 bool AsmPrinter::needsSEHMoves() {
619 return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
620 MF->getFunction()->needsUnwindTableEntry();
623 void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
624 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
626 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
629 if (needsCFIMoves() == CFI_M_None)
632 MachineModuleInfo &MMI = MF->getMMI();
633 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
634 bool FoundOne = false;
636 for (std::vector<MachineMove>::iterator I = Moves.begin(),
637 E = Moves.end(); I != E; ++I) {
638 if (I->getLabel() == Label) {
639 EmitCFIFrameMove(*I);
646 /// EmitFunctionBody - This method emits the body and trailer for a
648 void AsmPrinter::EmitFunctionBody() {
649 // Emit target-specific gunk before the function body.
650 EmitFunctionBodyStart();
652 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
654 // Print out code for the function.
655 bool HasAnyRealCode = false;
656 const MachineInstr *LastMI = 0;
657 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
659 // Print a label for the basic block.
660 EmitBasicBlockStart(I);
661 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
665 // Print the assembly for the instruction.
666 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
667 !II->isDebugValue()) {
668 HasAnyRealCode = true;
672 #ifndef ANDROID_TARGET_BUILD
673 if (ShouldPrintDebugScopes) {
674 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
675 DD->beginInstruction(II);
677 #endif // ANDROID_TARGET_BUILD
680 EmitComments(*II, OutStreamer.GetCommentOS());
682 switch (II->getOpcode()) {
683 case TargetOpcode::PROLOG_LABEL:
684 emitPrologLabel(*II);
687 case TargetOpcode::EH_LABEL:
688 case TargetOpcode::GC_LABEL:
689 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
691 case TargetOpcode::INLINEASM:
694 case TargetOpcode::DBG_VALUE:
696 if (!EmitDebugValueComment(II, *this))
700 case TargetOpcode::IMPLICIT_DEF:
701 if (isVerbose()) EmitImplicitDef(II, *this);
703 case TargetOpcode::KILL:
704 if (isVerbose()) EmitKill(II, *this);
707 if (!TM.hasMCUseLoc())
708 MCLineEntry::Make(&OutStreamer, getCurrentSection());
714 #ifndef ANDROID_TARGET_BUILD
715 if (ShouldPrintDebugScopes) {
716 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
717 DD->endInstruction(II);
719 #endif // ANDROID_TARGET_BUILD
723 // If the last instruction was a prolog label, then we have a situation where
724 // we emitted a prolog but no function body. This results in the ending prolog
725 // label equaling the end of function label and an invalid "row" in the
726 // FDE. We need to emit a noop in this situation so that the FDE's rows are
728 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
730 // If the function is empty and the object file uses .subsections_via_symbols,
731 // then we need to emit *something* to the function body to prevent the
732 // labels from collapsing together. Just emit a noop.
733 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
735 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
736 if (Noop.getOpcode()) {
737 OutStreamer.AddComment("avoids zero-length function");
738 OutStreamer.EmitInstruction(Noop);
739 } else // Target not mc-ized yet.
740 OutStreamer.EmitRawText(StringRef("\tnop\n"));
743 // Emit target-specific gunk after the function body.
744 EmitFunctionBodyEnd();
746 // If the target wants a .size directive for the size of the function, emit
748 if (MAI->hasDotTypeDotSizeDirective()) {
749 // Create a symbol for the end of function, so we can get the size as
750 // difference between the function label and the temp label.
751 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
752 OutStreamer.EmitLabel(FnEndLabel);
754 const MCExpr *SizeExp =
755 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
756 MCSymbolRefExpr::Create(CurrentFnSym, OutContext),
758 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
761 // Emit post-function debug information.
762 #ifndef ANDROID_TARGET_BUILD
764 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
768 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
771 #endif // ANDROID_TARGET_BUILD
774 // Print out jump tables referenced by the function.
777 OutStreamer.AddBlankLine();
780 /// getDebugValueLocation - Get location information encoded by DBG_VALUE
782 MachineLocation AsmPrinter::
783 getDebugValueLocation(const MachineInstr *MI) const {
784 // Target specific DBG_VALUE instructions are handled by each target.
785 return MachineLocation();
788 /// EmitDwarfRegOp - Emit dwarf register operation.
789 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc) const {
790 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
791 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
793 for (const unsigned *SR = TRI->getSuperRegisters(MLoc.getReg());
794 *SR && Reg < 0; ++SR) {
795 Reg = TRI->getDwarfRegNum(*SR, false);
796 // FIXME: Get the bit range this register uses of the superregister
797 // so that we can produce a DW_OP_bit_piece
800 // FIXME: Handle cases like a super register being encoded as
801 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
803 // FIXME: We have no reasonable way of handling errors in here. The
804 // caller might be in the middle of an dwarf expression. We should
805 // probably assert that Reg >= 0 once debug info generation is more mature.
807 if (int Offset = MLoc.getOffset()) {
809 OutStreamer.AddComment(
810 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
811 EmitInt8(dwarf::DW_OP_breg0 + Reg);
813 OutStreamer.AddComment("DW_OP_bregx");
814 EmitInt8(dwarf::DW_OP_bregx);
815 OutStreamer.AddComment(Twine(Reg));
821 OutStreamer.AddComment(
822 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
823 EmitInt8(dwarf::DW_OP_reg0 + Reg);
825 OutStreamer.AddComment("DW_OP_regx");
826 EmitInt8(dwarf::DW_OP_regx);
827 OutStreamer.AddComment(Twine(Reg));
832 // FIXME: Produce a DW_OP_bit_piece if we used a superregister
835 bool AsmPrinter::doFinalization(Module &M) {
836 // Emit global variables.
837 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
839 EmitGlobalVariable(I);
841 // Emit visibility info for declarations
842 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
843 const Function &F = *I;
844 if (!F.isDeclaration())
846 GlobalValue::VisibilityTypes V = F.getVisibility();
847 if (V == GlobalValue::DefaultVisibility)
850 MCSymbol *Name = Mang->getSymbol(&F);
851 EmitVisibility(Name, V, false);
854 // Finalize debug and EH information.
855 #ifndef ANDROID_TARGET_BUILD
858 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
865 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
870 #endif // ANDROID_TARGET_BUILD
872 // If the target wants to know about weak references, print them all.
873 if (MAI->getWeakRefDirective()) {
874 // FIXME: This is not lazy, it would be nice to only print weak references
875 // to stuff that is actually used. Note that doing so would require targets
876 // to notice uses in operands (due to constant exprs etc). This should
877 // happen with the MC stuff eventually.
879 // Print out module-level global variables here.
880 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
882 if (!I->hasExternalWeakLinkage()) continue;
883 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
886 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
887 if (!I->hasExternalWeakLinkage()) continue;
888 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
892 if (MAI->hasSetDirective()) {
893 OutStreamer.AddBlankLine();
894 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
896 MCSymbol *Name = Mang->getSymbol(I);
898 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
899 MCSymbol *Target = Mang->getSymbol(GV);
901 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
902 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
903 else if (I->hasWeakLinkage())
904 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
906 assert(I->hasLocalLinkage() && "Invalid alias linkage");
908 EmitVisibility(Name, I->getVisibility());
910 // Emit the directives as assignments aka .set:
911 OutStreamer.EmitAssignment(Name,
912 MCSymbolRefExpr::Create(Target, OutContext));
916 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
917 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
918 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
919 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
920 MP->finishAssembly(*this);
922 // If we don't have any trampolines, then we don't require stack memory
923 // to be executable. Some targets have a directive to declare this.
924 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
925 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
926 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
927 OutStreamer.SwitchSection(S);
929 // Allow the target to emit any magic that it wants at the end of the file,
930 // after everything else has gone out.
933 delete Mang; Mang = 0;
936 OutStreamer.Finish();
940 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
942 // Get the function symbol.
943 CurrentFnSym = Mang->getSymbol(MF.getFunction());
946 LI = &getAnalysis<MachineLoopInfo>();
950 // SectionCPs - Keep track the alignment, constpool entries per Section.
954 SmallVector<unsigned, 4> CPEs;
955 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
959 /// EmitConstantPool - Print to the current output stream assembly
960 /// representations of the constants in the constant pool MCP. This is
961 /// used to print out constants which have been "spilled to memory" by
962 /// the code generator.
964 void AsmPrinter::EmitConstantPool() {
965 const MachineConstantPool *MCP = MF->getConstantPool();
966 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
967 if (CP.empty()) return;
969 // Calculate sections for constant pool entries. We collect entries to go into
970 // the same section together to reduce amount of section switch statements.
971 SmallVector<SectionCPs, 4> CPSections;
972 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
973 const MachineConstantPoolEntry &CPE = CP[i];
974 unsigned Align = CPE.getAlignment();
977 switch (CPE.getRelocationInfo()) {
978 default: llvm_unreachable("Unknown section kind");
979 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
981 Kind = SectionKind::getReadOnlyWithRelLocal();
984 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
985 case 4: Kind = SectionKind::getMergeableConst4(); break;
986 case 8: Kind = SectionKind::getMergeableConst8(); break;
987 case 16: Kind = SectionKind::getMergeableConst16();break;
988 default: Kind = SectionKind::getMergeableConst(); break;
992 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
994 // The number of sections are small, just do a linear search from the
995 // last section to the first.
997 unsigned SecIdx = CPSections.size();
998 while (SecIdx != 0) {
999 if (CPSections[--SecIdx].S == S) {
1005 SecIdx = CPSections.size();
1006 CPSections.push_back(SectionCPs(S, Align));
1009 if (Align > CPSections[SecIdx].Alignment)
1010 CPSections[SecIdx].Alignment = Align;
1011 CPSections[SecIdx].CPEs.push_back(i);
1014 // Now print stuff into the calculated sections.
1015 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1016 OutStreamer.SwitchSection(CPSections[i].S);
1017 EmitAlignment(Log2_32(CPSections[i].Alignment));
1019 unsigned Offset = 0;
1020 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1021 unsigned CPI = CPSections[i].CPEs[j];
1022 MachineConstantPoolEntry CPE = CP[CPI];
1024 // Emit inter-object padding for alignment.
1025 unsigned AlignMask = CPE.getAlignment() - 1;
1026 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1027 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
1029 const Type *Ty = CPE.getType();
1030 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
1031 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1033 if (CPE.isMachineConstantPoolEntry())
1034 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1036 EmitGlobalConstant(CPE.Val.ConstVal);
1041 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1042 /// by the current function to the current output stream.
1044 void AsmPrinter::EmitJumpTableInfo() {
1045 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1046 if (MJTI == 0) return;
1047 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1048 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1049 if (JT.empty()) return;
1051 // Pick the directive to use to print the jump table entries, and switch to
1052 // the appropriate section.
1053 const Function *F = MF->getFunction();
1054 bool JTInDiffSection = false;
1055 if (// In PIC mode, we need to emit the jump table to the same section as the
1056 // function body itself, otherwise the label differences won't make sense.
1057 // FIXME: Need a better predicate for this: what about custom entries?
1058 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1059 // We should also do if the section name is NULL or function is declared
1060 // in discardable section
1061 // FIXME: this isn't the right predicate, should be based on the MCSection
1062 // for the function.
1063 F->isWeakForLinker()) {
1064 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1066 // Otherwise, drop it in the readonly section.
1067 const MCSection *ReadOnlySection =
1068 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1069 OutStreamer.SwitchSection(ReadOnlySection);
1070 JTInDiffSection = true;
1073 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
1075 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1076 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1078 // If this jump table was deleted, ignore it.
1079 if (JTBBs.empty()) continue;
1081 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1082 // .set directive for each unique entry. This reduces the number of
1083 // relocations the assembler will generate for the jump table.
1084 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1085 MAI->hasSetDirective()) {
1086 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1087 const TargetLowering *TLI = TM.getTargetLowering();
1088 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1089 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1090 const MachineBasicBlock *MBB = JTBBs[ii];
1091 if (!EmittedSets.insert(MBB)) continue;
1093 // .set LJTSet, LBB32-base
1095 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1096 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1097 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1101 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1102 // before each jump table. The first label is never referenced, but tells
1103 // the assembler and linker the extents of the jump table object. The
1104 // second label is actually referenced by the code.
1105 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1106 // FIXME: This doesn't have to have any specific name, just any randomly
1107 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1108 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1110 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1112 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1113 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1117 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1119 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1120 const MachineBasicBlock *MBB,
1121 unsigned UID) const {
1122 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1123 const MCExpr *Value = 0;
1124 switch (MJTI->getEntryKind()) {
1125 case MachineJumpTableInfo::EK_Inline:
1126 llvm_unreachable("Cannot emit EK_Inline jump table entry"); break;
1127 case MachineJumpTableInfo::EK_Custom32:
1128 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1131 case MachineJumpTableInfo::EK_BlockAddress:
1132 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1134 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1136 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1137 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1138 // with a relocation as gp-relative, e.g.:
1140 MCSymbol *MBBSym = MBB->getSymbol();
1141 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1145 case MachineJumpTableInfo::EK_LabelDifference32: {
1146 // EK_LabelDifference32 - Each entry is the address of the block minus
1147 // the address of the jump table. This is used for PIC jump tables where
1148 // gprel32 is not supported. e.g.:
1149 // .word LBB123 - LJTI1_2
1150 // If the .set directive is supported, this is emitted as:
1151 // .set L4_5_set_123, LBB123 - LJTI1_2
1152 // .word L4_5_set_123
1154 // If we have emitted set directives for the jump table entries, print
1155 // them rather than the entries themselves. If we're emitting PIC, then
1156 // emit the table entries as differences between two text section labels.
1157 if (MAI->hasSetDirective()) {
1158 // If we used .set, reference the .set's symbol.
1159 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1163 // Otherwise, use the difference as the jump table entry.
1164 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1165 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1166 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1171 assert(Value && "Unknown entry kind!");
1173 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
1174 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
1178 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1179 /// special global used by LLVM. If so, emit it and return true, otherwise
1180 /// do nothing and return false.
1181 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1182 if (GV->getName() == "llvm.used") {
1183 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1184 EmitLLVMUsedList(GV->getInitializer());
1188 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1189 if (GV->getSection() == "llvm.metadata" ||
1190 GV->hasAvailableExternallyLinkage())
1193 if (!GV->hasAppendingLinkage()) return false;
1195 assert(GV->hasInitializer() && "Not a special LLVM global!");
1197 const TargetData *TD = TM.getTargetData();
1198 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
1199 if (GV->getName() == "llvm.global_ctors") {
1200 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
1201 EmitAlignment(Align);
1202 EmitXXStructorList(GV->getInitializer());
1204 if (TM.getRelocationModel() == Reloc::Static &&
1205 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1206 StringRef Sym(".constructors_used");
1207 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1213 if (GV->getName() == "llvm.global_dtors") {
1214 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
1215 EmitAlignment(Align);
1216 EmitXXStructorList(GV->getInitializer());
1218 if (TM.getRelocationModel() == Reloc::Static &&
1219 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1220 StringRef Sym(".destructors_used");
1221 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1230 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1231 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1232 /// is true, as being used with this directive.
1233 void AsmPrinter::EmitLLVMUsedList(const Constant *List) {
1234 // Should be an array of 'i8*'.
1235 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1236 if (InitList == 0) return;
1238 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1239 const GlobalValue *GV =
1240 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1241 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1242 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
1246 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
1247 /// function pointers, ignoring the init priority.
1248 void AsmPrinter::EmitXXStructorList(const Constant *List) {
1249 // Should be an array of '{ int, void ()* }' structs. The first value is the
1250 // init priority, which we ignore.
1251 if (!isa<ConstantArray>(List)) return;
1252 const ConstantArray *InitList = cast<ConstantArray>(List);
1253 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1254 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1255 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1257 if (CS->getOperand(1)->isNullValue())
1258 return; // Found a null terminator, exit printing.
1259 // Emit the function pointer.
1260 EmitGlobalConstant(CS->getOperand(1));
1264 //===--------------------------------------------------------------------===//
1265 // Emission and print routines
1268 /// EmitInt8 - Emit a byte directive and value.
1270 void AsmPrinter::EmitInt8(int Value) const {
1271 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
1274 /// EmitInt16 - Emit a short directive and value.
1276 void AsmPrinter::EmitInt16(int Value) const {
1277 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
1280 /// EmitInt32 - Emit a long directive and value.
1282 void AsmPrinter::EmitInt32(int Value) const {
1283 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
1286 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1287 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1288 /// labels. This implicitly uses .set if it is available.
1289 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1290 unsigned Size) const {
1291 // Get the Hi-Lo expression.
1292 const MCExpr *Diff =
1293 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1294 MCSymbolRefExpr::Create(Lo, OutContext),
1297 if (!MAI->hasSetDirective()) {
1298 OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
1302 // Otherwise, emit with .set (aka assignment).
1303 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1304 OutStreamer.EmitAssignment(SetLabel, Diff);
1305 OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
1308 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1309 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1310 /// specify the labels. This implicitly uses .set if it is available.
1311 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1312 const MCSymbol *Lo, unsigned Size)
1315 // Emit Hi+Offset - Lo
1316 // Get the Hi+Offset expression.
1317 const MCExpr *Plus =
1318 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1319 MCConstantExpr::Create(Offset, OutContext),
1322 // Get the Hi+Offset-Lo expression.
1323 const MCExpr *Diff =
1324 MCBinaryExpr::CreateSub(Plus,
1325 MCSymbolRefExpr::Create(Lo, OutContext),
1328 if (!MAI->hasSetDirective())
1329 OutStreamer.EmitValue(Diff, 4, 0/*AddrSpace*/);
1331 // Otherwise, emit with .set (aka assignment).
1332 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1333 OutStreamer.EmitAssignment(SetLabel, Diff);
1334 OutStreamer.EmitSymbolValue(SetLabel, 4, 0/*AddrSpace*/);
1338 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1339 /// where the size in bytes of the directive is specified by Size and Label
1340 /// specifies the label. This implicitly uses .set if it is available.
1341 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1345 // Emit Label+Offset
1346 const MCExpr *Plus =
1347 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Label, OutContext),
1348 MCConstantExpr::Create(Offset, OutContext),
1351 OutStreamer.EmitValue(Plus, 4, 0/*AddrSpace*/);
1355 //===----------------------------------------------------------------------===//
1357 // EmitAlignment - Emit an alignment directive to the specified power of
1358 // two boundary. For example, if you pass in 3 here, you will get an 8
1359 // byte alignment. If a global value is specified, and if that global has
1360 // an explicit alignment requested, it will override the alignment request
1361 // if required for correctness.
1363 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1364 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getTargetData(), NumBits);
1366 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1368 if (getCurrentSection()->getKind().isText())
1369 OutStreamer.EmitCodeAlignment(1 << NumBits);
1371 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1374 //===----------------------------------------------------------------------===//
1375 // Constant emission.
1376 //===----------------------------------------------------------------------===//
1378 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
1380 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
1381 MCContext &Ctx = AP.OutContext;
1383 if (CV->isNullValue() || isa<UndefValue>(CV))
1384 return MCConstantExpr::Create(0, Ctx);
1386 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1387 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1389 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1390 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
1392 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1393 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1395 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1397 llvm_unreachable("Unknown constant value to lower!");
1398 return MCConstantExpr::Create(0, Ctx);
1401 switch (CE->getOpcode()) {
1403 // If the code isn't optimized, there may be outstanding folding
1404 // opportunities. Attempt to fold the expression using TargetData as a
1405 // last resort before giving up.
1407 ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
1409 return LowerConstant(C, AP);
1411 // Otherwise report the problem to the user.
1414 raw_string_ostream OS(S);
1415 OS << "Unsupported expression in static initializer: ";
1416 WriteAsOperand(OS, CE, /*PrintType=*/false,
1417 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1418 report_fatal_error(OS.str());
1420 return MCConstantExpr::Create(0, Ctx);
1421 case Instruction::GetElementPtr: {
1422 const TargetData &TD = *AP.TM.getTargetData();
1423 // Generate a symbolic expression for the byte address
1424 const Constant *PtrVal = CE->getOperand(0);
1425 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
1426 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
1429 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
1433 // Truncate/sext the offset to the pointer size.
1434 if (TD.getPointerSizeInBits() != 64) {
1435 int SExtAmount = 64-TD.getPointerSizeInBits();
1436 Offset = (Offset << SExtAmount) >> SExtAmount;
1439 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1443 case Instruction::Trunc:
1444 // We emit the value and depend on the assembler to truncate the generated
1445 // expression properly. This is important for differences between
1446 // blockaddress labels. Since the two labels are in the same function, it
1447 // is reasonable to treat their delta as a 32-bit value.
1449 case Instruction::BitCast:
1450 return LowerConstant(CE->getOperand(0), AP);
1452 case Instruction::IntToPtr: {
1453 const TargetData &TD = *AP.TM.getTargetData();
1454 // Handle casts to pointers by changing them into casts to the appropriate
1455 // integer type. This promotes constant folding and simplifies this code.
1456 Constant *Op = CE->getOperand(0);
1457 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1459 return LowerConstant(Op, AP);
1462 case Instruction::PtrToInt: {
1463 const TargetData &TD = *AP.TM.getTargetData();
1464 // Support only foldable casts to/from pointers that can be eliminated by
1465 // changing the pointer to the appropriately sized integer type.
1466 Constant *Op = CE->getOperand(0);
1467 const Type *Ty = CE->getType();
1469 const MCExpr *OpExpr = LowerConstant(Op, AP);
1471 // We can emit the pointer value into this slot if the slot is an
1472 // integer slot equal to the size of the pointer.
1473 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1476 // Otherwise the pointer is smaller than the resultant integer, mask off
1477 // the high bits so we are sure to get a proper truncation if the input is
1479 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1480 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1481 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1484 // The MC library also has a right-shift operator, but it isn't consistently
1485 // signed or unsigned between different targets.
1486 case Instruction::Add:
1487 case Instruction::Sub:
1488 case Instruction::Mul:
1489 case Instruction::SDiv:
1490 case Instruction::SRem:
1491 case Instruction::Shl:
1492 case Instruction::And:
1493 case Instruction::Or:
1494 case Instruction::Xor: {
1495 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
1496 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
1497 switch (CE->getOpcode()) {
1498 default: llvm_unreachable("Unknown binary operator constant cast expr");
1499 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1500 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1501 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1502 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1503 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1504 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1505 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1506 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1507 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1513 static void EmitGlobalConstantImpl(const Constant *C, unsigned AddrSpace,
1516 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1518 if (AddrSpace != 0 || !CA->isString()) {
1519 // Not a string. Print the values in successive locations
1520 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1521 EmitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
1525 // Otherwise, it can be emitted as .ascii.
1526 SmallVector<char, 128> TmpVec;
1527 TmpVec.reserve(CA->getNumOperands());
1528 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1529 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
1531 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
1534 static void EmitGlobalConstantVector(const ConstantVector *CV,
1535 unsigned AddrSpace, AsmPrinter &AP) {
1536 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1537 EmitGlobalConstantImpl(CV->getOperand(i), AddrSpace, AP);
1539 const TargetData &TD = *AP.TM.getTargetData();
1540 unsigned Size = TD.getTypeAllocSize(CV->getType());
1541 unsigned EmittedSize = TD.getTypeAllocSize(CV->getType()->getElementType()) *
1542 CV->getType()->getNumElements();
1543 if (unsigned Padding = Size - EmittedSize)
1544 AP.OutStreamer.EmitZeros(Padding, AddrSpace);
1547 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1548 unsigned AddrSpace, AsmPrinter &AP) {
1549 // Print the fields in successive locations. Pad to align if needed!
1550 const TargetData *TD = AP.TM.getTargetData();
1551 unsigned Size = TD->getTypeAllocSize(CS->getType());
1552 const StructLayout *Layout = TD->getStructLayout(CS->getType());
1553 uint64_t SizeSoFar = 0;
1554 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1555 const Constant *Field = CS->getOperand(i);
1557 // Check if padding is needed and insert one or more 0s.
1558 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1559 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1560 - Layout->getElementOffset(i)) - FieldSize;
1561 SizeSoFar += FieldSize + PadSize;
1563 // Now print the actual field value.
1564 EmitGlobalConstantImpl(Field, AddrSpace, AP);
1566 // Insert padding - this may include padding to increase the size of the
1567 // current field up to the ABI size (if the struct is not packed) as well
1568 // as padding to ensure that the next field starts at the right offset.
1569 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1571 assert(SizeSoFar == Layout->getSizeInBytes() &&
1572 "Layout of constant struct may be incorrect!");
1575 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1577 // FP Constants are printed as integer constants to avoid losing
1579 if (CFP->getType()->isDoubleTy()) {
1580 if (AP.isVerbose()) {
1581 double Val = CFP->getValueAPF().convertToDouble();
1582 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1585 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1586 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1590 if (CFP->getType()->isFloatTy()) {
1591 if (AP.isVerbose()) {
1592 float Val = CFP->getValueAPF().convertToFloat();
1593 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1595 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1596 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1600 if (CFP->getType()->isX86_FP80Ty()) {
1601 // all long double variants are printed as hex
1602 // API needed to prevent premature destruction
1603 APInt API = CFP->getValueAPF().bitcastToAPInt();
1604 const uint64_t *p = API.getRawData();
1605 if (AP.isVerbose()) {
1606 // Convert to double so we can print the approximate val as a comment.
1607 APFloat DoubleVal = CFP->getValueAPF();
1609 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1611 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1612 << DoubleVal.convertToDouble() << '\n';
1615 if (AP.TM.getTargetData()->isBigEndian()) {
1616 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1617 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1619 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1620 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1623 // Emit the tail padding for the long double.
1624 const TargetData &TD = *AP.TM.getTargetData();
1625 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1626 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1630 assert(CFP->getType()->isPPC_FP128Ty() &&
1631 "Floating point constant type not handled");
1632 // All long double variants are printed as hex
1633 // API needed to prevent premature destruction.
1634 APInt API = CFP->getValueAPF().bitcastToAPInt();
1635 const uint64_t *p = API.getRawData();
1636 if (AP.TM.getTargetData()->isBigEndian()) {
1637 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1638 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1640 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1641 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1645 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1646 unsigned AddrSpace, AsmPrinter &AP) {
1647 const TargetData *TD = AP.TM.getTargetData();
1648 unsigned BitWidth = CI->getBitWidth();
1649 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1651 // We don't expect assemblers to support integer data directives
1652 // for more than 64 bits, so we emit the data in at most 64-bit
1653 // quantities at a time.
1654 const uint64_t *RawData = CI->getValue().getRawData();
1655 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1656 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1657 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1661 static void EmitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace,
1663 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1664 uint64_t Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1665 return AP.OutStreamer.EmitZeros(Size, AddrSpace);
1668 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1669 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1676 AP.OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1677 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1680 EmitGlobalConstantLargeInt(CI, AddrSpace, AP);
1685 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1686 return EmitGlobalConstantArray(CVA, AddrSpace, AP);
1688 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1689 return EmitGlobalConstantStruct(CVS, AddrSpace, AP);
1691 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1692 return EmitGlobalConstantFP(CFP, AddrSpace, AP);
1694 if (isa<ConstantPointerNull>(CV)) {
1695 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1696 AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
1700 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1701 return EmitGlobalConstantVector(V, AddrSpace, AP);
1703 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1704 // thread the streamer with EmitValue.
1705 AP.OutStreamer.EmitValue(LowerConstant(CV, AP),
1706 AP.TM.getTargetData()->getTypeAllocSize(CV->getType()),
1710 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1711 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1712 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1714 EmitGlobalConstantImpl(CV, AddrSpace, *this);
1715 else if (MAI->hasSubsectionsViaSymbols()) {
1716 // If the global has zero size, emit a single byte so that two labels don't
1717 // look like they are at the same location.
1718 OutStreamer.EmitIntValue(0, 1, AddrSpace);
1722 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1723 // Target doesn't support this yet!
1724 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1727 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1729 OS << '+' << Offset;
1730 else if (Offset < 0)
1734 //===----------------------------------------------------------------------===//
1735 // Symbol Lowering Routines.
1736 //===----------------------------------------------------------------------===//
1738 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1739 /// temporary label with the specified stem and unique ID.
1740 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1741 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1745 /// GetTempSymbol - Return an assembler temporary label with the specified
1747 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1748 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1753 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
1754 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
1757 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1758 return MMI->getAddrLabelSymbol(BB);
1761 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1762 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1763 return OutContext.GetOrCreateSymbol
1764 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1765 + "_" + Twine(CPID));
1768 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1769 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1770 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1773 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1774 /// FIXME: privatize to AsmPrinter.
1775 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1776 return OutContext.GetOrCreateSymbol
1777 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1778 Twine(UID) + "_set_" + Twine(MBBID));
1781 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1782 /// global value name as its base, with the specified suffix, and where the
1783 /// symbol is forced to have private linkage if ForcePrivate is true.
1784 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1786 bool ForcePrivate) const {
1787 SmallString<60> NameStr;
1788 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1789 NameStr.append(Suffix.begin(), Suffix.end());
1790 return OutContext.GetOrCreateSymbol(NameStr.str());
1793 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1795 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1796 SmallString<60> NameStr;
1797 Mang->getNameWithPrefix(NameStr, Sym);
1798 return OutContext.GetOrCreateSymbol(NameStr.str());
1803 /// PrintParentLoopComment - Print comments about parent loops of this one.
1804 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1805 unsigned FunctionNumber) {
1806 if (Loop == 0) return;
1807 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1808 OS.indent(Loop->getLoopDepth()*2)
1809 << "Parent Loop BB" << FunctionNumber << "_"
1810 << Loop->getHeader()->getNumber()
1811 << " Depth=" << Loop->getLoopDepth() << '\n';
1815 /// PrintChildLoopComment - Print comments about child loops within
1816 /// the loop for this basic block, with nesting.
1817 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1818 unsigned FunctionNumber) {
1819 // Add child loop information
1820 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1821 OS.indent((*CL)->getLoopDepth()*2)
1822 << "Child Loop BB" << FunctionNumber << "_"
1823 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1825 PrintChildLoopComment(OS, *CL, FunctionNumber);
1829 /// EmitBasicBlockLoopComments - Pretty-print comments for basic blocks.
1830 static void EmitBasicBlockLoopComments(const MachineBasicBlock &MBB,
1831 const MachineLoopInfo *LI,
1832 const AsmPrinter &AP) {
1833 // Add loop depth information
1834 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1835 if (Loop == 0) return;
1837 MachineBasicBlock *Header = Loop->getHeader();
1838 assert(Header && "No header for loop");
1840 // If this block is not a loop header, just print out what is the loop header
1842 if (Header != &MBB) {
1843 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1844 Twine(AP.getFunctionNumber())+"_" +
1845 Twine(Loop->getHeader()->getNumber())+
1846 " Depth="+Twine(Loop->getLoopDepth()));
1850 // Otherwise, it is a loop header. Print out information about child and
1852 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1854 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1857 OS.indent(Loop->getLoopDepth()*2-2);
1862 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1864 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1868 /// EmitBasicBlockStart - This method prints the label for the specified
1869 /// MachineBasicBlock, an alignment (if present) and a comment describing
1870 /// it if appropriate.
1871 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1872 // Emit an alignment directive for this block, if needed.
1873 if (unsigned Align = MBB->getAlignment())
1874 EmitAlignment(Log2_32(Align));
1876 // If the block has its address taken, emit any labels that were used to
1877 // reference the block. It is possible that there is more than one label
1878 // here, because multiple LLVM BB's may have been RAUW'd to this block after
1879 // the references were generated.
1880 if (MBB->hasAddressTaken()) {
1881 const BasicBlock *BB = MBB->getBasicBlock();
1883 OutStreamer.AddComment("Block address taken");
1885 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
1887 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
1888 OutStreamer.EmitLabel(Syms[i]);
1891 // Print the main label for the block.
1892 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
1893 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
1894 if (const BasicBlock *BB = MBB->getBasicBlock())
1896 OutStreamer.AddComment("%" + BB->getName());
1898 EmitBasicBlockLoopComments(*MBB, LI, *this);
1900 // NOTE: Want this comment at start of line, don't emit with AddComment.
1901 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
1902 Twine(MBB->getNumber()) + ":");
1906 if (const BasicBlock *BB = MBB->getBasicBlock())
1908 OutStreamer.AddComment("%" + BB->getName());
1909 EmitBasicBlockLoopComments(*MBB, LI, *this);
1912 OutStreamer.EmitLabel(MBB->getSymbol());
1916 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
1917 bool IsDefinition) const {
1918 MCSymbolAttr Attr = MCSA_Invalid;
1920 switch (Visibility) {
1922 case GlobalValue::HiddenVisibility:
1924 Attr = MAI->getHiddenVisibilityAttr();
1926 Attr = MAI->getHiddenDeclarationVisibilityAttr();
1928 case GlobalValue::ProtectedVisibility:
1929 Attr = MAI->getProtectedVisibilityAttr();
1933 if (Attr != MCSA_Invalid)
1934 OutStreamer.EmitSymbolAttribute(Sym, Attr);
1937 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
1938 /// exactly one predecessor and the control transfer mechanism between
1939 /// the predecessor and this block is a fall-through.
1941 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
1942 // If this is a landing pad, it isn't a fall through. If it has no preds,
1943 // then nothing falls through to it.
1944 if (MBB->isLandingPad() || MBB->pred_empty())
1947 // If there isn't exactly one predecessor, it can't be a fall through.
1948 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
1950 if (PI2 != MBB->pred_end())
1953 // The predecessor has to be immediately before this block.
1954 MachineBasicBlock *Pred = *PI;
1956 if (!Pred->isLayoutSuccessor(MBB))
1959 // If the block is completely empty, then it definitely does fall through.
1963 // Check the terminators in the previous blocks
1964 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
1965 IE = Pred->end(); II != IE; ++II) {
1966 MachineInstr &MI = *II;
1968 // If it is not a simple branch, we are in a table somewhere.
1969 if (!MI.getDesc().isBranch() || MI.getDesc().isIndirectBranch())
1972 // If we are the operands of one of the branches, this is not
1974 for (MachineInstr::mop_iterator OI = MI.operands_begin(),
1975 OE = MI.operands_end(); OI != OE; ++OI) {
1976 const MachineOperand& OP = *OI;
1979 if (OP.isMBB() && OP.getMBB() == MBB)
1989 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1990 if (!S->usesMetadata())
1993 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
1994 gcp_map_type::iterator GCPI = GCMap.find(S);
1995 if (GCPI != GCMap.end())
1996 return GCPI->second;
1998 const char *Name = S->getName().c_str();
2000 for (GCMetadataPrinterRegistry::iterator
2001 I = GCMetadataPrinterRegistry::begin(),
2002 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2003 if (strcmp(Name, I->getName()) == 0) {
2004 GCMetadataPrinter *GMP = I->instantiate();
2006 GCMap.insert(std::make_pair(S, GMP));
2010 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));