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 #include "DwarfDebug.h"
17 #include "DwarfException.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/ConstantFolding.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/CodeGen/GCMetadataPrinter.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/DebugInfo.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCContext.h"
35 #include "llvm/MC/MCExpr.h"
36 #include "llvm/MC/MCInst.h"
37 #include "llvm/MC/MCSection.h"
38 #include "llvm/MC/MCStreamer.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Target/Mangler.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetLowering.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
52 static const char *DWARFGroupName = "DWARF Emission";
53 static const char *DbgTimerName = "DWARF Debug Writer";
54 static const char *EHTimerName = "DWARF Exception Writer";
56 STATISTIC(EmittedInsts, "Number of machine instrs printed");
58 char AsmPrinter::ID = 0;
60 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
61 static gcp_map_type &getGCMap(void *&P) {
63 P = new gcp_map_type();
64 return *(gcp_map_type*)P;
68 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
69 /// value in log2 form. This rounds up to the preferred alignment if possible
71 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
72 unsigned InBits = 0) {
74 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
75 NumBits = TD.getPreferredAlignmentLog(GVar);
77 // If InBits is specified, round it to it.
81 // If the GV has a specified alignment, take it into account.
82 if (GV->getAlignment() == 0)
85 unsigned GVAlign = Log2_32(GV->getAlignment());
87 // If the GVAlign is larger than NumBits, or if we are required to obey
88 // NumBits because the GV has an assigned section, obey it.
89 if (GVAlign > NumBits || GV->hasSection())
94 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
95 : MachineFunctionPass(ID),
96 TM(tm), MAI(tm.getMCAsmInfo()),
97 OutContext(Streamer.getContext()),
98 OutStreamer(Streamer),
99 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
100 DD = 0; DE = 0; MMI = 0; LI = 0;
101 CurrentFnSym = CurrentFnSymForSize = 0;
102 GCMetadataPrinters = 0;
103 VerboseAsm = Streamer.isVerboseAsm();
106 AsmPrinter::~AsmPrinter() {
107 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
109 if (GCMetadataPrinters != 0) {
110 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
112 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
115 GCMetadataPrinters = 0;
121 /// getFunctionNumber - Return a unique ID for the current function.
123 unsigned AsmPrinter::getFunctionNumber() const {
124 return MF->getFunctionNumber();
127 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
128 return TM.getTargetLowering()->getObjFileLowering();
131 /// getDataLayout - Return information about data layout.
132 const DataLayout &AsmPrinter::getDataLayout() const {
133 return *TM.getDataLayout();
136 StringRef AsmPrinter::getTargetTriple() const {
137 return TM.getTargetTriple();
140 /// getCurrentSection() - Return the current section we are emitting to.
141 const MCSection *AsmPrinter::getCurrentSection() const {
142 return OutStreamer.getCurrentSection().first;
147 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
148 AU.setPreservesAll();
149 MachineFunctionPass::getAnalysisUsage(AU);
150 AU.addRequired<MachineModuleInfo>();
151 AU.addRequired<GCModuleInfo>();
153 AU.addRequired<MachineLoopInfo>();
156 bool AsmPrinter::doInitialization(Module &M) {
157 OutStreamer.InitStreamer();
159 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
160 MMI->AnalyzeModule(M);
162 // Initialize TargetLoweringObjectFile.
163 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
164 .Initialize(OutContext, TM);
166 Mang = new Mangler(OutContext, *TM.getDataLayout());
168 // Allow the target to emit any magic that it wants at the start of the file.
169 EmitStartOfAsmFile(M);
171 // Very minimal debug info. It is ignored if we emit actual debug info. If we
172 // don't, this at least helps the user find where a global came from.
173 if (MAI->hasSingleParameterDotFile()) {
175 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
178 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
179 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
180 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
181 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
182 MP->beginAssembly(*this);
184 // Emit module-level inline asm if it exists.
185 if (!M.getModuleInlineAsm().empty()) {
186 OutStreamer.AddComment("Start of file scope inline assembly");
187 OutStreamer.AddBlankLine();
188 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
189 OutStreamer.AddComment("End of file scope inline assembly");
190 OutStreamer.AddBlankLine();
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);
211 llvm_unreachable("Unknown exception type.");
214 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
215 switch ((GlobalValue::LinkageTypes)Linkage) {
216 case GlobalValue::CommonLinkage:
217 case GlobalValue::LinkOnceAnyLinkage:
218 case GlobalValue::LinkOnceODRLinkage:
219 case GlobalValue::LinkOnceODRAutoHideLinkage:
220 case GlobalValue::WeakAnyLinkage:
221 case GlobalValue::WeakODRLinkage:
222 case GlobalValue::LinkerPrivateWeakLinkage:
223 if (MAI->getWeakDefDirective() != 0) {
225 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
227 if ((GlobalValue::LinkageTypes)Linkage !=
228 GlobalValue::LinkOnceODRAutoHideLinkage)
229 // .weak_definition _foo
230 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
232 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
233 } else if (MAI->getLinkOnceDirective() != 0) {
235 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
236 //NOTE: linkonce is handled by the section the symbol was assigned to.
239 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
242 case GlobalValue::DLLExportLinkage:
243 case GlobalValue::AppendingLinkage:
244 // FIXME: appending linkage variables should go into a section of
245 // their name or something. For now, just emit them as external.
246 case GlobalValue::ExternalLinkage:
247 // If external or appending, declare as a global symbol.
249 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
251 case GlobalValue::PrivateLinkage:
252 case GlobalValue::InternalLinkage:
253 case GlobalValue::LinkerPrivateLinkage:
256 llvm_unreachable("Unknown linkage type!");
261 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
262 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
263 if (GV->hasInitializer()) {
264 // Check to see if this is a special global used by LLVM, if so, emit it.
265 if (EmitSpecialLLVMGlobal(GV))
269 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
270 /*PrintType=*/false, GV->getParent());
271 OutStreamer.GetCommentOS() << '\n';
275 MCSymbol *GVSym = Mang->getSymbol(GV);
276 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
278 if (!GV->hasInitializer()) // External globals require no extra code.
281 if (MAI->hasDotTypeDotSizeDirective())
282 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
284 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
286 const DataLayout *TD = TM.getDataLayout();
287 uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
289 // If the alignment is specified, we *must* obey it. Overaligning a global
290 // with a specified alignment is a prompt way to break globals emitted to
291 // sections and expected to be contiguous (e.g. ObjC metadata).
292 unsigned AlignLog = getGVAlignmentLog2(GV, *TD);
294 // Handle common and BSS local symbols (.lcomm).
295 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
296 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
297 unsigned Align = 1 << AlignLog;
299 // Handle common symbols.
300 if (GVKind.isCommon()) {
301 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
305 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
309 // Handle local BSS symbols.
310 if (MAI->hasMachoZeroFillDirective()) {
311 const MCSection *TheSection =
312 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
313 // .zerofill __DATA, __bss, _foo, 400, 5
314 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
318 // Use .lcomm only if it supports user-specified alignment.
319 // Otherwise, while it would still be correct to use .lcomm in some
320 // cases (e.g. when Align == 1), the external assembler might enfore
321 // some -unknown- default alignment behavior, which could cause
322 // spurious differences between external and integrated assembler.
323 // Prefer to simply fall back to .local / .comm in this case.
324 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
326 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
330 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
334 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
336 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
340 const MCSection *TheSection =
341 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
343 // Handle the zerofill directive on darwin, which is a special form of BSS
345 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
346 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
349 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
350 // .zerofill __DATA, __common, _foo, 400, 5
351 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
355 // Handle thread local data for mach-o which requires us to output an
356 // additional structure of data and mangle the original symbol so that we
357 // can reference it later.
359 // TODO: This should become an "emit thread local global" method on TLOF.
360 // All of this macho specific stuff should be sunk down into TLOFMachO and
361 // stuff like "TLSExtraDataSection" should no longer be part of the parent
362 // TLOF class. This will also make it more obvious that stuff like
363 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
365 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
366 // Emit the .tbss symbol
368 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
370 if (GVKind.isThreadBSS())
371 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
372 else if (GVKind.isThreadData()) {
373 OutStreamer.SwitchSection(TheSection);
375 EmitAlignment(AlignLog, GV);
376 OutStreamer.EmitLabel(MangSym);
378 EmitGlobalConstant(GV->getInitializer());
381 OutStreamer.AddBlankLine();
383 // Emit the variable struct for the runtime.
384 const MCSection *TLVSect
385 = getObjFileLowering().getTLSExtraDataSection();
387 OutStreamer.SwitchSection(TLVSect);
388 // Emit the linkage here.
389 EmitLinkage(GV->getLinkage(), GVSym);
390 OutStreamer.EmitLabel(GVSym);
392 // Three pointers in size:
393 // - __tlv_bootstrap - used to make sure support exists
394 // - spare pointer, used when mapped by the runtime
395 // - pointer to mangled symbol above with initializer
396 unsigned PtrSize = TD->getPointerSizeInBits()/8;
397 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
399 OutStreamer.EmitIntValue(0, PtrSize);
400 OutStreamer.EmitSymbolValue(MangSym, PtrSize);
402 OutStreamer.AddBlankLine();
406 OutStreamer.SwitchSection(TheSection);
408 EmitLinkage(GV->getLinkage(), GVSym);
409 EmitAlignment(AlignLog, GV);
411 OutStreamer.EmitLabel(GVSym);
413 EmitGlobalConstant(GV->getInitializer());
415 if (MAI->hasDotTypeDotSizeDirective())
417 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
419 OutStreamer.AddBlankLine();
422 /// EmitFunctionHeader - This method emits the header for the current
424 void AsmPrinter::EmitFunctionHeader() {
425 // Print out constants referenced by the function
428 // Print the 'header' of function.
429 const Function *F = MF->getFunction();
431 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
432 EmitVisibility(CurrentFnSym, F->getVisibility());
434 EmitLinkage(F->getLinkage(), CurrentFnSym);
435 EmitAlignment(MF->getAlignment(), F);
437 if (MAI->hasDotTypeDotSizeDirective())
438 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
441 WriteAsOperand(OutStreamer.GetCommentOS(), F,
442 /*PrintType=*/false, F->getParent());
443 OutStreamer.GetCommentOS() << '\n';
446 // Emit the CurrentFnSym. This is a virtual function to allow targets to
447 // do their wild and crazy things as required.
448 EmitFunctionEntryLabel();
450 // If the function had address-taken blocks that got deleted, then we have
451 // references to the dangling symbols. Emit them at the start of the function
452 // so that we don't get references to undefined symbols.
453 std::vector<MCSymbol*> DeadBlockSyms;
454 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
455 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
456 OutStreamer.AddComment("Address taken block that was later removed");
457 OutStreamer.EmitLabel(DeadBlockSyms[i]);
460 // Add some workaround for linkonce linkage on Cygwin\MinGW.
461 if (MAI->getLinkOnceDirective() != 0 &&
462 (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
463 // FIXME: What is this?
465 OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
466 CurrentFnSym->getName());
467 OutStreamer.EmitLabel(FakeStub);
470 // Emit pre-function debug and/or EH information.
472 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
473 DE->BeginFunction(MF);
476 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
477 DD->beginFunction(MF);
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");
493 /// emitComments - Pretty-print comments for instructions.
494 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
495 const MachineFunction *MF = MI.getParent()->getParent();
496 const TargetMachine &TM = MF->getTarget();
498 // Check for spills and reloads
501 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
503 // We assume a single instruction only has a spill or reload, not
505 const MachineMemOperand *MMO;
506 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
507 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
508 MMO = *MI.memoperands_begin();
509 CommentOS << MMO->getSize() << "-byte Reload\n";
511 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
512 if (FrameInfo->isSpillSlotObjectIndex(FI))
513 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
514 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
515 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
516 MMO = *MI.memoperands_begin();
517 CommentOS << MMO->getSize() << "-byte Spill\n";
519 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
520 if (FrameInfo->isSpillSlotObjectIndex(FI))
521 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
524 // Check for spill-induced copies
525 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
526 CommentOS << " Reload Reuse\n";
529 /// emitImplicitDef - This method emits the specified machine instruction
530 /// that is an implicit def.
531 static void emitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
532 unsigned RegNo = MI->getOperand(0).getReg();
533 AP.OutStreamer.AddComment(Twine("implicit-def: ") +
534 AP.TM.getRegisterInfo()->getName(RegNo));
535 AP.OutStreamer.AddBlankLine();
538 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
539 std::string Str = "kill:";
540 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
541 const MachineOperand &Op = MI->getOperand(i);
542 assert(Op.isReg() && "KILL instruction must have only register operands");
544 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
545 Str += (Op.isDef() ? "<def>" : "<kill>");
547 AP.OutStreamer.AddComment(Str);
548 AP.OutStreamer.AddBlankLine();
551 /// emitDebugValueComment - This method handles the target-independent form
552 /// of DBG_VALUE, returning true if it was able to do so. A false return
553 /// means the target will need to handle MI in EmitInstruction.
554 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
555 // This code handles only the 3-operand target-independent form.
556 if (MI->getNumOperands() != 3)
559 SmallString<128> Str;
560 raw_svector_ostream OS(Str);
561 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
563 // cast away const; DIetc do not take const operands for some reason.
564 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
565 if (V.getContext().isSubprogram())
566 OS << DISubprogram(V.getContext()).getDisplayName() << ":";
567 OS << V.getName() << " <- ";
569 // Register or immediate value. Register 0 means undef.
570 if (MI->getOperand(0).isFPImm()) {
571 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
572 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
573 OS << (double)APF.convertToFloat();
574 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
575 OS << APF.convertToDouble();
577 // There is no good way to print long double. Convert a copy to
578 // double. Ah well, it's only a comment.
580 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
582 OS << "(long double) " << APF.convertToDouble();
584 } else if (MI->getOperand(0).isImm()) {
585 OS << MI->getOperand(0).getImm();
586 } else if (MI->getOperand(0).isCImm()) {
587 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
589 assert(MI->getOperand(0).isReg() && "Unknown operand type");
590 if (MI->getOperand(0).getReg() == 0) {
591 // Suppress offset, it is not meaningful here.
593 // NOTE: Want this comment at start of line, don't emit with AddComment.
594 AP.OutStreamer.EmitRawText(OS.str());
597 OS << AP.TM.getRegisterInfo()->getName(MI->getOperand(0).getReg());
600 OS << '+' << MI->getOperand(1).getImm();
601 // NOTE: Want this comment at start of line, don't emit with AddComment.
602 AP.OutStreamer.EmitRawText(OS.str());
606 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
607 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
608 MF->getFunction()->needsUnwindTableEntry())
611 if (MMI->hasDebugInfo())
617 bool AsmPrinter::needsSEHMoves() {
618 return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
619 MF->getFunction()->needsUnwindTableEntry();
622 bool AsmPrinter::needsRelocationsForDwarfStringPool() const {
623 return MAI->doesDwarfUseRelocationsAcrossSections();
626 void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
627 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
629 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
632 if (needsCFIMoves() == CFI_M_None)
635 if (MMI->getCompactUnwindEncoding() != 0)
636 OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
638 MachineModuleInfo &MMI = MF->getMMI();
639 const std::vector<MachineMove> &Moves = MMI.getFrameMoves();
640 bool FoundOne = false;
642 for (std::vector<MachineMove>::const_iterator I = Moves.begin(),
645 if (I->getLabel() == Label) {
646 EmitCFIFrameMove(*I);
653 /// EmitFunctionBody - This method emits the body and trailer for a
655 void AsmPrinter::EmitFunctionBody() {
656 // Emit target-specific gunk before the function body.
657 EmitFunctionBodyStart();
659 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
661 // Print out code for the function.
662 bool HasAnyRealCode = false;
663 const MachineInstr *LastMI = 0;
664 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
666 // Print a label for the basic block.
667 EmitBasicBlockStart(I);
668 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
672 // Print the assembly for the instruction.
673 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
674 !II->isDebugValue()) {
675 HasAnyRealCode = true;
679 if (ShouldPrintDebugScopes) {
680 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
681 DD->beginInstruction(II);
685 emitComments(*II, OutStreamer.GetCommentOS());
687 switch (II->getOpcode()) {
688 case TargetOpcode::PROLOG_LABEL:
689 emitPrologLabel(*II);
692 case TargetOpcode::EH_LABEL:
693 case TargetOpcode::GC_LABEL:
694 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
696 case TargetOpcode::INLINEASM:
699 case TargetOpcode::DBG_VALUE:
701 if (!emitDebugValueComment(II, *this))
705 case TargetOpcode::IMPLICIT_DEF:
706 if (isVerbose()) emitImplicitDef(II, *this);
708 case TargetOpcode::KILL:
709 if (isVerbose()) emitKill(II, *this);
712 if (!TM.hasMCUseLoc())
713 MCLineEntry::Make(&OutStreamer, getCurrentSection());
719 if (ShouldPrintDebugScopes) {
720 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
721 DD->endInstruction(II);
726 // If the last instruction was a prolog label, then we have a situation where
727 // we emitted a prolog but no function body. This results in the ending prolog
728 // label equaling the end of function label and an invalid "row" in the
729 // FDE. We need to emit a noop in this situation so that the FDE's rows are
731 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
733 // If the function is empty and the object file uses .subsections_via_symbols,
734 // then we need to emit *something* to the function body to prevent the
735 // labels from collapsing together. Just emit a noop.
736 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
738 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
739 if (Noop.getOpcode()) {
740 OutStreamer.AddComment("avoids zero-length function");
741 OutStreamer.EmitInstruction(Noop);
742 } else // Target not mc-ized yet.
743 OutStreamer.EmitRawText(StringRef("\tnop\n"));
746 const Function *F = MF->getFunction();
747 for (Function::const_iterator i = F->begin(), e = F->end(); i != e; ++i) {
748 const BasicBlock *BB = i;
749 if (!BB->hasAddressTaken())
751 MCSymbol *Sym = GetBlockAddressSymbol(BB);
752 if (Sym->isDefined())
754 OutStreamer.AddComment("Address of block that was removed by CodeGen");
755 OutStreamer.EmitLabel(Sym);
758 // Emit target-specific gunk after the function body.
759 EmitFunctionBodyEnd();
761 // If the target wants a .size directive for the size of the function, emit
763 if (MAI->hasDotTypeDotSizeDirective()) {
764 // Create a symbol for the end of function, so we can get the size as
765 // difference between the function label and the temp label.
766 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
767 OutStreamer.EmitLabel(FnEndLabel);
769 const MCExpr *SizeExp =
770 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
771 MCSymbolRefExpr::Create(CurrentFnSymForSize,
774 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
777 // Emit post-function debug information.
779 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
783 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
788 // Print out jump tables referenced by the function.
791 OutStreamer.AddBlankLine();
794 /// getDebugValueLocation - Get location information encoded by DBG_VALUE
796 MachineLocation AsmPrinter::
797 getDebugValueLocation(const MachineInstr *MI) const {
798 // Target specific DBG_VALUE instructions are handled by each target.
799 return MachineLocation();
802 /// EmitDwarfRegOp - Emit dwarf register operation.
803 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc) const {
804 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
805 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
807 for (MCSuperRegIterator SR(MLoc.getReg(), TRI); SR.isValid() && Reg < 0;
809 Reg = TRI->getDwarfRegNum(*SR, false);
810 // FIXME: Get the bit range this register uses of the superregister
811 // so that we can produce a DW_OP_bit_piece
814 // FIXME: Handle cases like a super register being encoded as
815 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
817 // FIXME: We have no reasonable way of handling errors in here. The
818 // caller might be in the middle of an dwarf expression. We should
819 // probably assert that Reg >= 0 once debug info generation is more mature.
821 if (MLoc.isIndirect()) {
823 OutStreamer.AddComment(
824 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
825 EmitInt8(dwarf::DW_OP_breg0 + Reg);
827 OutStreamer.AddComment("DW_OP_bregx");
828 EmitInt8(dwarf::DW_OP_bregx);
829 OutStreamer.AddComment(Twine(Reg));
832 EmitSLEB128(MLoc.getOffset());
835 OutStreamer.AddComment(
836 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
837 EmitInt8(dwarf::DW_OP_reg0 + Reg);
839 OutStreamer.AddComment("DW_OP_regx");
840 EmitInt8(dwarf::DW_OP_regx);
841 OutStreamer.AddComment(Twine(Reg));
846 // FIXME: Produce a DW_OP_bit_piece if we used a superregister
849 bool AsmPrinter::doFinalization(Module &M) {
850 // Emit global variables.
851 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
853 EmitGlobalVariable(I);
855 // Emit visibility info for declarations
856 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
857 const Function &F = *I;
858 if (!F.isDeclaration())
860 GlobalValue::VisibilityTypes V = F.getVisibility();
861 if (V == GlobalValue::DefaultVisibility)
864 MCSymbol *Name = Mang->getSymbol(&F);
865 EmitVisibility(Name, V, false);
868 // Emit module flags.
869 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
870 M.getModuleFlagsMetadata(ModuleFlags);
871 if (!ModuleFlags.empty())
872 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, Mang, TM);
874 // Finalize debug and EH information.
877 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
884 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
890 // If the target wants to know about weak references, print them all.
891 if (MAI->getWeakRefDirective()) {
892 // FIXME: This is not lazy, it would be nice to only print weak references
893 // to stuff that is actually used. Note that doing so would require targets
894 // to notice uses in operands (due to constant exprs etc). This should
895 // happen with the MC stuff eventually.
897 // Print out module-level global variables here.
898 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
900 if (!I->hasExternalWeakLinkage()) continue;
901 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
904 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
905 if (!I->hasExternalWeakLinkage()) continue;
906 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
910 if (MAI->hasSetDirective()) {
911 OutStreamer.AddBlankLine();
912 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
914 MCSymbol *Name = Mang->getSymbol(I);
916 const GlobalValue *GV = I->getAliasedGlobal();
917 MCSymbol *Target = Mang->getSymbol(GV);
919 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
920 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
921 else if (I->hasWeakLinkage())
922 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
924 assert(I->hasLocalLinkage() && "Invalid alias linkage");
926 EmitVisibility(Name, I->getVisibility());
928 // Emit the directives as assignments aka .set:
929 OutStreamer.EmitAssignment(Name,
930 MCSymbolRefExpr::Create(Target, OutContext));
934 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
935 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
936 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
937 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
938 MP->finishAssembly(*this);
940 // If we don't have any trampolines, then we don't require stack memory
941 // to be executable. Some targets have a directive to declare this.
942 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
943 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
944 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
945 OutStreamer.SwitchSection(S);
947 // Allow the target to emit any magic that it wants at the end of the file,
948 // after everything else has gone out.
951 delete Mang; Mang = 0;
954 OutStreamer.Finish();
960 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
962 // Get the function symbol.
963 CurrentFnSym = Mang->getSymbol(MF.getFunction());
964 CurrentFnSymForSize = CurrentFnSym;
967 LI = &getAnalysis<MachineLoopInfo>();
971 // SectionCPs - Keep track the alignment, constpool entries per Section.
975 SmallVector<unsigned, 4> CPEs;
976 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
980 /// EmitConstantPool - Print to the current output stream assembly
981 /// representations of the constants in the constant pool MCP. This is
982 /// used to print out constants which have been "spilled to memory" by
983 /// the code generator.
985 void AsmPrinter::EmitConstantPool() {
986 const MachineConstantPool *MCP = MF->getConstantPool();
987 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
988 if (CP.empty()) return;
990 // Calculate sections for constant pool entries. We collect entries to go into
991 // the same section together to reduce amount of section switch statements.
992 SmallVector<SectionCPs, 4> CPSections;
993 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
994 const MachineConstantPoolEntry &CPE = CP[i];
995 unsigned Align = CPE.getAlignment();
998 switch (CPE.getRelocationInfo()) {
999 default: llvm_unreachable("Unknown section kind");
1000 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
1002 Kind = SectionKind::getReadOnlyWithRelLocal();
1005 switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) {
1006 case 4: Kind = SectionKind::getMergeableConst4(); break;
1007 case 8: Kind = SectionKind::getMergeableConst8(); break;
1008 case 16: Kind = SectionKind::getMergeableConst16();break;
1009 default: Kind = SectionKind::getMergeableConst(); break;
1013 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
1015 // The number of sections are small, just do a linear search from the
1016 // last section to the first.
1018 unsigned SecIdx = CPSections.size();
1019 while (SecIdx != 0) {
1020 if (CPSections[--SecIdx].S == S) {
1026 SecIdx = CPSections.size();
1027 CPSections.push_back(SectionCPs(S, Align));
1030 if (Align > CPSections[SecIdx].Alignment)
1031 CPSections[SecIdx].Alignment = Align;
1032 CPSections[SecIdx].CPEs.push_back(i);
1035 // Now print stuff into the calculated sections.
1036 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1037 OutStreamer.SwitchSection(CPSections[i].S);
1038 EmitAlignment(Log2_32(CPSections[i].Alignment));
1040 unsigned Offset = 0;
1041 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1042 unsigned CPI = CPSections[i].CPEs[j];
1043 MachineConstantPoolEntry CPE = CP[CPI];
1045 // Emit inter-object padding for alignment.
1046 unsigned AlignMask = CPE.getAlignment() - 1;
1047 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1048 OutStreamer.EmitZeros(NewOffset - Offset);
1050 Type *Ty = CPE.getType();
1051 Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
1052 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1054 if (CPE.isMachineConstantPoolEntry())
1055 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1057 EmitGlobalConstant(CPE.Val.ConstVal);
1062 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1063 /// by the current function to the current output stream.
1065 void AsmPrinter::EmitJumpTableInfo() {
1066 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1067 if (MJTI == 0) return;
1068 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1069 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1070 if (JT.empty()) return;
1072 // Pick the directive to use to print the jump table entries, and switch to
1073 // the appropriate section.
1074 const Function *F = MF->getFunction();
1075 bool JTInDiffSection = false;
1076 if (// In PIC mode, we need to emit the jump table to the same section as the
1077 // function body itself, otherwise the label differences won't make sense.
1078 // FIXME: Need a better predicate for this: what about custom entries?
1079 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1080 // We should also do if the section name is NULL or function is declared
1081 // in discardable section
1082 // FIXME: this isn't the right predicate, should be based on the MCSection
1083 // for the function.
1084 F->isWeakForLinker()) {
1085 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1087 // Otherwise, drop it in the readonly section.
1088 const MCSection *ReadOnlySection =
1089 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1090 OutStreamer.SwitchSection(ReadOnlySection);
1091 JTInDiffSection = true;
1094 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
1096 // Jump tables in code sections are marked with a data_region directive
1097 // where that's supported.
1098 if (!JTInDiffSection)
1099 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1101 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1102 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1104 // If this jump table was deleted, ignore it.
1105 if (JTBBs.empty()) continue;
1107 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1108 // .set directive for each unique entry. This reduces the number of
1109 // relocations the assembler will generate for the jump table.
1110 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1111 MAI->hasSetDirective()) {
1112 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1113 const TargetLowering *TLI = TM.getTargetLowering();
1114 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1115 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1116 const MachineBasicBlock *MBB = JTBBs[ii];
1117 if (!EmittedSets.insert(MBB)) continue;
1119 // .set LJTSet, LBB32-base
1121 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1122 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1123 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1127 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1128 // before each jump table. The first label is never referenced, but tells
1129 // the assembler and linker the extents of the jump table object. The
1130 // second label is actually referenced by the code.
1131 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1132 // FIXME: This doesn't have to have any specific name, just any randomly
1133 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1134 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1136 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1138 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1139 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1141 if (!JTInDiffSection)
1142 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1145 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1147 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1148 const MachineBasicBlock *MBB,
1149 unsigned UID) const {
1150 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1151 const MCExpr *Value = 0;
1152 switch (MJTI->getEntryKind()) {
1153 case MachineJumpTableInfo::EK_Inline:
1154 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1155 case MachineJumpTableInfo::EK_Custom32:
1156 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1159 case MachineJumpTableInfo::EK_BlockAddress:
1160 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1162 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1164 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1165 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1166 // with a relocation as gp-relative, e.g.:
1168 MCSymbol *MBBSym = MBB->getSymbol();
1169 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1173 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1174 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1175 // with a relocation as gp-relative, e.g.:
1177 MCSymbol *MBBSym = MBB->getSymbol();
1178 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1182 case MachineJumpTableInfo::EK_LabelDifference32: {
1183 // EK_LabelDifference32 - Each entry is the address of the block minus
1184 // the address of the jump table. This is used for PIC jump tables where
1185 // gprel32 is not supported. e.g.:
1186 // .word LBB123 - LJTI1_2
1187 // If the .set directive is supported, this is emitted as:
1188 // .set L4_5_set_123, LBB123 - LJTI1_2
1189 // .word L4_5_set_123
1191 // If we have emitted set directives for the jump table entries, print
1192 // them rather than the entries themselves. If we're emitting PIC, then
1193 // emit the table entries as differences between two text section labels.
1194 if (MAI->hasSetDirective()) {
1195 // If we used .set, reference the .set's symbol.
1196 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1200 // Otherwise, use the difference as the jump table entry.
1201 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1202 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1203 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1208 assert(Value && "Unknown entry kind!");
1210 unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
1211 OutStreamer.EmitValue(Value, EntrySize);
1215 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1216 /// special global used by LLVM. If so, emit it and return true, otherwise
1217 /// do nothing and return false.
1218 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1219 if (GV->getName() == "llvm.used") {
1220 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1221 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1225 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1226 if (GV->getSection() == "llvm.metadata" ||
1227 GV->hasAvailableExternallyLinkage())
1230 if (!GV->hasAppendingLinkage()) return false;
1232 assert(GV->hasInitializer() && "Not a special LLVM global!");
1234 if (GV->getName() == "llvm.global_ctors") {
1235 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1237 if (TM.getRelocationModel() == Reloc::Static &&
1238 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1239 StringRef Sym(".constructors_used");
1240 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1246 if (GV->getName() == "llvm.global_dtors") {
1247 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1249 if (TM.getRelocationModel() == Reloc::Static &&
1250 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1251 StringRef Sym(".destructors_used");
1252 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1261 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1262 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1263 /// is true, as being used with this directive.
1264 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1265 // Should be an array of 'i8*'.
1266 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1267 const GlobalValue *GV =
1268 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1269 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1270 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
1274 typedef std::pair<unsigned, Constant*> Structor;
1276 static bool priority_order(const Structor& lhs, const Structor& rhs) {
1277 return lhs.first < rhs.first;
1280 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1282 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1283 // Should be an array of '{ int, void ()* }' structs. The first value is the
1285 if (!isa<ConstantArray>(List)) return;
1287 // Sanity check the structors list.
1288 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1289 if (!InitList) return; // Not an array!
1290 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1291 if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1292 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1293 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1295 // Gather the structors in a form that's convenient for sorting by priority.
1296 SmallVector<Structor, 8> Structors;
1297 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1298 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1299 if (!CS) continue; // Malformed.
1300 if (CS->getOperand(1)->isNullValue())
1301 break; // Found a null terminator, skip the rest.
1302 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1303 if (!Priority) continue; // Malformed.
1304 Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1305 CS->getOperand(1)));
1308 // Emit the function pointers in the target-specific order
1309 const DataLayout *TD = TM.getDataLayout();
1310 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
1311 std::stable_sort(Structors.begin(), Structors.end(), priority_order);
1312 for (unsigned i = 0, e = Structors.size(); i != e; ++i) {
1313 const MCSection *OutputSection =
1315 getObjFileLowering().getStaticCtorSection(Structors[i].first) :
1316 getObjFileLowering().getStaticDtorSection(Structors[i].first));
1317 OutStreamer.SwitchSection(OutputSection);
1318 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1319 EmitAlignment(Align);
1320 EmitXXStructor(Structors[i].second);
1324 //===--------------------------------------------------------------------===//
1325 // Emission and print routines
1328 /// EmitInt8 - Emit a byte directive and value.
1330 void AsmPrinter::EmitInt8(int Value) const {
1331 OutStreamer.EmitIntValue(Value, 1);
1334 /// EmitInt16 - Emit a short directive and value.
1336 void AsmPrinter::EmitInt16(int Value) const {
1337 OutStreamer.EmitIntValue(Value, 2);
1340 /// EmitInt32 - Emit a long directive and value.
1342 void AsmPrinter::EmitInt32(int Value) const {
1343 OutStreamer.EmitIntValue(Value, 4);
1346 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1347 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1348 /// labels. This implicitly uses .set if it is available.
1349 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1350 unsigned Size) const {
1351 // Get the Hi-Lo expression.
1352 const MCExpr *Diff =
1353 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1354 MCSymbolRefExpr::Create(Lo, OutContext),
1357 if (!MAI->hasSetDirective()) {
1358 OutStreamer.EmitValue(Diff, Size);
1362 // Otherwise, emit with .set (aka assignment).
1363 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1364 OutStreamer.EmitAssignment(SetLabel, Diff);
1365 OutStreamer.EmitSymbolValue(SetLabel, Size);
1368 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1369 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1370 /// specify the labels. This implicitly uses .set if it is available.
1371 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1372 const MCSymbol *Lo, unsigned Size)
1375 // Emit Hi+Offset - Lo
1376 // Get the Hi+Offset expression.
1377 const MCExpr *Plus =
1378 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1379 MCConstantExpr::Create(Offset, OutContext),
1382 // Get the Hi+Offset-Lo expression.
1383 const MCExpr *Diff =
1384 MCBinaryExpr::CreateSub(Plus,
1385 MCSymbolRefExpr::Create(Lo, OutContext),
1388 if (!MAI->hasSetDirective())
1389 OutStreamer.EmitValue(Diff, 4);
1391 // Otherwise, emit with .set (aka assignment).
1392 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1393 OutStreamer.EmitAssignment(SetLabel, Diff);
1394 OutStreamer.EmitSymbolValue(SetLabel, 4);
1398 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1399 /// where the size in bytes of the directive is specified by Size and Label
1400 /// specifies the label. This implicitly uses .set if it is available.
1401 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1405 // Emit Label+Offset (or just Label if Offset is zero)
1406 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1408 Expr = MCBinaryExpr::CreateAdd(Expr,
1409 MCConstantExpr::Create(Offset, OutContext),
1412 OutStreamer.EmitValue(Expr, Size);
1416 //===----------------------------------------------------------------------===//
1418 // EmitAlignment - Emit an alignment directive to the specified power of
1419 // two boundary. For example, if you pass in 3 here, you will get an 8
1420 // byte alignment. If a global value is specified, and if that global has
1421 // an explicit alignment requested, it will override the alignment request
1422 // if required for correctness.
1424 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1425 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
1427 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1429 if (getCurrentSection()->getKind().isText())
1430 OutStreamer.EmitCodeAlignment(1 << NumBits);
1432 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1435 //===----------------------------------------------------------------------===//
1436 // Constant emission.
1437 //===----------------------------------------------------------------------===//
1439 /// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
1441 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
1442 MCContext &Ctx = AP.OutContext;
1444 if (CV->isNullValue() || isa<UndefValue>(CV))
1445 return MCConstantExpr::Create(0, Ctx);
1447 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1448 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1450 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1451 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
1453 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1454 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1456 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1458 llvm_unreachable("Unknown constant value to lower!");
1461 switch (CE->getOpcode()) {
1463 // If the code isn't optimized, there may be outstanding folding
1464 // opportunities. Attempt to fold the expression using DataLayout as a
1465 // last resort before giving up.
1467 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
1469 return lowerConstant(C, AP);
1471 // Otherwise report the problem to the user.
1474 raw_string_ostream OS(S);
1475 OS << "Unsupported expression in static initializer: ";
1476 WriteAsOperand(OS, CE, /*PrintType=*/false,
1477 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1478 report_fatal_error(OS.str());
1480 case Instruction::GetElementPtr: {
1481 const DataLayout &TD = *AP.TM.getDataLayout();
1482 // Generate a symbolic expression for the byte address
1483 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
1484 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
1486 const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
1490 int64_t Offset = OffsetAI.getSExtValue();
1491 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1495 case Instruction::Trunc:
1496 // We emit the value and depend on the assembler to truncate the generated
1497 // expression properly. This is important for differences between
1498 // blockaddress labels. Since the two labels are in the same function, it
1499 // is reasonable to treat their delta as a 32-bit value.
1501 case Instruction::BitCast:
1502 return lowerConstant(CE->getOperand(0), AP);
1504 case Instruction::IntToPtr: {
1505 const DataLayout &TD = *AP.TM.getDataLayout();
1506 // Handle casts to pointers by changing them into casts to the appropriate
1507 // integer type. This promotes constant folding and simplifies this code.
1508 Constant *Op = CE->getOperand(0);
1509 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1511 return lowerConstant(Op, AP);
1514 case Instruction::PtrToInt: {
1515 const DataLayout &TD = *AP.TM.getDataLayout();
1516 // Support only foldable casts to/from pointers that can be eliminated by
1517 // changing the pointer to the appropriately sized integer type.
1518 Constant *Op = CE->getOperand(0);
1519 Type *Ty = CE->getType();
1521 const MCExpr *OpExpr = lowerConstant(Op, AP);
1523 // We can emit the pointer value into this slot if the slot is an
1524 // integer slot equal to the size of the pointer.
1525 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1528 // Otherwise the pointer is smaller than the resultant integer, mask off
1529 // the high bits so we are sure to get a proper truncation if the input is
1531 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1532 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1533 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1536 // The MC library also has a right-shift operator, but it isn't consistently
1537 // signed or unsigned between different targets.
1538 case Instruction::Add:
1539 case Instruction::Sub:
1540 case Instruction::Mul:
1541 case Instruction::SDiv:
1542 case Instruction::SRem:
1543 case Instruction::Shl:
1544 case Instruction::And:
1545 case Instruction::Or:
1546 case Instruction::Xor: {
1547 const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1548 const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
1549 switch (CE->getOpcode()) {
1550 default: llvm_unreachable("Unknown binary operator constant cast expr");
1551 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1552 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1553 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1554 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1555 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1556 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1557 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1558 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1559 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1565 static void emitGlobalConstantImpl(const Constant *C, unsigned AddrSpace,
1568 /// isRepeatedByteSequence - Determine whether the given value is
1569 /// composed of a repeated sequence of identical bytes and return the
1570 /// byte value. If it is not a repeated sequence, return -1.
1571 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1572 StringRef Data = V->getRawDataValues();
1573 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1575 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1576 if (Data[i] != C) return -1;
1577 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1581 /// isRepeatedByteSequence - Determine whether the given value is
1582 /// composed of a repeated sequence of identical bytes and return the
1583 /// byte value. If it is not a repeated sequence, return -1.
1584 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1586 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1587 if (CI->getBitWidth() > 64) return -1;
1589 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
1590 uint64_t Value = CI->getZExtValue();
1592 // Make sure the constant is at least 8 bits long and has a power
1593 // of 2 bit width. This guarantees the constant bit width is
1594 // always a multiple of 8 bits, avoiding issues with padding out
1595 // to Size and other such corner cases.
1596 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1598 uint8_t Byte = static_cast<uint8_t>(Value);
1600 for (unsigned i = 1; i < Size; ++i) {
1602 if (static_cast<uint8_t>(Value) != Byte) return -1;
1606 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1607 // Make sure all array elements are sequences of the same repeated
1609 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1610 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1611 if (Byte == -1) return -1;
1613 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1614 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1615 if (ThisByte == -1) return -1;
1616 if (Byte != ThisByte) return -1;
1621 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1622 return isRepeatedByteSequence(CDS);
1627 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1628 unsigned AddrSpace,AsmPrinter &AP){
1630 // See if we can aggregate this into a .fill, if so, emit it as such.
1631 int Value = isRepeatedByteSequence(CDS, AP.TM);
1633 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
1634 // Don't emit a 1-byte object as a .fill.
1636 return AP.OutStreamer.EmitFill(Bytes, Value, AddrSpace);
1639 // If this can be emitted with .ascii/.asciz, emit it as such.
1640 if (CDS->isString())
1641 return AP.OutStreamer.EmitBytes(CDS->getAsString(), AddrSpace);
1643 // Otherwise, emit the values in successive locations.
1644 unsigned ElementByteSize = CDS->getElementByteSize();
1645 if (isa<IntegerType>(CDS->getElementType())) {
1646 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1648 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1649 CDS->getElementAsInteger(i));
1650 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1651 ElementByteSize, AddrSpace);
1653 } else if (ElementByteSize == 4) {
1654 // FP Constants are printed as integer constants to avoid losing
1656 assert(CDS->getElementType()->isFloatTy());
1657 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1663 F = CDS->getElementAsFloat(i);
1665 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1666 AP.OutStreamer.EmitIntValue(I, 4, AddrSpace);
1669 assert(CDS->getElementType()->isDoubleTy());
1670 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1676 F = CDS->getElementAsDouble(i);
1678 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1679 AP.OutStreamer.EmitIntValue(I, 8, AddrSpace);
1683 const DataLayout &TD = *AP.TM.getDataLayout();
1684 unsigned Size = TD.getTypeAllocSize(CDS->getType());
1685 unsigned EmittedSize = TD.getTypeAllocSize(CDS->getType()->getElementType()) *
1686 CDS->getNumElements();
1687 if (unsigned Padding = Size - EmittedSize)
1688 AP.OutStreamer.EmitZeros(Padding, AddrSpace);
1692 static void emitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1694 // See if we can aggregate some values. Make sure it can be
1695 // represented as a series of bytes of the constant value.
1696 int Value = isRepeatedByteSequence(CA, AP.TM);
1699 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
1700 AP.OutStreamer.EmitFill(Bytes, Value, AddrSpace);
1703 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1704 emitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
1708 static void emitGlobalConstantVector(const ConstantVector *CV,
1709 unsigned AddrSpace, AsmPrinter &AP) {
1710 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1711 emitGlobalConstantImpl(CV->getOperand(i), AddrSpace, AP);
1713 const DataLayout &TD = *AP.TM.getDataLayout();
1714 unsigned Size = TD.getTypeAllocSize(CV->getType());
1715 unsigned EmittedSize = TD.getTypeAllocSize(CV->getType()->getElementType()) *
1716 CV->getType()->getNumElements();
1717 if (unsigned Padding = Size - EmittedSize)
1718 AP.OutStreamer.EmitZeros(Padding, AddrSpace);
1721 static void emitGlobalConstantStruct(const ConstantStruct *CS,
1722 unsigned AddrSpace, AsmPrinter &AP) {
1723 // Print the fields in successive locations. Pad to align if needed!
1724 const DataLayout *TD = AP.TM.getDataLayout();
1725 unsigned Size = TD->getTypeAllocSize(CS->getType());
1726 const StructLayout *Layout = TD->getStructLayout(CS->getType());
1727 uint64_t SizeSoFar = 0;
1728 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1729 const Constant *Field = CS->getOperand(i);
1731 // Check if padding is needed and insert one or more 0s.
1732 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1733 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1734 - Layout->getElementOffset(i)) - FieldSize;
1735 SizeSoFar += FieldSize + PadSize;
1737 // Now print the actual field value.
1738 emitGlobalConstantImpl(Field, AddrSpace, AP);
1740 // Insert padding - this may include padding to increase the size of the
1741 // current field up to the ABI size (if the struct is not packed) as well
1742 // as padding to ensure that the next field starts at the right offset.
1743 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1745 assert(SizeSoFar == Layout->getSizeInBytes() &&
1746 "Layout of constant struct may be incorrect!");
1749 static void emitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1751 APInt API = CFP->getValueAPF().bitcastToAPInt();
1753 // First print a comment with what we think the original floating-point value
1754 // should have been.
1755 if (AP.isVerbose()) {
1756 SmallString<8> StrVal;
1757 CFP->getValueAPF().toString(StrVal);
1759 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1760 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1763 // Now iterate through the APInt chunks, emitting them in endian-correct
1764 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1766 unsigned NumBytes = API.getBitWidth() / 8;
1767 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1768 const uint64_t *p = API.getRawData();
1770 // PPC's long double has odd notions of endianness compared to how LLVM
1771 // handles it: p[0] goes first for *big* endian on PPC.
1772 if (AP.TM.getDataLayout()->isBigEndian() != CFP->getType()->isPPC_FP128Ty()) {
1773 int Chunk = API.getNumWords() - 1;
1776 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes, AddrSpace);
1778 for (; Chunk >= 0; --Chunk)
1779 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t), AddrSpace);
1782 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1783 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t), AddrSpace);
1786 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes, AddrSpace);
1789 // Emit the tail padding for the long double.
1790 const DataLayout &TD = *AP.TM.getDataLayout();
1791 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1792 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1795 static void emitGlobalConstantLargeInt(const ConstantInt *CI,
1796 unsigned AddrSpace, AsmPrinter &AP) {
1797 const DataLayout *TD = AP.TM.getDataLayout();
1798 unsigned BitWidth = CI->getBitWidth();
1799 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1801 // We don't expect assemblers to support integer data directives
1802 // for more than 64 bits, so we emit the data in at most 64-bit
1803 // quantities at a time.
1804 const uint64_t *RawData = CI->getValue().getRawData();
1805 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1806 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1807 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1811 static void emitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace,
1813 const DataLayout *TD = AP.TM.getDataLayout();
1814 uint64_t Size = TD->getTypeAllocSize(CV->getType());
1815 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
1816 return AP.OutStreamer.EmitZeros(Size, AddrSpace);
1818 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1825 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1826 CI->getZExtValue());
1827 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1830 emitGlobalConstantLargeInt(CI, AddrSpace, AP);
1835 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1836 return emitGlobalConstantFP(CFP, AddrSpace, AP);
1838 if (isa<ConstantPointerNull>(CV)) {
1839 AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
1843 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
1844 return emitGlobalConstantDataSequential(CDS, AddrSpace, AP);
1846 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1847 return emitGlobalConstantArray(CVA, AddrSpace, AP);
1849 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1850 return emitGlobalConstantStruct(CVS, AddrSpace, AP);
1852 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1853 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
1855 if (CE->getOpcode() == Instruction::BitCast)
1856 return emitGlobalConstantImpl(CE->getOperand(0), AddrSpace, AP);
1859 // If the constant expression's size is greater than 64-bits, then we have
1860 // to emit the value in chunks. Try to constant fold the value and emit it
1862 Constant *New = ConstantFoldConstantExpression(CE, TD);
1863 if (New && New != CE)
1864 return emitGlobalConstantImpl(New, AddrSpace, AP);
1868 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1869 return emitGlobalConstantVector(V, AddrSpace, AP);
1871 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1872 // thread the streamer with EmitValue.
1873 AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size, AddrSpace);
1876 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1877 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1878 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
1880 emitGlobalConstantImpl(CV, AddrSpace, *this);
1881 else if (MAI->hasSubsectionsViaSymbols()) {
1882 // If the global has zero size, emit a single byte so that two labels don't
1883 // look like they are at the same location.
1884 OutStreamer.EmitIntValue(0, 1, AddrSpace);
1888 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1889 // Target doesn't support this yet!
1890 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1893 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1895 OS << '+' << Offset;
1896 else if (Offset < 0)
1900 //===----------------------------------------------------------------------===//
1901 // Symbol Lowering Routines.
1902 //===----------------------------------------------------------------------===//
1904 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1905 /// temporary label with the specified stem and unique ID.
1906 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1907 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1911 /// GetTempSymbol - Return an assembler temporary label with the specified
1913 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1914 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1919 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
1920 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
1923 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1924 return MMI->getAddrLabelSymbol(BB);
1927 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1928 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1929 return OutContext.GetOrCreateSymbol
1930 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1931 + "_" + Twine(CPID));
1934 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1935 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1936 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1939 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1940 /// FIXME: privatize to AsmPrinter.
1941 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1942 return OutContext.GetOrCreateSymbol
1943 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1944 Twine(UID) + "_set_" + Twine(MBBID));
1947 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1948 /// global value name as its base, with the specified suffix, and where the
1949 /// symbol is forced to have private linkage if ForcePrivate is true.
1950 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1952 bool ForcePrivate) const {
1953 SmallString<60> NameStr;
1954 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1955 NameStr.append(Suffix.begin(), Suffix.end());
1956 return OutContext.GetOrCreateSymbol(NameStr.str());
1959 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1961 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1962 SmallString<60> NameStr;
1963 Mang->getNameWithPrefix(NameStr, Sym);
1964 return OutContext.GetOrCreateSymbol(NameStr.str());
1969 /// PrintParentLoopComment - Print comments about parent loops of this one.
1970 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1971 unsigned FunctionNumber) {
1972 if (Loop == 0) return;
1973 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1974 OS.indent(Loop->getLoopDepth()*2)
1975 << "Parent Loop BB" << FunctionNumber << "_"
1976 << Loop->getHeader()->getNumber()
1977 << " Depth=" << Loop->getLoopDepth() << '\n';
1981 /// PrintChildLoopComment - Print comments about child loops within
1982 /// the loop for this basic block, with nesting.
1983 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1984 unsigned FunctionNumber) {
1985 // Add child loop information
1986 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1987 OS.indent((*CL)->getLoopDepth()*2)
1988 << "Child Loop BB" << FunctionNumber << "_"
1989 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1991 PrintChildLoopComment(OS, *CL, FunctionNumber);
1995 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
1996 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
1997 const MachineLoopInfo *LI,
1998 const AsmPrinter &AP) {
1999 // Add loop depth information
2000 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2001 if (Loop == 0) return;
2003 MachineBasicBlock *Header = Loop->getHeader();
2004 assert(Header && "No header for loop");
2006 // If this block is not a loop header, just print out what is the loop header
2008 if (Header != &MBB) {
2009 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2010 Twine(AP.getFunctionNumber())+"_" +
2011 Twine(Loop->getHeader()->getNumber())+
2012 " Depth="+Twine(Loop->getLoopDepth()));
2016 // Otherwise, it is a loop header. Print out information about child and
2018 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2020 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2023 OS.indent(Loop->getLoopDepth()*2-2);
2028 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2030 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2034 /// EmitBasicBlockStart - This method prints the label for the specified
2035 /// MachineBasicBlock, an alignment (if present) and a comment describing
2036 /// it if appropriate.
2037 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
2038 // Emit an alignment directive for this block, if needed.
2039 if (unsigned Align = MBB->getAlignment())
2040 EmitAlignment(Align);
2042 // If the block has its address taken, emit any labels that were used to
2043 // reference the block. It is possible that there is more than one label
2044 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2045 // the references were generated.
2046 if (MBB->hasAddressTaken()) {
2047 const BasicBlock *BB = MBB->getBasicBlock();
2049 OutStreamer.AddComment("Block address taken");
2051 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
2053 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
2054 OutStreamer.EmitLabel(Syms[i]);
2057 // Print some verbose block comments.
2059 if (const BasicBlock *BB = MBB->getBasicBlock())
2061 OutStreamer.AddComment("%" + BB->getName());
2062 emitBasicBlockLoopComments(*MBB, LI, *this);
2065 // Print the main label for the block.
2066 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
2067 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
2068 // NOTE: Want this comment at start of line, don't emit with AddComment.
2069 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
2070 Twine(MBB->getNumber()) + ":");
2073 OutStreamer.EmitLabel(MBB->getSymbol());
2077 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2078 bool IsDefinition) const {
2079 MCSymbolAttr Attr = MCSA_Invalid;
2081 switch (Visibility) {
2083 case GlobalValue::HiddenVisibility:
2085 Attr = MAI->getHiddenVisibilityAttr();
2087 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2089 case GlobalValue::ProtectedVisibility:
2090 Attr = MAI->getProtectedVisibilityAttr();
2094 if (Attr != MCSA_Invalid)
2095 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2098 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2099 /// exactly one predecessor and the control transfer mechanism between
2100 /// the predecessor and this block is a fall-through.
2102 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2103 // If this is a landing pad, it isn't a fall through. If it has no preds,
2104 // then nothing falls through to it.
2105 if (MBB->isLandingPad() || MBB->pred_empty())
2108 // If there isn't exactly one predecessor, it can't be a fall through.
2109 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2111 if (PI2 != MBB->pred_end())
2114 // The predecessor has to be immediately before this block.
2115 MachineBasicBlock *Pred = *PI;
2117 if (!Pred->isLayoutSuccessor(MBB))
2120 // If the block is completely empty, then it definitely does fall through.
2124 // Check the terminators in the previous blocks
2125 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2126 IE = Pred->end(); II != IE; ++II) {
2127 MachineInstr &MI = *II;
2129 // If it is not a simple branch, we are in a table somewhere.
2130 if (!MI.isBranch() || MI.isIndirectBranch())
2133 // If we are the operands of one of the branches, this is not
2135 for (MachineInstr::mop_iterator OI = MI.operands_begin(),
2136 OE = MI.operands_end(); OI != OE; ++OI) {
2137 const MachineOperand& OP = *OI;
2140 if (OP.isMBB() && OP.getMBB() == MBB)
2150 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2151 if (!S->usesMetadata())
2154 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2155 gcp_map_type::iterator GCPI = GCMap.find(S);
2156 if (GCPI != GCMap.end())
2157 return GCPI->second;
2159 const char *Name = S->getName().c_str();
2161 for (GCMetadataPrinterRegistry::iterator
2162 I = GCMetadataPrinterRegistry::begin(),
2163 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2164 if (strcmp(Name, I->getName()) == 0) {
2165 GCMetadataPrinter *GMP = I->instantiate();
2167 GCMap.insert(std::make_pair(S, GMP));
2171 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));