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/TargetFrameLowering.h"
46 #include "llvm/Target/TargetInstrInfo.h"
47 #include "llvm/Target/TargetLowering.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 #include "llvm/Transforms/Utils/GlobalStatus.h"
54 static const char *const DWARFGroupName = "DWARF Emission";
55 static const char *const DbgTimerName = "DWARF Debug Writer";
56 static const char *const 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 DataLayout &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())
96 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
97 : MachineFunctionPass(ID),
98 TM(tm), MAI(tm.getMCAsmInfo()), MII(tm.getInstrInfo()),
99 OutContext(Streamer.getContext()),
100 OutStreamer(Streamer),
101 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
102 DD = 0; DE = 0; MMI = 0; LI = 0; MF = 0;
103 CurrentFnSym = CurrentFnSymForSize = 0;
104 GCMetadataPrinters = 0;
105 VerboseAsm = Streamer.isVerboseAsm();
108 AsmPrinter::~AsmPrinter() {
109 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
111 if (GCMetadataPrinters != 0) {
112 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
114 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
117 GCMetadataPrinters = 0;
123 /// getFunctionNumber - Return a unique ID for the current function.
125 unsigned AsmPrinter::getFunctionNumber() const {
126 return MF->getFunctionNumber();
129 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
130 return TM.getTargetLowering()->getObjFileLowering();
133 /// getDataLayout - Return information about data layout.
134 const DataLayout &AsmPrinter::getDataLayout() const {
135 return *TM.getDataLayout();
138 StringRef AsmPrinter::getTargetTriple() const {
139 return TM.getTargetTriple();
142 /// getCurrentSection() - Return the current section we are emitting to.
143 const MCSection *AsmPrinter::getCurrentSection() const {
144 return OutStreamer.getCurrentSection().first;
149 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
150 AU.setPreservesAll();
151 MachineFunctionPass::getAnalysisUsage(AU);
152 AU.addRequired<MachineModuleInfo>();
153 AU.addRequired<GCModuleInfo>();
155 AU.addRequired<MachineLoopInfo>();
158 bool AsmPrinter::doInitialization(Module &M) {
159 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
160 MMI->AnalyzeModule(M);
162 // Initialize TargetLoweringObjectFile.
163 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
164 .Initialize(OutContext, TM);
166 OutStreamer.InitStreamer();
168 Mang = new Mangler(&TM);
170 // Allow the target to emit any magic that it wants at the start of the file.
171 EmitStartOfAsmFile(M);
173 // Very minimal debug info. It is ignored if we emit actual debug info. If we
174 // don't, this at least helps the user find where a global came from.
175 if (MAI->hasSingleParameterDotFile()) {
177 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
180 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
181 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
182 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
183 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
184 MP->beginAssembly(*this);
186 // Emit module-level inline asm if it exists.
187 if (!M.getModuleInlineAsm().empty()) {
188 OutStreamer.AddComment("Start of file scope inline assembly");
189 OutStreamer.AddBlankLine();
190 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
191 OutStreamer.AddComment("End of file scope inline assembly");
192 OutStreamer.AddBlankLine();
195 if (MAI->doesSupportDebugInformation())
196 DD = new DwarfDebug(this, &M);
198 switch (MAI->getExceptionHandlingType()) {
199 case ExceptionHandling::None:
201 case ExceptionHandling::SjLj:
202 case ExceptionHandling::DwarfCFI:
203 DE = new DwarfCFIException(this);
205 case ExceptionHandling::ARM:
206 DE = new ARMException(this);
208 case ExceptionHandling::Win64:
209 DE = new Win64Exception(this);
213 llvm_unreachable("Unknown exception type.");
216 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
217 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
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 if (MAI->getWeakDefDirective() != 0) {
227 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
229 bool CanBeHidden = false;
231 if (Linkage == GlobalValue::LinkOnceODRLinkage) {
232 if (GV->hasUnnamedAddr()) {
236 if (!GlobalStatus::analyzeGlobal(GV, GS) && !GS.IsCompared)
242 // .weak_definition _foo
243 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
245 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
246 } else if (MAI->getLinkOnceDirective() != 0) {
248 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
249 //NOTE: linkonce is handled by the section the symbol was assigned to.
252 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
255 case GlobalValue::DLLExportLinkage:
256 case GlobalValue::AppendingLinkage:
257 // FIXME: appending linkage variables should go into a section of
258 // their name or something. For now, just emit them as external.
259 case GlobalValue::ExternalLinkage:
260 // If external or appending, declare as a global symbol.
262 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
264 case GlobalValue::PrivateLinkage:
265 case GlobalValue::InternalLinkage:
266 case GlobalValue::LinkerPrivateLinkage:
268 case GlobalValue::AvailableExternallyLinkage:
269 llvm_unreachable("Should never emit this");
270 case GlobalValue::DLLImportLinkage:
271 case GlobalValue::ExternalWeakLinkage:
272 llvm_unreachable("Don't know how to emit these");
274 llvm_unreachable("Unknown linkage type!");
277 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
278 return getObjFileLowering().getSymbol(*Mang, GV);
281 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
282 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
283 if (GV->hasInitializer()) {
284 // Check to see if this is a special global used by LLVM, if so, emit it.
285 if (EmitSpecialLLVMGlobal(GV))
289 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
290 /*PrintType=*/false, GV->getParent());
291 OutStreamer.GetCommentOS() << '\n';
295 MCSymbol *GVSym = getSymbol(GV);
296 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
298 if (!GV->hasInitializer()) // External globals require no extra code.
301 if (MAI->hasDotTypeDotSizeDirective())
302 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
304 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
306 const DataLayout *DL = TM.getDataLayout();
307 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
309 // If the alignment is specified, we *must* obey it. Overaligning a global
310 // with a specified alignment is a prompt way to break globals emitted to
311 // sections and expected to be contiguous (e.g. ObjC metadata).
312 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
315 DD->setSymbolSize(GVSym, Size);
317 // Handle common and BSS local symbols (.lcomm).
318 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
319 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
320 unsigned Align = 1 << AlignLog;
322 // Handle common symbols.
323 if (GVKind.isCommon()) {
324 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
328 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
332 // Handle local BSS symbols.
333 if (MAI->hasMachoZeroFillDirective()) {
334 const MCSection *TheSection =
335 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
336 // .zerofill __DATA, __bss, _foo, 400, 5
337 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
341 // Use .lcomm only if it supports user-specified alignment.
342 // Otherwise, while it would still be correct to use .lcomm in some
343 // cases (e.g. when Align == 1), the external assembler might enfore
344 // some -unknown- default alignment behavior, which could cause
345 // spurious differences between external and integrated assembler.
346 // Prefer to simply fall back to .local / .comm in this case.
347 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
349 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
353 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
357 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
359 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
363 const MCSection *TheSection =
364 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
366 // Handle the zerofill directive on darwin, which is a special form of BSS
368 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
369 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
372 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
373 // .zerofill __DATA, __common, _foo, 400, 5
374 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
378 // Handle thread local data for mach-o which requires us to output an
379 // additional structure of data and mangle the original symbol so that we
380 // can reference it later.
382 // TODO: This should become an "emit thread local global" method on TLOF.
383 // All of this macho specific stuff should be sunk down into TLOFMachO and
384 // stuff like "TLSExtraDataSection" should no longer be part of the parent
385 // TLOF class. This will also make it more obvious that stuff like
386 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
388 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
389 // Emit the .tbss symbol
391 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
393 if (GVKind.isThreadBSS()) {
394 TheSection = getObjFileLowering().getTLSBSSSection();
395 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
396 } else if (GVKind.isThreadData()) {
397 OutStreamer.SwitchSection(TheSection);
399 EmitAlignment(AlignLog, GV);
400 OutStreamer.EmitLabel(MangSym);
402 EmitGlobalConstant(GV->getInitializer());
405 OutStreamer.AddBlankLine();
407 // Emit the variable struct for the runtime.
408 const MCSection *TLVSect
409 = getObjFileLowering().getTLSExtraDataSection();
411 OutStreamer.SwitchSection(TLVSect);
412 // Emit the linkage here.
413 EmitLinkage(GV, GVSym);
414 OutStreamer.EmitLabel(GVSym);
416 // Three pointers in size:
417 // - __tlv_bootstrap - used to make sure support exists
418 // - spare pointer, used when mapped by the runtime
419 // - pointer to mangled symbol above with initializer
420 unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
421 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
423 OutStreamer.EmitIntValue(0, PtrSize);
424 OutStreamer.EmitSymbolValue(MangSym, PtrSize);
426 OutStreamer.AddBlankLine();
430 OutStreamer.SwitchSection(TheSection);
432 EmitLinkage(GV, GVSym);
433 EmitAlignment(AlignLog, GV);
435 OutStreamer.EmitLabel(GVSym);
437 EmitGlobalConstant(GV->getInitializer());
439 if (MAI->hasDotTypeDotSizeDirective())
441 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
443 OutStreamer.AddBlankLine();
446 /// EmitFunctionHeader - This method emits the header for the current
448 void AsmPrinter::EmitFunctionHeader() {
449 // Print out constants referenced by the function
452 // Print the 'header' of function.
453 const Function *F = MF->getFunction();
455 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
456 EmitVisibility(CurrentFnSym, F->getVisibility());
458 EmitLinkage(F, CurrentFnSym);
459 EmitAlignment(MF->getAlignment(), F);
461 if (MAI->hasDotTypeDotSizeDirective())
462 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
465 WriteAsOperand(OutStreamer.GetCommentOS(), F,
466 /*PrintType=*/false, F->getParent());
467 OutStreamer.GetCommentOS() << '\n';
470 // Emit the CurrentFnSym. This is a virtual function to allow targets to
471 // do their wild and crazy things as required.
472 EmitFunctionEntryLabel();
474 // If the function had address-taken blocks that got deleted, then we have
475 // references to the dangling symbols. Emit them at the start of the function
476 // so that we don't get references to undefined symbols.
477 std::vector<MCSymbol*> DeadBlockSyms;
478 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
479 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
480 OutStreamer.AddComment("Address taken block that was later removed");
481 OutStreamer.EmitLabel(DeadBlockSyms[i]);
484 // Emit pre-function debug and/or EH information.
486 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
487 DE->BeginFunction(MF);
490 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
491 DD->beginFunction(MF);
494 // Emit the prefix data.
495 if (F->hasPrefixData())
496 EmitGlobalConstant(F->getPrefixData());
499 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
500 /// function. This can be overridden by targets as required to do custom stuff.
501 void AsmPrinter::EmitFunctionEntryLabel() {
502 // The function label could have already been emitted if two symbols end up
503 // conflicting due to asm renaming. Detect this and emit an error.
504 if (CurrentFnSym->isUndefined())
505 return OutStreamer.EmitLabel(CurrentFnSym);
507 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
508 "' label emitted multiple times to assembly file");
511 /// emitComments - Pretty-print comments for instructions.
512 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
513 const MachineFunction *MF = MI.getParent()->getParent();
514 const TargetMachine &TM = MF->getTarget();
516 // Check for spills and reloads
519 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
521 // We assume a single instruction only has a spill or reload, not
523 const MachineMemOperand *MMO;
524 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
525 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
526 MMO = *MI.memoperands_begin();
527 CommentOS << MMO->getSize() << "-byte Reload\n";
529 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
530 if (FrameInfo->isSpillSlotObjectIndex(FI))
531 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
532 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
533 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
534 MMO = *MI.memoperands_begin();
535 CommentOS << MMO->getSize() << "-byte Spill\n";
537 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
538 if (FrameInfo->isSpillSlotObjectIndex(FI))
539 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
542 // Check for spill-induced copies
543 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
544 CommentOS << " Reload Reuse\n";
547 /// emitImplicitDef - This method emits the specified machine instruction
548 /// that is an implicit def.
549 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
550 unsigned RegNo = MI->getOperand(0).getReg();
551 OutStreamer.AddComment(Twine("implicit-def: ") +
552 TM.getRegisterInfo()->getName(RegNo));
553 OutStreamer.AddBlankLine();
556 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
557 std::string Str = "kill:";
558 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
559 const MachineOperand &Op = MI->getOperand(i);
560 assert(Op.isReg() && "KILL instruction must have only register operands");
562 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
563 Str += (Op.isDef() ? "<def>" : "<kill>");
565 AP.OutStreamer.AddComment(Str);
566 AP.OutStreamer.AddBlankLine();
569 /// emitDebugValueComment - This method handles the target-independent form
570 /// of DBG_VALUE, returning true if it was able to do so. A false return
571 /// means the target will need to handle MI in EmitInstruction.
572 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
573 // This code handles only the 3-operand target-independent form.
574 if (MI->getNumOperands() != 3)
577 SmallString<128> Str;
578 raw_svector_ostream OS(Str);
579 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
581 // cast away const; DIetc do not take const operands for some reason.
582 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
583 if (V.getContext().isSubprogram()) {
584 StringRef Name = DISubprogram(V.getContext()).getDisplayName();
588 OS << V.getName() << " <- ";
590 // The second operand is only an offset if it's an immediate.
591 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
592 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
594 // Register or immediate value. Register 0 means undef.
595 if (MI->getOperand(0).isFPImm()) {
596 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
597 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
598 OS << (double)APF.convertToFloat();
599 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
600 OS << APF.convertToDouble();
602 // There is no good way to print long double. Convert a copy to
603 // double. Ah well, it's only a comment.
605 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
607 OS << "(long double) " << APF.convertToDouble();
609 } else if (MI->getOperand(0).isImm()) {
610 OS << MI->getOperand(0).getImm();
611 } else if (MI->getOperand(0).isCImm()) {
612 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
615 if (MI->getOperand(0).isReg()) {
616 Reg = MI->getOperand(0).getReg();
618 assert(MI->getOperand(0).isFI() && "Unknown operand type");
619 const TargetFrameLowering *TFI = AP.TM.getFrameLowering();
620 Offset += TFI->getFrameIndexReference(*AP.MF,
621 MI->getOperand(0).getIndex(), Reg);
625 // Suppress offset, it is not meaningful here.
627 // NOTE: Want this comment at start of line, don't emit with AddComment.
628 AP.OutStreamer.EmitRawText(OS.str());
633 OS << AP.TM.getRegisterInfo()->getName(Reg);
637 OS << '+' << Offset << ']';
639 // NOTE: Want this comment at start of line, don't emit with AddComment.
640 AP.OutStreamer.EmitRawText(OS.str());
644 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
645 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
646 MF->getFunction()->needsUnwindTableEntry())
649 if (MMI->hasDebugInfo())
655 bool AsmPrinter::needsSEHMoves() {
656 return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
657 MF->getFunction()->needsUnwindTableEntry();
660 bool AsmPrinter::needsRelocationsForDwarfStringPool() const {
661 return MAI->doesDwarfUseRelocationsAcrossSections();
664 void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
665 const MCSymbol *Label = MI.getOperand(0).getMCSymbol();
667 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
670 if (needsCFIMoves() == CFI_M_None)
673 if (MMI->getCompactUnwindEncoding() != 0)
674 OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
676 const MachineModuleInfo &MMI = MF->getMMI();
677 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
678 bool FoundOne = false;
680 for (std::vector<MCCFIInstruction>::const_iterator I = Instrs.begin(),
681 E = Instrs.end(); I != E; ++I) {
682 if (I->getLabel() == Label) {
683 emitCFIInstruction(*I);
690 /// EmitFunctionBody - This method emits the body and trailer for a
692 void AsmPrinter::EmitFunctionBody() {
693 // Emit target-specific gunk before the function body.
694 EmitFunctionBodyStart();
696 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
698 // Print out code for the function.
699 bool HasAnyRealCode = false;
700 const MachineInstr *LastMI = 0;
701 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
703 // Print a label for the basic block.
704 EmitBasicBlockStart(I);
705 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
709 // Print the assembly for the instruction.
710 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
711 !II->isDebugValue()) {
712 HasAnyRealCode = true;
716 if (ShouldPrintDebugScopes) {
717 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
718 DD->beginInstruction(II);
722 emitComments(*II, OutStreamer.GetCommentOS());
724 switch (II->getOpcode()) {
725 case TargetOpcode::PROLOG_LABEL:
726 emitPrologLabel(*II);
729 case TargetOpcode::EH_LABEL:
730 case TargetOpcode::GC_LABEL:
731 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
733 case TargetOpcode::INLINEASM:
736 case TargetOpcode::DBG_VALUE:
738 if (!emitDebugValueComment(II, *this))
742 case TargetOpcode::IMPLICIT_DEF:
743 if (isVerbose()) emitImplicitDef(II);
745 case TargetOpcode::KILL:
746 if (isVerbose()) emitKill(II, *this);
749 if (!TM.hasMCUseLoc())
750 MCLineEntry::Make(&OutStreamer, getCurrentSection());
756 if (ShouldPrintDebugScopes) {
757 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
758 DD->endInstruction(II);
763 // If the last instruction was a prolog label, then we have a situation where
764 // we emitted a prolog but no function body. This results in the ending prolog
765 // label equaling the end of function label and an invalid "row" in the
766 // FDE. We need to emit a noop in this situation so that the FDE's rows are
768 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
770 // If the function is empty and the object file uses .subsections_via_symbols,
771 // then we need to emit *something* to the function body to prevent the
772 // labels from collapsing together. Just emit a noop.
773 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
775 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
776 if (Noop.getOpcode()) {
777 OutStreamer.AddComment("avoids zero-length function");
778 OutStreamer.EmitInstruction(Noop);
779 } else // Target not mc-ized yet.
780 OutStreamer.EmitRawText(StringRef("\tnop\n"));
783 const Function *F = MF->getFunction();
784 for (Function::const_iterator i = F->begin(), e = F->end(); i != e; ++i) {
785 const BasicBlock *BB = i;
786 if (!BB->hasAddressTaken())
788 MCSymbol *Sym = GetBlockAddressSymbol(BB);
789 if (Sym->isDefined())
791 OutStreamer.AddComment("Address of block that was removed by CodeGen");
792 OutStreamer.EmitLabel(Sym);
795 // Emit target-specific gunk after the function body.
796 EmitFunctionBodyEnd();
798 // If the target wants a .size directive for the size of the function, emit
800 if (MAI->hasDotTypeDotSizeDirective()) {
801 // Create a symbol for the end of function, so we can get the size as
802 // difference between the function label and the temp label.
803 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
804 OutStreamer.EmitLabel(FnEndLabel);
806 const MCExpr *SizeExp =
807 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
808 MCSymbolRefExpr::Create(CurrentFnSymForSize,
811 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
814 // Emit post-function debug information.
816 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
820 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
825 // Print out jump tables referenced by the function.
828 OutStreamer.AddBlankLine();
831 /// EmitDwarfRegOp - Emit dwarf register operation.
832 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc,
833 bool Indirect) const {
834 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
835 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
837 for (MCSuperRegIterator SR(MLoc.getReg(), TRI); SR.isValid() && Reg < 0;
839 Reg = TRI->getDwarfRegNum(*SR, false);
840 // FIXME: Get the bit range this register uses of the superregister
841 // so that we can produce a DW_OP_bit_piece
844 // FIXME: Handle cases like a super register being encoded as
845 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
847 // FIXME: We have no reasonable way of handling errors in here. The
848 // caller might be in the middle of an dwarf expression. We should
849 // probably assert that Reg >= 0 once debug info generation is more mature.
851 if (MLoc.isIndirect() || Indirect) {
853 OutStreamer.AddComment(
854 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
855 EmitInt8(dwarf::DW_OP_breg0 + Reg);
857 OutStreamer.AddComment("DW_OP_bregx");
858 EmitInt8(dwarf::DW_OP_bregx);
859 OutStreamer.AddComment(Twine(Reg));
862 EmitSLEB128(!MLoc.isIndirect() ? 0 : MLoc.getOffset());
863 if (MLoc.isIndirect() && Indirect)
864 EmitInt8(dwarf::DW_OP_deref);
867 OutStreamer.AddComment(
868 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
869 EmitInt8(dwarf::DW_OP_reg0 + Reg);
871 OutStreamer.AddComment("DW_OP_regx");
872 EmitInt8(dwarf::DW_OP_regx);
873 OutStreamer.AddComment(Twine(Reg));
878 // FIXME: Produce a DW_OP_bit_piece if we used a superregister
881 bool AsmPrinter::doFinalization(Module &M) {
882 // Emit global variables.
883 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
885 EmitGlobalVariable(I);
887 // Emit visibility info for declarations
888 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
889 const Function &F = *I;
890 if (!F.isDeclaration())
892 GlobalValue::VisibilityTypes V = F.getVisibility();
893 if (V == GlobalValue::DefaultVisibility)
896 MCSymbol *Name = getSymbol(&F);
897 EmitVisibility(Name, V, false);
900 // Emit module flags.
901 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
902 M.getModuleFlagsMetadata(ModuleFlags);
903 if (!ModuleFlags.empty())
904 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, Mang, TM);
906 // Make sure we wrote out everything we need.
909 // Finalize debug and EH information.
912 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
919 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
925 // If the target wants to know about weak references, print them all.
926 if (MAI->getWeakRefDirective()) {
927 // FIXME: This is not lazy, it would be nice to only print weak references
928 // to stuff that is actually used. Note that doing so would require targets
929 // to notice uses in operands (due to constant exprs etc). This should
930 // happen with the MC stuff eventually.
932 // Print out module-level global variables here.
933 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
935 if (!I->hasExternalWeakLinkage()) continue;
936 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
939 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
940 if (!I->hasExternalWeakLinkage()) continue;
941 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
945 if (MAI->hasSetDirective()) {
946 OutStreamer.AddBlankLine();
947 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
949 MCSymbol *Name = getSymbol(I);
951 const GlobalValue *GV = I->getAliasedGlobal();
952 MCSymbol *Target = getSymbol(GV);
954 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
955 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
956 else if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
957 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
959 assert(I->hasLocalLinkage() && "Invalid alias linkage");
961 EmitVisibility(Name, I->getVisibility());
963 // Emit the directives as assignments aka .set:
964 OutStreamer.EmitAssignment(Name,
965 MCSymbolRefExpr::Create(Target, OutContext));
969 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
970 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
971 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
972 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
973 MP->finishAssembly(*this);
975 // Emit llvm.ident metadata in an '.ident' directive.
978 // If we don't have any trampolines, then we don't require stack memory
979 // to be executable. Some targets have a directive to declare this.
980 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
981 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
982 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
983 OutStreamer.SwitchSection(S);
985 // Allow the target to emit any magic that it wants at the end of the file,
986 // after everything else has gone out.
989 delete Mang; Mang = 0;
992 OutStreamer.Finish();
998 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1000 // Get the function symbol.
1001 CurrentFnSym = getSymbol(MF.getFunction());
1002 CurrentFnSymForSize = CurrentFnSym;
1005 LI = &getAnalysis<MachineLoopInfo>();
1009 // SectionCPs - Keep track the alignment, constpool entries per Section.
1013 SmallVector<unsigned, 4> CPEs;
1014 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1018 /// EmitConstantPool - Print to the current output stream assembly
1019 /// representations of the constants in the constant pool MCP. This is
1020 /// used to print out constants which have been "spilled to memory" by
1021 /// the code generator.
1023 void AsmPrinter::EmitConstantPool() {
1024 const MachineConstantPool *MCP = MF->getConstantPool();
1025 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1026 if (CP.empty()) return;
1028 // Calculate sections for constant pool entries. We collect entries to go into
1029 // the same section together to reduce amount of section switch statements.
1030 SmallVector<SectionCPs, 4> CPSections;
1031 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1032 const MachineConstantPoolEntry &CPE = CP[i];
1033 unsigned Align = CPE.getAlignment();
1036 switch (CPE.getRelocationInfo()) {
1037 default: llvm_unreachable("Unknown section kind");
1038 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
1040 Kind = SectionKind::getReadOnlyWithRelLocal();
1043 switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) {
1044 case 4: Kind = SectionKind::getMergeableConst4(); break;
1045 case 8: Kind = SectionKind::getMergeableConst8(); break;
1046 case 16: Kind = SectionKind::getMergeableConst16();break;
1047 default: Kind = SectionKind::getMergeableConst(); break;
1051 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
1053 // The number of sections are small, just do a linear search from the
1054 // last section to the first.
1056 unsigned SecIdx = CPSections.size();
1057 while (SecIdx != 0) {
1058 if (CPSections[--SecIdx].S == S) {
1064 SecIdx = CPSections.size();
1065 CPSections.push_back(SectionCPs(S, Align));
1068 if (Align > CPSections[SecIdx].Alignment)
1069 CPSections[SecIdx].Alignment = Align;
1070 CPSections[SecIdx].CPEs.push_back(i);
1073 // Now print stuff into the calculated sections.
1074 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1075 OutStreamer.SwitchSection(CPSections[i].S);
1076 EmitAlignment(Log2_32(CPSections[i].Alignment));
1078 unsigned Offset = 0;
1079 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1080 unsigned CPI = CPSections[i].CPEs[j];
1081 MachineConstantPoolEntry CPE = CP[CPI];
1083 // Emit inter-object padding for alignment.
1084 unsigned AlignMask = CPE.getAlignment() - 1;
1085 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1086 OutStreamer.EmitZeros(NewOffset - Offset);
1088 Type *Ty = CPE.getType();
1089 Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
1090 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1092 if (CPE.isMachineConstantPoolEntry())
1093 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1095 EmitGlobalConstant(CPE.Val.ConstVal);
1100 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1101 /// by the current function to the current output stream.
1103 void AsmPrinter::EmitJumpTableInfo() {
1104 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1105 if (MJTI == 0) return;
1106 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1107 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1108 if (JT.empty()) return;
1110 // Pick the directive to use to print the jump table entries, and switch to
1111 // the appropriate section.
1112 const Function *F = MF->getFunction();
1113 bool JTInDiffSection = false;
1114 if (// In PIC mode, we need to emit the jump table to the same section as the
1115 // function body itself, otherwise the label differences won't make sense.
1116 // FIXME: Need a better predicate for this: what about custom entries?
1117 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1118 // We should also do if the section name is NULL or function is declared
1119 // in discardable section
1120 // FIXME: this isn't the right predicate, should be based on the MCSection
1121 // for the function.
1122 F->isWeakForLinker()) {
1123 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1125 // Otherwise, drop it in the readonly section.
1126 const MCSection *ReadOnlySection =
1127 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1128 OutStreamer.SwitchSection(ReadOnlySection);
1129 JTInDiffSection = true;
1132 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
1134 // Jump tables in code sections are marked with a data_region directive
1135 // where that's supported.
1136 if (!JTInDiffSection)
1137 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1139 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1140 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1142 // If this jump table was deleted, ignore it.
1143 if (JTBBs.empty()) continue;
1145 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1146 // .set directive for each unique entry. This reduces the number of
1147 // relocations the assembler will generate for the jump table.
1148 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1149 MAI->hasSetDirective()) {
1150 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1151 const TargetLowering *TLI = TM.getTargetLowering();
1152 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1153 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1154 const MachineBasicBlock *MBB = JTBBs[ii];
1155 if (!EmittedSets.insert(MBB)) continue;
1157 // .set LJTSet, LBB32-base
1159 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1160 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1161 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1165 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1166 // before each jump table. The first label is never referenced, but tells
1167 // the assembler and linker the extents of the jump table object. The
1168 // second label is actually referenced by the code.
1169 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1170 // FIXME: This doesn't have to have any specific name, just any randomly
1171 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1172 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1174 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1176 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1177 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1179 if (!JTInDiffSection)
1180 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1183 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1185 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1186 const MachineBasicBlock *MBB,
1187 unsigned UID) const {
1188 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1189 const MCExpr *Value = 0;
1190 switch (MJTI->getEntryKind()) {
1191 case MachineJumpTableInfo::EK_Inline:
1192 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1193 case MachineJumpTableInfo::EK_Custom32:
1194 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1197 case MachineJumpTableInfo::EK_BlockAddress:
1198 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1200 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1202 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1203 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1204 // with a relocation as gp-relative, e.g.:
1206 MCSymbol *MBBSym = MBB->getSymbol();
1207 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1211 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1212 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1213 // with a relocation as gp-relative, e.g.:
1215 MCSymbol *MBBSym = MBB->getSymbol();
1216 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1220 case MachineJumpTableInfo::EK_LabelDifference32: {
1221 // EK_LabelDifference32 - Each entry is the address of the block minus
1222 // the address of the jump table. This is used for PIC jump tables where
1223 // gprel32 is not supported. e.g.:
1224 // .word LBB123 - LJTI1_2
1225 // If the .set directive is supported, this is emitted as:
1226 // .set L4_5_set_123, LBB123 - LJTI1_2
1227 // .word L4_5_set_123
1229 // If we have emitted set directives for the jump table entries, print
1230 // them rather than the entries themselves. If we're emitting PIC, then
1231 // emit the table entries as differences between two text section labels.
1232 if (MAI->hasSetDirective()) {
1233 // If we used .set, reference the .set's symbol.
1234 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1238 // Otherwise, use the difference as the jump table entry.
1239 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1240 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1241 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1246 assert(Value && "Unknown entry kind!");
1248 unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
1249 OutStreamer.EmitValue(Value, EntrySize);
1253 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1254 /// special global used by LLVM. If so, emit it and return true, otherwise
1255 /// do nothing and return false.
1256 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1257 if (GV->getName() == "llvm.used") {
1258 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1259 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1263 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1264 if (GV->getSection() == "llvm.metadata" ||
1265 GV->hasAvailableExternallyLinkage())
1268 if (!GV->hasAppendingLinkage()) return false;
1270 assert(GV->hasInitializer() && "Not a special LLVM global!");
1272 if (GV->getName() == "llvm.global_ctors") {
1273 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1275 if (TM.getRelocationModel() == Reloc::Static &&
1276 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1277 StringRef Sym(".constructors_used");
1278 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1284 if (GV->getName() == "llvm.global_dtors") {
1285 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1287 if (TM.getRelocationModel() == Reloc::Static &&
1288 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1289 StringRef Sym(".destructors_used");
1290 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1299 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1300 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1301 /// is true, as being used with this directive.
1302 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1303 // Should be an array of 'i8*'.
1304 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1305 const GlobalValue *GV =
1306 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1307 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1308 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1312 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1314 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1315 // Should be an array of '{ int, void ()* }' structs. The first value is the
1317 if (!isa<ConstantArray>(List)) return;
1319 // Sanity check the structors list.
1320 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1321 if (!InitList) return; // Not an array!
1322 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1323 if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1324 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1325 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1327 // Gather the structors in a form that's convenient for sorting by priority.
1328 typedef std::pair<unsigned, Constant *> Structor;
1329 SmallVector<Structor, 8> Structors;
1330 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1331 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1332 if (!CS) continue; // Malformed.
1333 if (CS->getOperand(1)->isNullValue())
1334 break; // Found a null terminator, skip the rest.
1335 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1336 if (!Priority) continue; // Malformed.
1337 Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1338 CS->getOperand(1)));
1341 // Emit the function pointers in the target-specific order
1342 const DataLayout *DL = TM.getDataLayout();
1343 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1344 std::stable_sort(Structors.begin(), Structors.end(), less_first());
1345 for (unsigned i = 0, e = Structors.size(); i != e; ++i) {
1346 const MCSection *OutputSection =
1348 getObjFileLowering().getStaticCtorSection(Structors[i].first) :
1349 getObjFileLowering().getStaticDtorSection(Structors[i].first));
1350 OutStreamer.SwitchSection(OutputSection);
1351 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1352 EmitAlignment(Align);
1353 EmitXXStructor(Structors[i].second);
1357 void AsmPrinter::EmitModuleIdents(Module &M) {
1358 if (!MAI->hasIdentDirective())
1361 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1362 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1363 const MDNode *N = NMD->getOperand(i);
1364 assert(N->getNumOperands() == 1 &&
1365 "llvm.ident metadata entry can have only one operand");
1366 const MDString *S = cast<MDString>(N->getOperand(0));
1367 OutStreamer.EmitIdent(S->getString());
1372 //===--------------------------------------------------------------------===//
1373 // Emission and print routines
1376 /// EmitInt8 - Emit a byte directive and value.
1378 void AsmPrinter::EmitInt8(int Value) const {
1379 OutStreamer.EmitIntValue(Value, 1);
1382 /// EmitInt16 - Emit a short directive and value.
1384 void AsmPrinter::EmitInt16(int Value) const {
1385 OutStreamer.EmitIntValue(Value, 2);
1388 /// EmitInt32 - Emit a long directive and value.
1390 void AsmPrinter::EmitInt32(int Value) const {
1391 OutStreamer.EmitIntValue(Value, 4);
1394 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1395 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1396 /// labels. This implicitly uses .set if it is available.
1397 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1398 unsigned Size) const {
1399 // Get the Hi-Lo expression.
1400 const MCExpr *Diff =
1401 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1402 MCSymbolRefExpr::Create(Lo, OutContext),
1405 if (!MAI->hasSetDirective()) {
1406 OutStreamer.EmitValue(Diff, Size);
1410 // Otherwise, emit with .set (aka assignment).
1411 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1412 OutStreamer.EmitAssignment(SetLabel, Diff);
1413 OutStreamer.EmitSymbolValue(SetLabel, Size);
1416 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1417 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1418 /// specify the labels. This implicitly uses .set if it is available.
1419 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1420 const MCSymbol *Lo, unsigned Size)
1423 // Emit Hi+Offset - Lo
1424 // Get the Hi+Offset expression.
1425 const MCExpr *Plus =
1426 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1427 MCConstantExpr::Create(Offset, OutContext),
1430 // Get the Hi+Offset-Lo expression.
1431 const MCExpr *Diff =
1432 MCBinaryExpr::CreateSub(Plus,
1433 MCSymbolRefExpr::Create(Lo, OutContext),
1436 if (!MAI->hasSetDirective())
1437 OutStreamer.EmitValue(Diff, Size);
1439 // Otherwise, emit with .set (aka assignment).
1440 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1441 OutStreamer.EmitAssignment(SetLabel, Diff);
1442 OutStreamer.EmitSymbolValue(SetLabel, Size);
1446 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1447 /// where the size in bytes of the directive is specified by Size and Label
1448 /// specifies the label. This implicitly uses .set if it is available.
1449 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1450 unsigned Size, bool IsSectionRelative)
1452 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1453 OutStreamer.EmitCOFFSecRel32(Label);
1457 // Emit Label+Offset (or just Label if Offset is zero)
1458 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1460 Expr = MCBinaryExpr::CreateAdd(Expr,
1461 MCConstantExpr::Create(Offset, OutContext),
1464 OutStreamer.EmitValue(Expr, Size);
1468 //===----------------------------------------------------------------------===//
1470 // EmitAlignment - Emit an alignment directive to the specified power of
1471 // two boundary. For example, if you pass in 3 here, you will get an 8
1472 // byte alignment. If a global value is specified, and if that global has
1473 // an explicit alignment requested, it will override the alignment request
1474 // if required for correctness.
1476 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1477 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
1479 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1481 if (getCurrentSection()->getKind().isText())
1482 OutStreamer.EmitCodeAlignment(1 << NumBits);
1484 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1487 //===----------------------------------------------------------------------===//
1488 // Constant emission.
1489 //===----------------------------------------------------------------------===//
1491 /// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
1493 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
1494 MCContext &Ctx = AP.OutContext;
1496 if (CV->isNullValue() || isa<UndefValue>(CV))
1497 return MCConstantExpr::Create(0, Ctx);
1499 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1500 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1502 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1503 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
1505 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1506 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1508 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1510 llvm_unreachable("Unknown constant value to lower!");
1513 switch (CE->getOpcode()) {
1515 // If the code isn't optimized, there may be outstanding folding
1516 // opportunities. Attempt to fold the expression using DataLayout as a
1517 // last resort before giving up.
1519 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
1521 return lowerConstant(C, AP);
1523 // Otherwise report the problem to the user.
1526 raw_string_ostream OS(S);
1527 OS << "Unsupported expression in static initializer: ";
1528 WriteAsOperand(OS, CE, /*PrintType=*/false,
1529 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1530 report_fatal_error(OS.str());
1532 case Instruction::GetElementPtr: {
1533 const DataLayout &DL = *AP.TM.getDataLayout();
1534 // Generate a symbolic expression for the byte address
1535 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1536 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1538 const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
1542 int64_t Offset = OffsetAI.getSExtValue();
1543 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1547 case Instruction::Trunc:
1548 // We emit the value and depend on the assembler to truncate the generated
1549 // expression properly. This is important for differences between
1550 // blockaddress labels. Since the two labels are in the same function, it
1551 // is reasonable to treat their delta as a 32-bit value.
1553 case Instruction::BitCast:
1554 return lowerConstant(CE->getOperand(0), AP);
1556 case Instruction::IntToPtr: {
1557 const DataLayout &DL = *AP.TM.getDataLayout();
1558 // Handle casts to pointers by changing them into casts to the appropriate
1559 // integer type. This promotes constant folding and simplifies this code.
1560 Constant *Op = CE->getOperand(0);
1561 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1563 return lowerConstant(Op, AP);
1566 case Instruction::PtrToInt: {
1567 const DataLayout &DL = *AP.TM.getDataLayout();
1568 // Support only foldable casts to/from pointers that can be eliminated by
1569 // changing the pointer to the appropriately sized integer type.
1570 Constant *Op = CE->getOperand(0);
1571 Type *Ty = CE->getType();
1573 const MCExpr *OpExpr = lowerConstant(Op, AP);
1575 // We can emit the pointer value into this slot if the slot is an
1576 // integer slot equal to the size of the pointer.
1577 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1580 // Otherwise the pointer is smaller than the resultant integer, mask off
1581 // the high bits so we are sure to get a proper truncation if the input is
1583 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1584 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1585 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1588 // The MC library also has a right-shift operator, but it isn't consistently
1589 // signed or unsigned between different targets.
1590 case Instruction::Add:
1591 case Instruction::Sub:
1592 case Instruction::Mul:
1593 case Instruction::SDiv:
1594 case Instruction::SRem:
1595 case Instruction::Shl:
1596 case Instruction::And:
1597 case Instruction::Or:
1598 case Instruction::Xor: {
1599 const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1600 const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
1601 switch (CE->getOpcode()) {
1602 default: llvm_unreachable("Unknown binary operator constant cast expr");
1603 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1604 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1605 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1606 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1607 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1608 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1609 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1610 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1611 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1617 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
1619 /// isRepeatedByteSequence - Determine whether the given value is
1620 /// composed of a repeated sequence of identical bytes and return the
1621 /// byte value. If it is not a repeated sequence, return -1.
1622 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1623 StringRef Data = V->getRawDataValues();
1624 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1626 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1627 if (Data[i] != C) return -1;
1628 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1632 /// isRepeatedByteSequence - Determine whether the given value is
1633 /// composed of a repeated sequence of identical bytes and return the
1634 /// byte value. If it is not a repeated sequence, return -1.
1635 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1637 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1638 if (CI->getBitWidth() > 64) return -1;
1640 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
1641 uint64_t Value = CI->getZExtValue();
1643 // Make sure the constant is at least 8 bits long and has a power
1644 // of 2 bit width. This guarantees the constant bit width is
1645 // always a multiple of 8 bits, avoiding issues with padding out
1646 // to Size and other such corner cases.
1647 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1649 uint8_t Byte = static_cast<uint8_t>(Value);
1651 for (unsigned i = 1; i < Size; ++i) {
1653 if (static_cast<uint8_t>(Value) != Byte) return -1;
1657 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1658 // Make sure all array elements are sequences of the same repeated
1660 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1661 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1662 if (Byte == -1) return -1;
1664 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1665 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1666 if (ThisByte == -1) return -1;
1667 if (Byte != ThisByte) return -1;
1672 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1673 return isRepeatedByteSequence(CDS);
1678 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1681 // See if we can aggregate this into a .fill, if so, emit it as such.
1682 int Value = isRepeatedByteSequence(CDS, AP.TM);
1684 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
1685 // Don't emit a 1-byte object as a .fill.
1687 return AP.OutStreamer.EmitFill(Bytes, Value);
1690 // If this can be emitted with .ascii/.asciz, emit it as such.
1691 if (CDS->isString())
1692 return AP.OutStreamer.EmitBytes(CDS->getAsString());
1694 // Otherwise, emit the values in successive locations.
1695 unsigned ElementByteSize = CDS->getElementByteSize();
1696 if (isa<IntegerType>(CDS->getElementType())) {
1697 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1699 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1700 CDS->getElementAsInteger(i));
1701 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1704 } else if (ElementByteSize == 4) {
1705 // FP Constants are printed as integer constants to avoid losing
1707 assert(CDS->getElementType()->isFloatTy());
1708 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1714 F = CDS->getElementAsFloat(i);
1716 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1717 AP.OutStreamer.EmitIntValue(I, 4);
1720 assert(CDS->getElementType()->isDoubleTy());
1721 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1727 F = CDS->getElementAsDouble(i);
1729 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1730 AP.OutStreamer.EmitIntValue(I, 8);
1734 const DataLayout &DL = *AP.TM.getDataLayout();
1735 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1736 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1737 CDS->getNumElements();
1738 if (unsigned Padding = Size - EmittedSize)
1739 AP.OutStreamer.EmitZeros(Padding);
1743 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
1744 // See if we can aggregate some values. Make sure it can be
1745 // represented as a series of bytes of the constant value.
1746 int Value = isRepeatedByteSequence(CA, AP.TM);
1749 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
1750 AP.OutStreamer.EmitFill(Bytes, Value);
1753 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1754 emitGlobalConstantImpl(CA->getOperand(i), AP);
1758 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1759 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1760 emitGlobalConstantImpl(CV->getOperand(i), AP);
1762 const DataLayout &DL = *AP.TM.getDataLayout();
1763 unsigned Size = DL.getTypeAllocSize(CV->getType());
1764 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1765 CV->getType()->getNumElements();
1766 if (unsigned Padding = Size - EmittedSize)
1767 AP.OutStreamer.EmitZeros(Padding);
1770 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
1771 // Print the fields in successive locations. Pad to align if needed!
1772 const DataLayout *DL = AP.TM.getDataLayout();
1773 unsigned Size = DL->getTypeAllocSize(CS->getType());
1774 const StructLayout *Layout = DL->getStructLayout(CS->getType());
1775 uint64_t SizeSoFar = 0;
1776 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1777 const Constant *Field = CS->getOperand(i);
1779 // Check if padding is needed and insert one or more 0s.
1780 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1781 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1782 - Layout->getElementOffset(i)) - FieldSize;
1783 SizeSoFar += FieldSize + PadSize;
1785 // Now print the actual field value.
1786 emitGlobalConstantImpl(Field, AP);
1788 // Insert padding - this may include padding to increase the size of the
1789 // current field up to the ABI size (if the struct is not packed) as well
1790 // as padding to ensure that the next field starts at the right offset.
1791 AP.OutStreamer.EmitZeros(PadSize);
1793 assert(SizeSoFar == Layout->getSizeInBytes() &&
1794 "Layout of constant struct may be incorrect!");
1797 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1798 APInt API = CFP->getValueAPF().bitcastToAPInt();
1800 // First print a comment with what we think the original floating-point value
1801 // should have been.
1802 if (AP.isVerbose()) {
1803 SmallString<8> StrVal;
1804 CFP->getValueAPF().toString(StrVal);
1806 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1807 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1810 // Now iterate through the APInt chunks, emitting them in endian-correct
1811 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1813 unsigned NumBytes = API.getBitWidth() / 8;
1814 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1815 const uint64_t *p = API.getRawData();
1817 // PPC's long double has odd notions of endianness compared to how LLVM
1818 // handles it: p[0] goes first for *big* endian on PPC.
1819 if (AP.TM.getDataLayout()->isBigEndian() != CFP->getType()->isPPC_FP128Ty()) {
1820 int Chunk = API.getNumWords() - 1;
1823 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1825 for (; Chunk >= 0; --Chunk)
1826 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1829 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1830 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1833 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
1836 // Emit the tail padding for the long double.
1837 const DataLayout &DL = *AP.TM.getDataLayout();
1838 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1839 DL.getTypeStoreSize(CFP->getType()));
1842 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
1843 const DataLayout *DL = AP.TM.getDataLayout();
1844 unsigned BitWidth = CI->getBitWidth();
1846 // Copy the value as we may massage the layout for constants whose bit width
1847 // is not a multiple of 64-bits.
1848 APInt Realigned(CI->getValue());
1849 uint64_t ExtraBits = 0;
1850 unsigned ExtraBitsSize = BitWidth & 63;
1852 if (ExtraBitsSize) {
1853 // The bit width of the data is not a multiple of 64-bits.
1854 // The extra bits are expected to be at the end of the chunk of the memory.
1856 // * Nothing to be done, just record the extra bits to emit.
1858 // * Record the extra bits to emit.
1859 // * Realign the raw data to emit the chunks of 64-bits.
1860 if (DL->isBigEndian()) {
1861 // Basically the structure of the raw data is a chunk of 64-bits cells:
1862 // 0 1 BitWidth / 64
1863 // [chunk1][chunk2] ... [chunkN].
1864 // The most significant chunk is chunkN and it should be emitted first.
1865 // However, due to the alignment issue chunkN contains useless bits.
1866 // Realign the chunks so that they contain only useless information:
1867 // ExtraBits 0 1 (BitWidth / 64) - 1
1868 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
1869 ExtraBits = Realigned.getRawData()[0] &
1870 (((uint64_t)-1) >> (64 - ExtraBitsSize));
1871 Realigned = Realigned.lshr(ExtraBitsSize);
1873 ExtraBits = Realigned.getRawData()[BitWidth / 64];
1876 // We don't expect assemblers to support integer data directives
1877 // for more than 64 bits, so we emit the data in at most 64-bit
1878 // quantities at a time.
1879 const uint64_t *RawData = Realigned.getRawData();
1880 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1881 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1882 AP.OutStreamer.EmitIntValue(Val, 8);
1885 if (ExtraBitsSize) {
1886 // Emit the extra bits after the 64-bits chunks.
1888 // Emit a directive that fills the expected size.
1889 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(CI->getType());
1890 Size -= (BitWidth / 64) * 8;
1891 assert(Size && Size * 8 >= ExtraBitsSize &&
1892 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
1893 == ExtraBits && "Directive too small for extra bits.");
1894 AP.OutStreamer.EmitIntValue(ExtraBits, Size);
1898 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
1899 const DataLayout *DL = AP.TM.getDataLayout();
1900 uint64_t Size = DL->getTypeAllocSize(CV->getType());
1901 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
1902 return AP.OutStreamer.EmitZeros(Size);
1904 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1911 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1912 CI->getZExtValue());
1913 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
1916 emitGlobalConstantLargeInt(CI, AP);
1921 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1922 return emitGlobalConstantFP(CFP, AP);
1924 if (isa<ConstantPointerNull>(CV)) {
1925 AP.OutStreamer.EmitIntValue(0, Size);
1929 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
1930 return emitGlobalConstantDataSequential(CDS, AP);
1932 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1933 return emitGlobalConstantArray(CVA, AP);
1935 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1936 return emitGlobalConstantStruct(CVS, AP);
1938 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1939 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
1941 if (CE->getOpcode() == Instruction::BitCast)
1942 return emitGlobalConstantImpl(CE->getOperand(0), AP);
1945 // If the constant expression's size is greater than 64-bits, then we have
1946 // to emit the value in chunks. Try to constant fold the value and emit it
1948 Constant *New = ConstantFoldConstantExpression(CE, DL);
1949 if (New && New != CE)
1950 return emitGlobalConstantImpl(New, AP);
1954 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1955 return emitGlobalConstantVector(V, AP);
1957 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1958 // thread the streamer with EmitValue.
1959 AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
1962 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1963 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
1964 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
1966 emitGlobalConstantImpl(CV, *this);
1967 else if (MAI->hasSubsectionsViaSymbols()) {
1968 // If the global has zero size, emit a single byte so that two labels don't
1969 // look like they are at the same location.
1970 OutStreamer.EmitIntValue(0, 1);
1974 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1975 // Target doesn't support this yet!
1976 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1979 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1981 OS << '+' << Offset;
1982 else if (Offset < 0)
1986 //===----------------------------------------------------------------------===//
1987 // Symbol Lowering Routines.
1988 //===----------------------------------------------------------------------===//
1990 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1991 /// temporary label with the specified stem and unique ID.
1992 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1993 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1997 /// GetTempSymbol - Return an assembler temporary label with the specified
1999 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
2000 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
2005 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2006 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2009 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2010 return MMI->getAddrLabelSymbol(BB);
2013 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2014 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2015 return OutContext.GetOrCreateSymbol
2016 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2017 + "_" + Twine(CPID));
2020 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2021 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2022 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2025 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2026 /// FIXME: privatize to AsmPrinter.
2027 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2028 return OutContext.GetOrCreateSymbol
2029 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2030 Twine(UID) + "_set_" + Twine(MBBID));
2033 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
2034 /// global value name as its base, with the specified suffix, and where the
2035 /// symbol is forced to have private linkage if ForcePrivate is true.
2036 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
2038 bool ForcePrivate) const {
2039 SmallString<60> NameStr;
2040 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
2041 NameStr.append(Suffix.begin(), Suffix.end());
2042 return OutContext.GetOrCreateSymbol(NameStr.str());
2045 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2047 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2048 SmallString<60> NameStr;
2049 Mang->getNameWithPrefix(NameStr, Sym);
2050 return OutContext.GetOrCreateSymbol(NameStr.str());
2055 /// PrintParentLoopComment - Print comments about parent loops of this one.
2056 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2057 unsigned FunctionNumber) {
2058 if (Loop == 0) return;
2059 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2060 OS.indent(Loop->getLoopDepth()*2)
2061 << "Parent Loop BB" << FunctionNumber << "_"
2062 << Loop->getHeader()->getNumber()
2063 << " Depth=" << Loop->getLoopDepth() << '\n';
2067 /// PrintChildLoopComment - Print comments about child loops within
2068 /// the loop for this basic block, with nesting.
2069 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2070 unsigned FunctionNumber) {
2071 // Add child loop information
2072 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
2073 OS.indent((*CL)->getLoopDepth()*2)
2074 << "Child Loop BB" << FunctionNumber << "_"
2075 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
2077 PrintChildLoopComment(OS, *CL, FunctionNumber);
2081 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2082 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2083 const MachineLoopInfo *LI,
2084 const AsmPrinter &AP) {
2085 // Add loop depth information
2086 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2087 if (Loop == 0) return;
2089 MachineBasicBlock *Header = Loop->getHeader();
2090 assert(Header && "No header for loop");
2092 // If this block is not a loop header, just print out what is the loop header
2094 if (Header != &MBB) {
2095 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2096 Twine(AP.getFunctionNumber())+"_" +
2097 Twine(Loop->getHeader()->getNumber())+
2098 " Depth="+Twine(Loop->getLoopDepth()));
2102 // Otherwise, it is a loop header. Print out information about child and
2104 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2106 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2109 OS.indent(Loop->getLoopDepth()*2-2);
2114 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2116 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2120 /// EmitBasicBlockStart - This method prints the label for the specified
2121 /// MachineBasicBlock, an alignment (if present) and a comment describing
2122 /// it if appropriate.
2123 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
2124 // Emit an alignment directive for this block, if needed.
2125 if (unsigned Align = MBB->getAlignment())
2126 EmitAlignment(Align);
2128 // If the block has its address taken, emit any labels that were used to
2129 // reference the block. It is possible that there is more than one label
2130 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2131 // the references were generated.
2132 if (MBB->hasAddressTaken()) {
2133 const BasicBlock *BB = MBB->getBasicBlock();
2135 OutStreamer.AddComment("Block address taken");
2137 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
2139 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
2140 OutStreamer.EmitLabel(Syms[i]);
2143 // Print some verbose block comments.
2145 if (const BasicBlock *BB = MBB->getBasicBlock())
2147 OutStreamer.AddComment("%" + BB->getName());
2148 emitBasicBlockLoopComments(*MBB, LI, *this);
2151 // Print the main label for the block.
2152 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
2153 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
2154 // NOTE: Want this comment at start of line, don't emit with AddComment.
2155 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
2156 Twine(MBB->getNumber()) + ":");
2159 OutStreamer.EmitLabel(MBB->getSymbol());
2163 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2164 bool IsDefinition) const {
2165 MCSymbolAttr Attr = MCSA_Invalid;
2167 switch (Visibility) {
2169 case GlobalValue::HiddenVisibility:
2171 Attr = MAI->getHiddenVisibilityAttr();
2173 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2175 case GlobalValue::ProtectedVisibility:
2176 Attr = MAI->getProtectedVisibilityAttr();
2180 if (Attr != MCSA_Invalid)
2181 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2184 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2185 /// exactly one predecessor and the control transfer mechanism between
2186 /// the predecessor and this block is a fall-through.
2188 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2189 // If this is a landing pad, it isn't a fall through. If it has no preds,
2190 // then nothing falls through to it.
2191 if (MBB->isLandingPad() || MBB->pred_empty())
2194 // If there isn't exactly one predecessor, it can't be a fall through.
2195 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2197 if (PI2 != MBB->pred_end())
2200 // The predecessor has to be immediately before this block.
2201 MachineBasicBlock *Pred = *PI;
2203 if (!Pred->isLayoutSuccessor(MBB))
2206 // If the block is completely empty, then it definitely does fall through.
2210 // Check the terminators in the previous blocks
2211 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2212 IE = Pred->end(); II != IE; ++II) {
2213 MachineInstr &MI = *II;
2215 // If it is not a simple branch, we are in a table somewhere.
2216 if (!MI.isBranch() || MI.isIndirectBranch())
2219 // If we are the operands of one of the branches, this is not
2221 for (MachineInstr::mop_iterator OI = MI.operands_begin(),
2222 OE = MI.operands_end(); OI != OE; ++OI) {
2223 const MachineOperand& OP = *OI;
2226 if (OP.isMBB() && OP.getMBB() == MBB)
2236 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2237 if (!S->usesMetadata())
2240 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2241 gcp_map_type::iterator GCPI = GCMap.find(S);
2242 if (GCPI != GCMap.end())
2243 return GCPI->second;
2245 const char *Name = S->getName().c_str();
2247 for (GCMetadataPrinterRegistry::iterator
2248 I = GCMetadataPrinterRegistry::begin(),
2249 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2250 if (strcmp(Name, I->getName()) == 0) {
2251 GCMetadataPrinter *GMP = I->instantiate();
2253 GCMap.insert(std::make_pair(S, GMP));
2257 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));