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/CodeGen/GCMetadataPrinter.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBundle.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/Mangler.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Operator.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCExpr.h"
37 #include "llvm/MC/MCInst.h"
38 #include "llvm/MC/MCSection.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/Format.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/Timer.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/Target/TargetSubtargetInfo.h"
52 #include "llvm/Transforms/Utils/GlobalStatus.h"
53 #include "WinCodeViewLineTables.h"
56 static const char *const DWARFGroupName = "DWARF Emission";
57 static const char *const DbgTimerName = "Debug Info Emission";
58 static const char *const EHTimerName = "DWARF Exception Writer";
59 static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables";
61 STATISTIC(EmittedInsts, "Number of machine instrs printed");
63 char AsmPrinter::ID = 0;
65 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
66 static gcp_map_type &getGCMap(void *&P) {
68 P = new gcp_map_type();
69 return *(gcp_map_type*)P;
73 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
74 /// value in log2 form. This rounds up to the preferred alignment if possible
76 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
77 unsigned InBits = 0) {
79 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
80 NumBits = TD.getPreferredAlignmentLog(GVar);
82 // If InBits is specified, round it to it.
86 // If the GV has a specified alignment, take it into account.
87 if (GV->getAlignment() == 0)
90 unsigned GVAlign = Log2_32(GV->getAlignment());
92 // If the GVAlign is larger than NumBits, or if we are required to obey
93 // NumBits because the GV has an assigned section, obey it.
94 if (GVAlign > NumBits || GV->hasSection())
99 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
100 : MachineFunctionPass(ID),
101 TM(tm), MAI(tm.getMCAsmInfo()), MII(tm.getInstrInfo()),
102 OutContext(Streamer.getContext()),
103 OutStreamer(Streamer),
104 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
105 DD = 0; MMI = 0; LI = 0; MF = 0;
106 CurrentFnSym = CurrentFnSymForSize = 0;
107 GCMetadataPrinters = 0;
108 VerboseAsm = Streamer.isVerboseAsm();
111 AsmPrinter::~AsmPrinter() {
112 assert(DD == 0 && Handlers.empty() && "Debug/EH info didn't get finalized");
114 if (GCMetadataPrinters != 0) {
115 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
117 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
120 GCMetadataPrinters = 0;
126 /// getFunctionNumber - Return a unique ID for the current function.
128 unsigned AsmPrinter::getFunctionNumber() const {
129 return MF->getFunctionNumber();
132 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
133 return TM.getTargetLowering()->getObjFileLowering();
136 /// getDataLayout - Return information about data layout.
137 const DataLayout &AsmPrinter::getDataLayout() const {
138 return *TM.getDataLayout();
141 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
142 return TM.getSubtarget<MCSubtargetInfo>();
145 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
146 S.EmitInstruction(Inst, getSubtargetInfo());
149 StringRef AsmPrinter::getTargetTriple() const {
150 return TM.getTargetTriple();
153 /// getCurrentSection() - Return the current section we are emitting to.
154 const MCSection *AsmPrinter::getCurrentSection() const {
155 return OutStreamer.getCurrentSection().first;
160 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
161 AU.setPreservesAll();
162 MachineFunctionPass::getAnalysisUsage(AU);
163 AU.addRequired<MachineModuleInfo>();
164 AU.addRequired<GCModuleInfo>();
166 AU.addRequired<MachineLoopInfo>();
169 bool AsmPrinter::doInitialization(Module &M) {
170 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
171 MMI->AnalyzeModule(M);
173 // Initialize TargetLoweringObjectFile.
174 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
175 .Initialize(OutContext, TM);
177 OutStreamer.InitSections(false);
179 Mang = new Mangler(TM.getDataLayout());
181 // Allow the target to emit any magic that it wants at the start of the file.
182 EmitStartOfAsmFile(M);
184 // Very minimal debug info. It is ignored if we emit actual debug info. If we
185 // don't, this at least helps the user find where a global came from.
186 if (MAI->hasSingleParameterDotFile()) {
188 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
191 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
192 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
193 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
194 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
195 MP->beginAssembly(*this);
197 // Emit module-level inline asm if it exists.
198 if (!M.getModuleInlineAsm().empty()) {
199 OutStreamer.AddComment("Start of file scope inline assembly");
200 OutStreamer.AddBlankLine();
201 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
202 OutStreamer.AddComment("End of file scope inline assembly");
203 OutStreamer.AddBlankLine();
206 if (MAI->doesSupportDebugInformation()) {
207 if (Triple(TM.getTargetTriple()).getOS() == Triple::Win32) {
208 Handlers.push_back(HandlerInfo(new WinCodeViewLineTables(this),
210 CodeViewLineTablesGroupName));
212 DD = new DwarfDebug(this, &M);
213 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
217 DwarfException *DE = 0;
218 switch (MAI->getExceptionHandlingType()) {
219 case ExceptionHandling::None:
221 case ExceptionHandling::SjLj:
222 case ExceptionHandling::DwarfCFI:
223 DE = new DwarfCFIException(this);
225 case ExceptionHandling::ARM:
226 DE = new ARMException(this);
228 case ExceptionHandling::Win64:
229 DE = new Win64Exception(this);
233 Handlers.push_back(HandlerInfo(DE, EHTimerName, DWARFGroupName));
237 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
238 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
239 if (Linkage != GlobalValue::LinkOnceODRLinkage)
242 if (!MAI.hasWeakDefCanBeHiddenDirective())
245 if (GV->hasUnnamedAddr())
249 if (!GlobalStatus::analyzeGlobal(GV, GS) && !GS.IsCompared)
255 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
256 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
258 case GlobalValue::CommonLinkage:
259 case GlobalValue::LinkOnceAnyLinkage:
260 case GlobalValue::LinkOnceODRLinkage:
261 case GlobalValue::WeakAnyLinkage:
262 case GlobalValue::WeakODRLinkage:
263 case GlobalValue::LinkerPrivateWeakLinkage:
264 if (MAI->hasWeakDefDirective()) {
266 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
268 if (!canBeHidden(GV, *MAI))
269 // .weak_definition _foo
270 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
272 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
273 } else if (MAI->hasLinkOnceDirective()) {
275 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
276 //NOTE: linkonce is handled by the section the symbol was assigned to.
279 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
282 case GlobalValue::AppendingLinkage:
283 // FIXME: appending linkage variables should go into a section of
284 // their name or something. For now, just emit them as external.
285 case GlobalValue::ExternalLinkage:
286 // If external or appending, declare as a global symbol.
288 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
290 case GlobalValue::PrivateLinkage:
291 case GlobalValue::InternalLinkage:
292 case GlobalValue::LinkerPrivateLinkage:
294 case GlobalValue::AvailableExternallyLinkage:
295 llvm_unreachable("Should never emit this");
296 case GlobalValue::ExternalWeakLinkage:
297 llvm_unreachable("Don't know how to emit these");
299 llvm_unreachable("Unknown linkage type!");
302 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
303 return getObjFileLowering().getSymbol(*Mang, GV);
306 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
307 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
308 if (GV->hasInitializer()) {
309 // Check to see if this is a special global used by LLVM, if so, emit it.
310 if (EmitSpecialLLVMGlobal(GV))
314 GV->printAsOperand(OutStreamer.GetCommentOS(),
315 /*PrintType=*/false, GV->getParent());
316 OutStreamer.GetCommentOS() << '\n';
320 MCSymbol *GVSym = getSymbol(GV);
321 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
323 if (!GV->hasInitializer()) // External globals require no extra code.
326 if (MAI->hasDotTypeDotSizeDirective())
327 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
329 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
331 const DataLayout *DL = TM.getDataLayout();
332 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
334 // If the alignment is specified, we *must* obey it. Overaligning a global
335 // with a specified alignment is a prompt way to break globals emitted to
336 // sections and expected to be contiguous (e.g. ObjC metadata).
337 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
339 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
340 const HandlerInfo &OI = Handlers[I];
341 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName, TimePassesIsEnabled);
342 OI.Handler->setSymbolSize(GVSym, Size);
345 // Handle common and BSS local symbols (.lcomm).
346 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
347 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
348 unsigned Align = 1 << AlignLog;
350 // Handle common symbols.
351 if (GVKind.isCommon()) {
352 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
356 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
360 // Handle local BSS symbols.
361 if (MAI->hasMachoZeroFillDirective()) {
362 const MCSection *TheSection =
363 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
364 // .zerofill __DATA, __bss, _foo, 400, 5
365 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
369 // Use .lcomm only if it supports user-specified alignment.
370 // Otherwise, while it would still be correct to use .lcomm in some
371 // cases (e.g. when Align == 1), the external assembler might enfore
372 // some -unknown- default alignment behavior, which could cause
373 // spurious differences between external and integrated assembler.
374 // Prefer to simply fall back to .local / .comm in this case.
375 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
377 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
381 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
385 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
387 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
391 const MCSection *TheSection =
392 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
394 // Handle the zerofill directive on darwin, which is a special form of BSS
396 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
397 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
400 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
401 // .zerofill __DATA, __common, _foo, 400, 5
402 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
406 // Handle thread local data for mach-o which requires us to output an
407 // additional structure of data and mangle the original symbol so that we
408 // can reference it later.
410 // TODO: This should become an "emit thread local global" method on TLOF.
411 // All of this macho specific stuff should be sunk down into TLOFMachO and
412 // stuff like "TLSExtraDataSection" should no longer be part of the parent
413 // TLOF class. This will also make it more obvious that stuff like
414 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
416 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
417 // Emit the .tbss symbol
419 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
421 if (GVKind.isThreadBSS()) {
422 TheSection = getObjFileLowering().getTLSBSSSection();
423 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
424 } else if (GVKind.isThreadData()) {
425 OutStreamer.SwitchSection(TheSection);
427 EmitAlignment(AlignLog, GV);
428 OutStreamer.EmitLabel(MangSym);
430 EmitGlobalConstant(GV->getInitializer());
433 OutStreamer.AddBlankLine();
435 // Emit the variable struct for the runtime.
436 const MCSection *TLVSect
437 = getObjFileLowering().getTLSExtraDataSection();
439 OutStreamer.SwitchSection(TLVSect);
440 // Emit the linkage here.
441 EmitLinkage(GV, GVSym);
442 OutStreamer.EmitLabel(GVSym);
444 // Three pointers in size:
445 // - __tlv_bootstrap - used to make sure support exists
446 // - spare pointer, used when mapped by the runtime
447 // - pointer to mangled symbol above with initializer
448 unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
449 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
451 OutStreamer.EmitIntValue(0, PtrSize);
452 OutStreamer.EmitSymbolValue(MangSym, PtrSize);
454 OutStreamer.AddBlankLine();
458 OutStreamer.SwitchSection(TheSection);
460 EmitLinkage(GV, GVSym);
461 EmitAlignment(AlignLog, GV);
463 OutStreamer.EmitLabel(GVSym);
465 EmitGlobalConstant(GV->getInitializer());
467 if (MAI->hasDotTypeDotSizeDirective())
469 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
471 OutStreamer.AddBlankLine();
474 /// EmitFunctionHeader - This method emits the header for the current
476 void AsmPrinter::EmitFunctionHeader() {
477 // Print out constants referenced by the function
480 // Print the 'header' of function.
481 const Function *F = MF->getFunction();
483 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
484 EmitVisibility(CurrentFnSym, F->getVisibility());
486 EmitLinkage(F, CurrentFnSym);
487 EmitAlignment(MF->getAlignment(), F);
489 if (MAI->hasDotTypeDotSizeDirective())
490 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
493 F->printAsOperand(OutStreamer.GetCommentOS(),
494 /*PrintType=*/false, F->getParent());
495 OutStreamer.GetCommentOS() << '\n';
498 // Emit the CurrentFnSym. This is a virtual function to allow targets to
499 // do their wild and crazy things as required.
500 EmitFunctionEntryLabel();
502 // If the function had address-taken blocks that got deleted, then we have
503 // references to the dangling symbols. Emit them at the start of the function
504 // so that we don't get references to undefined symbols.
505 std::vector<MCSymbol*> DeadBlockSyms;
506 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
507 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
508 OutStreamer.AddComment("Address taken block that was later removed");
509 OutStreamer.EmitLabel(DeadBlockSyms[i]);
512 // Emit pre-function debug and/or EH information.
513 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
514 const HandlerInfo &OI = Handlers[I];
515 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName, TimePassesIsEnabled);
516 OI.Handler->beginFunction(MF);
519 // Emit the prefix data.
520 if (F->hasPrefixData())
521 EmitGlobalConstant(F->getPrefixData());
524 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
525 /// function. This can be overridden by targets as required to do custom stuff.
526 void AsmPrinter::EmitFunctionEntryLabel() {
527 // The function label could have already been emitted if two symbols end up
528 // conflicting due to asm renaming. Detect this and emit an error.
529 if (CurrentFnSym->isUndefined())
530 return OutStreamer.EmitLabel(CurrentFnSym);
532 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
533 "' label emitted multiple times to assembly file");
536 /// emitComments - Pretty-print comments for instructions.
537 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
538 const MachineFunction *MF = MI.getParent()->getParent();
539 const TargetMachine &TM = MF->getTarget();
541 // Check for spills and reloads
544 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
546 // We assume a single instruction only has a spill or reload, not
548 const MachineMemOperand *MMO;
549 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
550 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
551 MMO = *MI.memoperands_begin();
552 CommentOS << MMO->getSize() << "-byte Reload\n";
554 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
555 if (FrameInfo->isSpillSlotObjectIndex(FI))
556 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
557 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
558 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
559 MMO = *MI.memoperands_begin();
560 CommentOS << MMO->getSize() << "-byte Spill\n";
562 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
563 if (FrameInfo->isSpillSlotObjectIndex(FI))
564 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
567 // Check for spill-induced copies
568 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
569 CommentOS << " Reload Reuse\n";
572 /// emitImplicitDef - This method emits the specified machine instruction
573 /// that is an implicit def.
574 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
575 unsigned RegNo = MI->getOperand(0).getReg();
576 OutStreamer.AddComment(Twine("implicit-def: ") +
577 TM.getRegisterInfo()->getName(RegNo));
578 OutStreamer.AddBlankLine();
581 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
582 std::string Str = "kill:";
583 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
584 const MachineOperand &Op = MI->getOperand(i);
585 assert(Op.isReg() && "KILL instruction must have only register operands");
587 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
588 Str += (Op.isDef() ? "<def>" : "<kill>");
590 AP.OutStreamer.AddComment(Str);
591 AP.OutStreamer.AddBlankLine();
594 /// emitDebugValueComment - This method handles the target-independent form
595 /// of DBG_VALUE, returning true if it was able to do so. A false return
596 /// means the target will need to handle MI in EmitInstruction.
597 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
598 // This code handles only the 3-operand target-independent form.
599 if (MI->getNumOperands() != 3)
602 SmallString<128> Str;
603 raw_svector_ostream OS(Str);
604 OS << "DEBUG_VALUE: ";
606 DIVariable V(MI->getOperand(2).getMetadata());
607 if (V.getContext().isSubprogram()) {
608 StringRef Name = DISubprogram(V.getContext()).getDisplayName();
612 OS << V.getName() << " <- ";
614 // The second operand is only an offset if it's an immediate.
615 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
616 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
618 // Register or immediate value. Register 0 means undef.
619 if (MI->getOperand(0).isFPImm()) {
620 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
621 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
622 OS << (double)APF.convertToFloat();
623 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
624 OS << APF.convertToDouble();
626 // There is no good way to print long double. Convert a copy to
627 // double. Ah well, it's only a comment.
629 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
631 OS << "(long double) " << APF.convertToDouble();
633 } else if (MI->getOperand(0).isImm()) {
634 OS << MI->getOperand(0).getImm();
635 } else if (MI->getOperand(0).isCImm()) {
636 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
639 if (MI->getOperand(0).isReg()) {
640 Reg = MI->getOperand(0).getReg();
642 assert(MI->getOperand(0).isFI() && "Unknown operand type");
643 const TargetFrameLowering *TFI = AP.TM.getFrameLowering();
644 Offset += TFI->getFrameIndexReference(*AP.MF,
645 MI->getOperand(0).getIndex(), Reg);
649 // Suppress offset, it is not meaningful here.
651 // NOTE: Want this comment at start of line, don't emit with AddComment.
652 AP.OutStreamer.emitRawComment(OS.str());
657 OS << AP.TM.getRegisterInfo()->getName(Reg);
661 OS << '+' << Offset << ']';
663 // NOTE: Want this comment at start of line, don't emit with AddComment.
664 AP.OutStreamer.emitRawComment(OS.str());
668 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
669 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
670 MF->getFunction()->needsUnwindTableEntry())
673 if (MMI->hasDebugInfo())
679 bool AsmPrinter::needsSEHMoves() {
680 return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
681 MF->getFunction()->needsUnwindTableEntry();
684 void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
685 const MCSymbol *Label = MI.getOperand(0).getMCSymbol();
687 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
690 if (needsCFIMoves() == CFI_M_None)
693 if (MMI->getCompactUnwindEncoding() != 0)
694 OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
696 const MachineModuleInfo &MMI = MF->getMMI();
697 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
698 bool FoundOne = false;
700 for (std::vector<MCCFIInstruction>::const_iterator I = Instrs.begin(),
701 E = Instrs.end(); I != E; ++I) {
702 if (I->getLabel() == Label) {
703 emitCFIInstruction(*I);
710 /// EmitFunctionBody - This method emits the body and trailer for a
712 void AsmPrinter::EmitFunctionBody() {
713 // Emit target-specific gunk before the function body.
714 EmitFunctionBodyStart();
716 bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
718 // Print out code for the function.
719 bool HasAnyRealCode = false;
720 const MachineInstr *LastMI = 0;
721 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
723 // Print a label for the basic block.
724 EmitBasicBlockStart(I);
725 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
729 // Print the assembly for the instruction.
730 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
731 !II->isDebugValue()) {
732 HasAnyRealCode = true;
736 if (ShouldPrintDebugScopes) {
737 for (unsigned III = 0, EEE = Handlers.size(); III != EEE; ++III) {
738 const HandlerInfo &OI = Handlers[III];
739 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
740 TimePassesIsEnabled);
741 OI.Handler->beginInstruction(II);
746 emitComments(*II, OutStreamer.GetCommentOS());
748 switch (II->getOpcode()) {
749 case TargetOpcode::PROLOG_LABEL:
750 emitPrologLabel(*II);
753 case TargetOpcode::EH_LABEL:
754 case TargetOpcode::GC_LABEL:
755 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
757 case TargetOpcode::INLINEASM:
760 case TargetOpcode::DBG_VALUE:
762 if (!emitDebugValueComment(II, *this))
766 case TargetOpcode::IMPLICIT_DEF:
767 if (isVerbose()) emitImplicitDef(II);
769 case TargetOpcode::KILL:
770 if (isVerbose()) emitKill(II, *this);
777 if (ShouldPrintDebugScopes) {
778 for (unsigned III = 0, EEE = Handlers.size(); III != EEE; ++III) {
779 const HandlerInfo &OI = Handlers[III];
780 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
781 TimePassesIsEnabled);
782 OI.Handler->endInstruction();
788 // If the last instruction was a prolog label, then we have a situation where
789 // we emitted a prolog but no function body. This results in the ending prolog
790 // label equaling the end of function label and an invalid "row" in the
791 // FDE. We need to emit a noop in this situation so that the FDE's rows are
793 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
795 // If the function is empty and the object file uses .subsections_via_symbols,
796 // then we need to emit *something* to the function body to prevent the
797 // labels from collapsing together. Just emit a noop.
798 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
800 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
801 if (Noop.getOpcode()) {
802 OutStreamer.AddComment("avoids zero-length function");
803 OutStreamer.EmitInstruction(Noop, getSubtargetInfo());
804 } else // Target not mc-ized yet.
805 OutStreamer.EmitRawText(StringRef("\tnop\n"));
808 const Function *F = MF->getFunction();
809 for (Function::const_iterator i = F->begin(), e = F->end(); i != e; ++i) {
810 const BasicBlock *BB = i;
811 if (!BB->hasAddressTaken())
813 MCSymbol *Sym = GetBlockAddressSymbol(BB);
814 if (Sym->isDefined())
816 OutStreamer.AddComment("Address of block that was removed by CodeGen");
817 OutStreamer.EmitLabel(Sym);
820 // Emit target-specific gunk after the function body.
821 EmitFunctionBodyEnd();
823 // If the target wants a .size directive for the size of the function, emit
825 if (MAI->hasDotTypeDotSizeDirective()) {
826 // Create a symbol for the end of function, so we can get the size as
827 // difference between the function label and the temp label.
828 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
829 OutStreamer.EmitLabel(FnEndLabel);
831 const MCExpr *SizeExp =
832 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
833 MCSymbolRefExpr::Create(CurrentFnSymForSize,
836 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
839 // Emit post-function debug and/or EH information.
840 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
841 const HandlerInfo &OI = Handlers[I];
842 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName, TimePassesIsEnabled);
843 OI.Handler->endFunction(MF);
847 // Print out jump tables referenced by the function.
850 OutStreamer.AddBlankLine();
853 /// EmitDwarfRegOp - Emit dwarf register operation.
854 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc,
855 bool Indirect) const {
856 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
857 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
859 for (MCSuperRegIterator SR(MLoc.getReg(), TRI); SR.isValid() && Reg < 0;
861 Reg = TRI->getDwarfRegNum(*SR, false);
862 // FIXME: Get the bit range this register uses of the superregister
863 // so that we can produce a DW_OP_bit_piece
866 // FIXME: Handle cases like a super register being encoded as
867 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
869 // FIXME: We have no reasonable way of handling errors in here. The
870 // caller might be in the middle of an dwarf expression. We should
871 // probably assert that Reg >= 0 once debug info generation is more mature.
873 if (MLoc.isIndirect() || Indirect) {
875 OutStreamer.AddComment(
876 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
877 EmitInt8(dwarf::DW_OP_breg0 + Reg);
879 OutStreamer.AddComment("DW_OP_bregx");
880 EmitInt8(dwarf::DW_OP_bregx);
881 OutStreamer.AddComment(Twine(Reg));
884 EmitSLEB128(!MLoc.isIndirect() ? 0 : MLoc.getOffset());
885 if (MLoc.isIndirect() && Indirect)
886 EmitInt8(dwarf::DW_OP_deref);
889 OutStreamer.AddComment(
890 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
891 EmitInt8(dwarf::DW_OP_reg0 + Reg);
893 OutStreamer.AddComment("DW_OP_regx");
894 EmitInt8(dwarf::DW_OP_regx);
895 OutStreamer.AddComment(Twine(Reg));
900 // FIXME: Produce a DW_OP_bit_piece if we used a superregister
903 bool AsmPrinter::doFinalization(Module &M) {
904 // Emit global variables.
905 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
907 EmitGlobalVariable(I);
909 // Emit visibility info for declarations
910 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
911 const Function &F = *I;
912 if (!F.isDeclaration())
914 GlobalValue::VisibilityTypes V = F.getVisibility();
915 if (V == GlobalValue::DefaultVisibility)
918 MCSymbol *Name = getSymbol(&F);
919 EmitVisibility(Name, V, false);
922 // Emit module flags.
923 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
924 M.getModuleFlagsMetadata(ModuleFlags);
925 if (!ModuleFlags.empty())
926 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, Mang, TM);
928 // Make sure we wrote out everything we need.
931 // Finalize debug and EH information.
932 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
933 const HandlerInfo &OI = Handlers[I];
934 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
935 TimePassesIsEnabled);
936 OI.Handler->endModule();
942 // If the target wants to know about weak references, print them all.
943 if (MAI->getWeakRefDirective()) {
944 // FIXME: This is not lazy, it would be nice to only print weak references
945 // to stuff that is actually used. Note that doing so would require targets
946 // to notice uses in operands (due to constant exprs etc). This should
947 // happen with the MC stuff eventually.
949 // Print out module-level global variables here.
950 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
952 if (!I->hasExternalWeakLinkage()) continue;
953 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
956 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
957 if (!I->hasExternalWeakLinkage()) continue;
958 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
962 if (MAI->hasSetDirective()) {
963 OutStreamer.AddBlankLine();
964 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
966 MCSymbol *Name = getSymbol(I);
968 const GlobalValue *GV = I->getAliasedGlobal();
969 if (GV->isDeclaration()) {
970 report_fatal_error(Name->getName() +
971 ": Target doesn't support aliases to declarations");
974 MCSymbol *Target = getSymbol(GV);
976 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
977 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
978 else if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
979 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
981 assert(I->hasLocalLinkage() && "Invalid alias linkage");
983 EmitVisibility(Name, I->getVisibility());
985 // Emit the directives as assignments aka .set:
986 OutStreamer.EmitAssignment(Name,
987 MCSymbolRefExpr::Create(Target, OutContext));
991 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
992 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
993 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
994 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
995 MP->finishAssembly(*this);
997 // Emit llvm.ident metadata in an '.ident' directive.
1000 // If we don't have any trampolines, then we don't require stack memory
1001 // to be executable. Some targets have a directive to declare this.
1002 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1003 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1004 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1005 OutStreamer.SwitchSection(S);
1007 // Allow the target to emit any magic that it wants at the end of the file,
1008 // after everything else has gone out.
1009 EmitEndOfAsmFile(M);
1011 delete Mang; Mang = 0;
1014 OutStreamer.Finish();
1015 OutStreamer.reset();
1020 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1022 // Get the function symbol.
1023 CurrentFnSym = getSymbol(MF.getFunction());
1024 CurrentFnSymForSize = CurrentFnSym;
1027 LI = &getAnalysis<MachineLoopInfo>();
1031 // SectionCPs - Keep track the alignment, constpool entries per Section.
1035 SmallVector<unsigned, 4> CPEs;
1036 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1040 /// EmitConstantPool - Print to the current output stream assembly
1041 /// representations of the constants in the constant pool MCP. This is
1042 /// used to print out constants which have been "spilled to memory" by
1043 /// the code generator.
1045 void AsmPrinter::EmitConstantPool() {
1046 const MachineConstantPool *MCP = MF->getConstantPool();
1047 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1048 if (CP.empty()) return;
1050 // Calculate sections for constant pool entries. We collect entries to go into
1051 // the same section together to reduce amount of section switch statements.
1052 SmallVector<SectionCPs, 4> CPSections;
1053 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1054 const MachineConstantPoolEntry &CPE = CP[i];
1055 unsigned Align = CPE.getAlignment();
1058 switch (CPE.getRelocationInfo()) {
1059 default: llvm_unreachable("Unknown section kind");
1060 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
1062 Kind = SectionKind::getReadOnlyWithRelLocal();
1065 switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) {
1066 case 4: Kind = SectionKind::getMergeableConst4(); break;
1067 case 8: Kind = SectionKind::getMergeableConst8(); break;
1068 case 16: Kind = SectionKind::getMergeableConst16();break;
1069 default: Kind = SectionKind::getMergeableConst(); break;
1073 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
1075 // The number of sections are small, just do a linear search from the
1076 // last section to the first.
1078 unsigned SecIdx = CPSections.size();
1079 while (SecIdx != 0) {
1080 if (CPSections[--SecIdx].S == S) {
1086 SecIdx = CPSections.size();
1087 CPSections.push_back(SectionCPs(S, Align));
1090 if (Align > CPSections[SecIdx].Alignment)
1091 CPSections[SecIdx].Alignment = Align;
1092 CPSections[SecIdx].CPEs.push_back(i);
1095 // Now print stuff into the calculated sections.
1096 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1097 OutStreamer.SwitchSection(CPSections[i].S);
1098 EmitAlignment(Log2_32(CPSections[i].Alignment));
1100 unsigned Offset = 0;
1101 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1102 unsigned CPI = CPSections[i].CPEs[j];
1103 MachineConstantPoolEntry CPE = CP[CPI];
1105 // Emit inter-object padding for alignment.
1106 unsigned AlignMask = CPE.getAlignment() - 1;
1107 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1108 OutStreamer.EmitZeros(NewOffset - Offset);
1110 Type *Ty = CPE.getType();
1111 Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
1112 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1114 if (CPE.isMachineConstantPoolEntry())
1115 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1117 EmitGlobalConstant(CPE.Val.ConstVal);
1122 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1123 /// by the current function to the current output stream.
1125 void AsmPrinter::EmitJumpTableInfo() {
1126 const DataLayout *DL = MF->getTarget().getDataLayout();
1127 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1128 if (MJTI == 0) return;
1129 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1130 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1131 if (JT.empty()) return;
1133 // Pick the directive to use to print the jump table entries, and switch to
1134 // the appropriate section.
1135 const Function *F = MF->getFunction();
1136 bool JTInDiffSection = false;
1137 if (// In PIC mode, we need to emit the jump table to the same section as the
1138 // function body itself, otherwise the label differences won't make sense.
1139 // FIXME: Need a better predicate for this: what about custom entries?
1140 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1141 // We should also do if the section name is NULL or function is declared
1142 // in discardable section
1143 // FIXME: this isn't the right predicate, should be based on the MCSection
1144 // for the function.
1145 F->isWeakForLinker()) {
1146 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1148 // Otherwise, drop it in the readonly section.
1149 const MCSection *ReadOnlySection =
1150 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1151 OutStreamer.SwitchSection(ReadOnlySection);
1152 JTInDiffSection = true;
1155 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
1157 // Jump tables in code sections are marked with a data_region directive
1158 // where that's supported.
1159 if (!JTInDiffSection)
1160 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1162 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1163 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1165 // If this jump table was deleted, ignore it.
1166 if (JTBBs.empty()) continue;
1168 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1169 // .set directive for each unique entry. This reduces the number of
1170 // relocations the assembler will generate for the jump table.
1171 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1172 MAI->hasSetDirective()) {
1173 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1174 const TargetLowering *TLI = TM.getTargetLowering();
1175 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1176 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1177 const MachineBasicBlock *MBB = JTBBs[ii];
1178 if (!EmittedSets.insert(MBB)) continue;
1180 // .set LJTSet, LBB32-base
1182 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1183 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1184 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1188 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1189 // before each jump table. The first label is never referenced, but tells
1190 // the assembler and linker the extents of the jump table object. The
1191 // second label is actually referenced by the code.
1192 if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
1193 // FIXME: This doesn't have to have any specific name, just any randomly
1194 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1195 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1197 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1199 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1200 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1202 if (!JTInDiffSection)
1203 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1206 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1208 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1209 const MachineBasicBlock *MBB,
1210 unsigned UID) const {
1211 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1212 const MCExpr *Value = 0;
1213 switch (MJTI->getEntryKind()) {
1214 case MachineJumpTableInfo::EK_Inline:
1215 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1216 case MachineJumpTableInfo::EK_Custom32:
1217 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1220 case MachineJumpTableInfo::EK_BlockAddress:
1221 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1223 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1225 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1226 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1227 // with a relocation as gp-relative, e.g.:
1229 MCSymbol *MBBSym = MBB->getSymbol();
1230 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1234 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1235 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1236 // with a relocation as gp-relative, e.g.:
1238 MCSymbol *MBBSym = MBB->getSymbol();
1239 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1243 case MachineJumpTableInfo::EK_LabelDifference32: {
1244 // EK_LabelDifference32 - Each entry is the address of the block minus
1245 // the address of the jump table. This is used for PIC jump tables where
1246 // gprel32 is not supported. e.g.:
1247 // .word LBB123 - LJTI1_2
1248 // If the .set directive is supported, this is emitted as:
1249 // .set L4_5_set_123, LBB123 - LJTI1_2
1250 // .word L4_5_set_123
1252 // If we have emitted set directives for the jump table entries, print
1253 // them rather than the entries themselves. If we're emitting PIC, then
1254 // emit the table entries as differences between two text section labels.
1255 if (MAI->hasSetDirective()) {
1256 // If we used .set, reference the .set's symbol.
1257 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1261 // Otherwise, use the difference as the jump table entry.
1262 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1263 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1264 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1269 assert(Value && "Unknown entry kind!");
1271 unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
1272 OutStreamer.EmitValue(Value, EntrySize);
1276 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1277 /// special global used by LLVM. If so, emit it and return true, otherwise
1278 /// do nothing and return false.
1279 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1280 if (GV->getName() == "llvm.used") {
1281 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1282 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1286 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1287 if (GV->getSection() == "llvm.metadata" ||
1288 GV->hasAvailableExternallyLinkage())
1291 if (!GV->hasAppendingLinkage()) return false;
1293 assert(GV->hasInitializer() && "Not a special LLVM global!");
1295 if (GV->getName() == "llvm.global_ctors") {
1296 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1298 if (TM.getRelocationModel() == Reloc::Static &&
1299 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1300 StringRef Sym(".constructors_used");
1301 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1307 if (GV->getName() == "llvm.global_dtors") {
1308 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1310 if (TM.getRelocationModel() == Reloc::Static &&
1311 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1312 StringRef Sym(".destructors_used");
1313 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1322 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1323 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1324 /// is true, as being used with this directive.
1325 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1326 // Should be an array of 'i8*'.
1327 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1328 const GlobalValue *GV =
1329 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1330 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1331 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1335 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1337 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1338 // Should be an array of '{ int, void ()* }' structs. The first value is the
1340 if (!isa<ConstantArray>(List)) return;
1342 // Sanity check the structors list.
1343 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1344 if (!InitList) return; // Not an array!
1345 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1346 if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1347 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1348 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1350 // Gather the structors in a form that's convenient for sorting by priority.
1351 typedef std::pair<unsigned, Constant *> Structor;
1352 SmallVector<Structor, 8> Structors;
1353 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1354 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1355 if (!CS) continue; // Malformed.
1356 if (CS->getOperand(1)->isNullValue())
1357 break; // Found a null terminator, skip the rest.
1358 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1359 if (!Priority) continue; // Malformed.
1360 Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1361 CS->getOperand(1)));
1364 // Emit the function pointers in the target-specific order
1365 const DataLayout *DL = TM.getDataLayout();
1366 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1367 std::stable_sort(Structors.begin(), Structors.end(), less_first());
1368 for (unsigned i = 0, e = Structors.size(); i != e; ++i) {
1369 const MCSection *OutputSection =
1371 getObjFileLowering().getStaticCtorSection(Structors[i].first) :
1372 getObjFileLowering().getStaticDtorSection(Structors[i].first));
1373 OutStreamer.SwitchSection(OutputSection);
1374 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1375 EmitAlignment(Align);
1376 EmitXXStructor(Structors[i].second);
1380 void AsmPrinter::EmitModuleIdents(Module &M) {
1381 if (!MAI->hasIdentDirective())
1384 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1385 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1386 const MDNode *N = NMD->getOperand(i);
1387 assert(N->getNumOperands() == 1 &&
1388 "llvm.ident metadata entry can have only one operand");
1389 const MDString *S = cast<MDString>(N->getOperand(0));
1390 OutStreamer.EmitIdent(S->getString());
1395 //===--------------------------------------------------------------------===//
1396 // Emission and print routines
1399 /// EmitInt8 - Emit a byte directive and value.
1401 void AsmPrinter::EmitInt8(int Value) const {
1402 OutStreamer.EmitIntValue(Value, 1);
1405 /// EmitInt16 - Emit a short directive and value.
1407 void AsmPrinter::EmitInt16(int Value) const {
1408 OutStreamer.EmitIntValue(Value, 2);
1411 /// EmitInt32 - Emit a long directive and value.
1413 void AsmPrinter::EmitInt32(int Value) const {
1414 OutStreamer.EmitIntValue(Value, 4);
1417 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1418 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1419 /// labels. This implicitly uses .set if it is available.
1420 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1421 unsigned Size) const {
1422 // Get the Hi-Lo expression.
1423 const MCExpr *Diff =
1424 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1425 MCSymbolRefExpr::Create(Lo, OutContext),
1428 if (!MAI->hasSetDirective()) {
1429 OutStreamer.EmitValue(Diff, Size);
1433 // Otherwise, emit with .set (aka assignment).
1434 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1435 OutStreamer.EmitAssignment(SetLabel, Diff);
1436 OutStreamer.EmitSymbolValue(SetLabel, Size);
1439 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1440 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1441 /// specify the labels. This implicitly uses .set if it is available.
1442 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1444 unsigned Size) const {
1446 // Emit Hi+Offset - Lo
1447 // Get the Hi+Offset expression.
1448 const MCExpr *Plus =
1449 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1450 MCConstantExpr::Create(Offset, OutContext),
1453 // Get the Hi+Offset-Lo expression.
1454 const MCExpr *Diff =
1455 MCBinaryExpr::CreateSub(Plus,
1456 MCSymbolRefExpr::Create(Lo, OutContext),
1459 if (!MAI->hasSetDirective())
1460 OutStreamer.EmitValue(Diff, Size);
1462 // Otherwise, emit with .set (aka assignment).
1463 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1464 OutStreamer.EmitAssignment(SetLabel, Diff);
1465 OutStreamer.EmitSymbolValue(SetLabel, Size);
1469 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1470 /// where the size in bytes of the directive is specified by Size and Label
1471 /// specifies the label. This implicitly uses .set if it is available.
1472 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1474 bool IsSectionRelative) const {
1475 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1476 OutStreamer.EmitCOFFSecRel32(Label);
1480 // Emit Label+Offset (or just Label if Offset is zero)
1481 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1483 Expr = MCBinaryExpr::CreateAdd(
1484 Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
1486 OutStreamer.EmitValue(Expr, Size);
1489 //===----------------------------------------------------------------------===//
1491 // EmitAlignment - Emit an alignment directive to the specified power of
1492 // two boundary. For example, if you pass in 3 here, you will get an 8
1493 // byte alignment. If a global value is specified, and if that global has
1494 // an explicit alignment requested, it will override the alignment request
1495 // if required for correctness.
1497 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1498 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
1500 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1502 if (getCurrentSection()->getKind().isText())
1503 OutStreamer.EmitCodeAlignment(1 << NumBits);
1505 OutStreamer.EmitValueToAlignment(1 << NumBits);
1508 //===----------------------------------------------------------------------===//
1509 // Constant emission.
1510 //===----------------------------------------------------------------------===//
1512 /// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
1514 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
1515 MCContext &Ctx = AP.OutContext;
1517 if (CV->isNullValue() || isa<UndefValue>(CV))
1518 return MCConstantExpr::Create(0, Ctx);
1520 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1521 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1523 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1524 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
1526 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1527 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1529 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1531 llvm_unreachable("Unknown constant value to lower!");
1534 if (const MCExpr *RelocExpr =
1535 AP.getObjFileLowering().getExecutableRelativeSymbol(CE, AP.Mang))
1538 switch (CE->getOpcode()) {
1540 // If the code isn't optimized, there may be outstanding folding
1541 // opportunities. Attempt to fold the expression using DataLayout as a
1542 // last resort before giving up.
1544 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
1546 return lowerConstant(C, AP);
1548 // Otherwise report the problem to the user.
1551 raw_string_ostream OS(S);
1552 OS << "Unsupported expression in static initializer: ";
1553 CE->printAsOperand(OS, /*PrintType=*/false,
1554 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1555 report_fatal_error(OS.str());
1557 case Instruction::GetElementPtr: {
1558 const DataLayout &DL = *AP.TM.getDataLayout();
1559 // Generate a symbolic expression for the byte address
1560 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1561 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1563 const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
1567 int64_t Offset = OffsetAI.getSExtValue();
1568 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1572 case Instruction::Trunc:
1573 // We emit the value and depend on the assembler to truncate the generated
1574 // expression properly. This is important for differences between
1575 // blockaddress labels. Since the two labels are in the same function, it
1576 // is reasonable to treat their delta as a 32-bit value.
1578 case Instruction::BitCast:
1579 return lowerConstant(CE->getOperand(0), AP);
1581 case Instruction::IntToPtr: {
1582 const DataLayout &DL = *AP.TM.getDataLayout();
1583 // Handle casts to pointers by changing them into casts to the appropriate
1584 // integer type. This promotes constant folding and simplifies this code.
1585 Constant *Op = CE->getOperand(0);
1586 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1588 return lowerConstant(Op, AP);
1591 case Instruction::PtrToInt: {
1592 const DataLayout &DL = *AP.TM.getDataLayout();
1593 // Support only foldable casts to/from pointers that can be eliminated by
1594 // changing the pointer to the appropriately sized integer type.
1595 Constant *Op = CE->getOperand(0);
1596 Type *Ty = CE->getType();
1598 const MCExpr *OpExpr = lowerConstant(Op, AP);
1600 // We can emit the pointer value into this slot if the slot is an
1601 // integer slot equal to the size of the pointer.
1602 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1605 // Otherwise the pointer is smaller than the resultant integer, mask off
1606 // the high bits so we are sure to get a proper truncation if the input is
1608 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1609 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1610 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1613 // The MC library also has a right-shift operator, but it isn't consistently
1614 // signed or unsigned between different targets.
1615 case Instruction::Add:
1616 case Instruction::Sub:
1617 case Instruction::Mul:
1618 case Instruction::SDiv:
1619 case Instruction::SRem:
1620 case Instruction::Shl:
1621 case Instruction::And:
1622 case Instruction::Or:
1623 case Instruction::Xor: {
1624 const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1625 const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
1626 switch (CE->getOpcode()) {
1627 default: llvm_unreachable("Unknown binary operator constant cast expr");
1628 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1629 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1630 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1631 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1632 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1633 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1634 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1635 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1636 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1642 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
1644 /// isRepeatedByteSequence - Determine whether the given value is
1645 /// composed of a repeated sequence of identical bytes and return the
1646 /// byte value. If it is not a repeated sequence, return -1.
1647 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1648 StringRef Data = V->getRawDataValues();
1649 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1651 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1652 if (Data[i] != C) return -1;
1653 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1657 /// isRepeatedByteSequence - Determine whether the given value is
1658 /// composed of a repeated sequence of identical bytes and return the
1659 /// byte value. If it is not a repeated sequence, return -1.
1660 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1662 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1663 if (CI->getBitWidth() > 64) return -1;
1665 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
1666 uint64_t Value = CI->getZExtValue();
1668 // Make sure the constant is at least 8 bits long and has a power
1669 // of 2 bit width. This guarantees the constant bit width is
1670 // always a multiple of 8 bits, avoiding issues with padding out
1671 // to Size and other such corner cases.
1672 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1674 uint8_t Byte = static_cast<uint8_t>(Value);
1676 for (unsigned i = 1; i < Size; ++i) {
1678 if (static_cast<uint8_t>(Value) != Byte) return -1;
1682 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1683 // Make sure all array elements are sequences of the same repeated
1685 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1686 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1687 if (Byte == -1) return -1;
1689 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1690 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1691 if (ThisByte == -1) return -1;
1692 if (Byte != ThisByte) return -1;
1697 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1698 return isRepeatedByteSequence(CDS);
1703 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1706 // See if we can aggregate this into a .fill, if so, emit it as such.
1707 int Value = isRepeatedByteSequence(CDS, AP.TM);
1709 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
1710 // Don't emit a 1-byte object as a .fill.
1712 return AP.OutStreamer.EmitFill(Bytes, Value);
1715 // If this can be emitted with .ascii/.asciz, emit it as such.
1716 if (CDS->isString())
1717 return AP.OutStreamer.EmitBytes(CDS->getAsString());
1719 // Otherwise, emit the values in successive locations.
1720 unsigned ElementByteSize = CDS->getElementByteSize();
1721 if (isa<IntegerType>(CDS->getElementType())) {
1722 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1724 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1725 CDS->getElementAsInteger(i));
1726 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1729 } else if (ElementByteSize == 4) {
1730 // FP Constants are printed as integer constants to avoid losing
1732 assert(CDS->getElementType()->isFloatTy());
1733 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1739 F = CDS->getElementAsFloat(i);
1741 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1742 AP.OutStreamer.EmitIntValue(I, 4);
1745 assert(CDS->getElementType()->isDoubleTy());
1746 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1752 F = CDS->getElementAsDouble(i);
1754 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1755 AP.OutStreamer.EmitIntValue(I, 8);
1759 const DataLayout &DL = *AP.TM.getDataLayout();
1760 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1761 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1762 CDS->getNumElements();
1763 if (unsigned Padding = Size - EmittedSize)
1764 AP.OutStreamer.EmitZeros(Padding);
1768 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
1769 // See if we can aggregate some values. Make sure it can be
1770 // represented as a series of bytes of the constant value.
1771 int Value = isRepeatedByteSequence(CA, AP.TM);
1774 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
1775 AP.OutStreamer.EmitFill(Bytes, Value);
1778 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1779 emitGlobalConstantImpl(CA->getOperand(i), AP);
1783 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1784 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1785 emitGlobalConstantImpl(CV->getOperand(i), AP);
1787 const DataLayout &DL = *AP.TM.getDataLayout();
1788 unsigned Size = DL.getTypeAllocSize(CV->getType());
1789 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1790 CV->getType()->getNumElements();
1791 if (unsigned Padding = Size - EmittedSize)
1792 AP.OutStreamer.EmitZeros(Padding);
1795 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
1796 // Print the fields in successive locations. Pad to align if needed!
1797 const DataLayout *DL = AP.TM.getDataLayout();
1798 unsigned Size = DL->getTypeAllocSize(CS->getType());
1799 const StructLayout *Layout = DL->getStructLayout(CS->getType());
1800 uint64_t SizeSoFar = 0;
1801 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1802 const Constant *Field = CS->getOperand(i);
1804 // Check if padding is needed and insert one or more 0s.
1805 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1806 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1807 - Layout->getElementOffset(i)) - FieldSize;
1808 SizeSoFar += FieldSize + PadSize;
1810 // Now print the actual field value.
1811 emitGlobalConstantImpl(Field, AP);
1813 // Insert padding - this may include padding to increase the size of the
1814 // current field up to the ABI size (if the struct is not packed) as well
1815 // as padding to ensure that the next field starts at the right offset.
1816 AP.OutStreamer.EmitZeros(PadSize);
1818 assert(SizeSoFar == Layout->getSizeInBytes() &&
1819 "Layout of constant struct may be incorrect!");
1822 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1823 APInt API = CFP->getValueAPF().bitcastToAPInt();
1825 // First print a comment with what we think the original floating-point value
1826 // should have been.
1827 if (AP.isVerbose()) {
1828 SmallString<8> StrVal;
1829 CFP->getValueAPF().toString(StrVal);
1831 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1832 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1835 // Now iterate through the APInt chunks, emitting them in endian-correct
1836 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1838 unsigned NumBytes = API.getBitWidth() / 8;
1839 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1840 const uint64_t *p = API.getRawData();
1842 // PPC's long double has odd notions of endianness compared to how LLVM
1843 // handles it: p[0] goes first for *big* endian on PPC.
1844 if (AP.TM.getDataLayout()->isBigEndian() != CFP->getType()->isPPC_FP128Ty()) {
1845 int Chunk = API.getNumWords() - 1;
1848 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1850 for (; Chunk >= 0; --Chunk)
1851 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1854 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1855 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1858 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
1861 // Emit the tail padding for the long double.
1862 const DataLayout &DL = *AP.TM.getDataLayout();
1863 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1864 DL.getTypeStoreSize(CFP->getType()));
1867 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
1868 const DataLayout *DL = AP.TM.getDataLayout();
1869 unsigned BitWidth = CI->getBitWidth();
1871 // Copy the value as we may massage the layout for constants whose bit width
1872 // is not a multiple of 64-bits.
1873 APInt Realigned(CI->getValue());
1874 uint64_t ExtraBits = 0;
1875 unsigned ExtraBitsSize = BitWidth & 63;
1877 if (ExtraBitsSize) {
1878 // The bit width of the data is not a multiple of 64-bits.
1879 // The extra bits are expected to be at the end of the chunk of the memory.
1881 // * Nothing to be done, just record the extra bits to emit.
1883 // * Record the extra bits to emit.
1884 // * Realign the raw data to emit the chunks of 64-bits.
1885 if (DL->isBigEndian()) {
1886 // Basically the structure of the raw data is a chunk of 64-bits cells:
1887 // 0 1 BitWidth / 64
1888 // [chunk1][chunk2] ... [chunkN].
1889 // The most significant chunk is chunkN and it should be emitted first.
1890 // However, due to the alignment issue chunkN contains useless bits.
1891 // Realign the chunks so that they contain only useless information:
1892 // ExtraBits 0 1 (BitWidth / 64) - 1
1893 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
1894 ExtraBits = Realigned.getRawData()[0] &
1895 (((uint64_t)-1) >> (64 - ExtraBitsSize));
1896 Realigned = Realigned.lshr(ExtraBitsSize);
1898 ExtraBits = Realigned.getRawData()[BitWidth / 64];
1901 // We don't expect assemblers to support integer data directives
1902 // for more than 64 bits, so we emit the data in at most 64-bit
1903 // quantities at a time.
1904 const uint64_t *RawData = Realigned.getRawData();
1905 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1906 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1907 AP.OutStreamer.EmitIntValue(Val, 8);
1910 if (ExtraBitsSize) {
1911 // Emit the extra bits after the 64-bits chunks.
1913 // Emit a directive that fills the expected size.
1914 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(CI->getType());
1915 Size -= (BitWidth / 64) * 8;
1916 assert(Size && Size * 8 >= ExtraBitsSize &&
1917 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
1918 == ExtraBits && "Directive too small for extra bits.");
1919 AP.OutStreamer.EmitIntValue(ExtraBits, Size);
1923 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
1924 const DataLayout *DL = AP.TM.getDataLayout();
1925 uint64_t Size = DL->getTypeAllocSize(CV->getType());
1926 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
1927 return AP.OutStreamer.EmitZeros(Size);
1929 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1936 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1937 CI->getZExtValue());
1938 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
1941 emitGlobalConstantLargeInt(CI, AP);
1946 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1947 return emitGlobalConstantFP(CFP, AP);
1949 if (isa<ConstantPointerNull>(CV)) {
1950 AP.OutStreamer.EmitIntValue(0, Size);
1954 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
1955 return emitGlobalConstantDataSequential(CDS, AP);
1957 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1958 return emitGlobalConstantArray(CVA, AP);
1960 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1961 return emitGlobalConstantStruct(CVS, AP);
1963 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1964 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
1966 if (CE->getOpcode() == Instruction::BitCast)
1967 return emitGlobalConstantImpl(CE->getOperand(0), AP);
1970 // If the constant expression's size is greater than 64-bits, then we have
1971 // to emit the value in chunks. Try to constant fold the value and emit it
1973 Constant *New = ConstantFoldConstantExpression(CE, DL);
1974 if (New && New != CE)
1975 return emitGlobalConstantImpl(New, AP);
1979 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1980 return emitGlobalConstantVector(V, AP);
1982 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1983 // thread the streamer with EmitValue.
1984 AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
1987 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1988 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
1989 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
1991 emitGlobalConstantImpl(CV, *this);
1992 else if (MAI->hasSubsectionsViaSymbols()) {
1993 // If the global has zero size, emit a single byte so that two labels don't
1994 // look like they are at the same location.
1995 OutStreamer.EmitIntValue(0, 1);
1999 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2000 // Target doesn't support this yet!
2001 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2004 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2006 OS << '+' << Offset;
2007 else if (Offset < 0)
2011 //===----------------------------------------------------------------------===//
2012 // Symbol Lowering Routines.
2013 //===----------------------------------------------------------------------===//
2015 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
2016 /// temporary label with the specified stem and unique ID.
2017 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
2018 const DataLayout *DL = TM.getDataLayout();
2019 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix()) +
2023 /// GetTempSymbol - Return an assembler temporary label with the specified
2025 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
2026 const DataLayout *DL = TM.getDataLayout();
2027 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
2032 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2033 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2036 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2037 return MMI->getAddrLabelSymbol(BB);
2040 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2041 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2042 const DataLayout *DL = TM.getDataLayout();
2043 return OutContext.GetOrCreateSymbol
2044 (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2045 + "_" + Twine(CPID));
2048 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2049 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2050 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2053 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2054 /// FIXME: privatize to AsmPrinter.
2055 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2056 const DataLayout *DL = TM.getDataLayout();
2057 return OutContext.GetOrCreateSymbol
2058 (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2059 Twine(UID) + "_set_" + Twine(MBBID));
2062 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2063 StringRef Suffix) const {
2064 return getObjFileLowering().getSymbolWithGlobalValueBase(*Mang, GV, Suffix);
2067 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2069 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2070 SmallString<60> NameStr;
2071 Mang->getNameWithPrefix(NameStr, Sym);
2072 return OutContext.GetOrCreateSymbol(NameStr.str());
2077 /// PrintParentLoopComment - Print comments about parent loops of this one.
2078 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2079 unsigned FunctionNumber) {
2080 if (Loop == 0) return;
2081 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2082 OS.indent(Loop->getLoopDepth()*2)
2083 << "Parent Loop BB" << FunctionNumber << "_"
2084 << Loop->getHeader()->getNumber()
2085 << " Depth=" << Loop->getLoopDepth() << '\n';
2089 /// PrintChildLoopComment - Print comments about child loops within
2090 /// the loop for this basic block, with nesting.
2091 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2092 unsigned FunctionNumber) {
2093 // Add child loop information
2094 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
2095 OS.indent((*CL)->getLoopDepth()*2)
2096 << "Child Loop BB" << FunctionNumber << "_"
2097 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
2099 PrintChildLoopComment(OS, *CL, FunctionNumber);
2103 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2104 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2105 const MachineLoopInfo *LI,
2106 const AsmPrinter &AP) {
2107 // Add loop depth information
2108 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2109 if (Loop == 0) return;
2111 MachineBasicBlock *Header = Loop->getHeader();
2112 assert(Header && "No header for loop");
2114 // If this block is not a loop header, just print out what is the loop header
2116 if (Header != &MBB) {
2117 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2118 Twine(AP.getFunctionNumber())+"_" +
2119 Twine(Loop->getHeader()->getNumber())+
2120 " Depth="+Twine(Loop->getLoopDepth()));
2124 // Otherwise, it is a loop header. Print out information about child and
2126 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2128 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2131 OS.indent(Loop->getLoopDepth()*2-2);
2136 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2138 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2142 /// EmitBasicBlockStart - This method prints the label for the specified
2143 /// MachineBasicBlock, an alignment (if present) and a comment describing
2144 /// it if appropriate.
2145 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
2146 // Emit an alignment directive for this block, if needed.
2147 if (unsigned Align = MBB->getAlignment())
2148 EmitAlignment(Align);
2150 // If the block has its address taken, emit any labels that were used to
2151 // reference the block. It is possible that there is more than one label
2152 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2153 // the references were generated.
2154 if (MBB->hasAddressTaken()) {
2155 const BasicBlock *BB = MBB->getBasicBlock();
2157 OutStreamer.AddComment("Block address taken");
2159 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
2161 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
2162 OutStreamer.EmitLabel(Syms[i]);
2165 // Print some verbose block comments.
2167 if (const BasicBlock *BB = MBB->getBasicBlock())
2169 OutStreamer.AddComment("%" + BB->getName());
2170 emitBasicBlockLoopComments(*MBB, LI, *this);
2173 // Print the main label for the block.
2174 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
2176 // NOTE: Want this comment at start of line, don't emit with AddComment.
2177 OutStreamer.emitRawComment(" BB#" + Twine(MBB->getNumber()) + ":", false);
2180 OutStreamer.EmitLabel(MBB->getSymbol());
2184 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2185 bool IsDefinition) const {
2186 MCSymbolAttr Attr = MCSA_Invalid;
2188 switch (Visibility) {
2190 case GlobalValue::HiddenVisibility:
2192 Attr = MAI->getHiddenVisibilityAttr();
2194 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2196 case GlobalValue::ProtectedVisibility:
2197 Attr = MAI->getProtectedVisibilityAttr();
2201 if (Attr != MCSA_Invalid)
2202 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2205 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2206 /// exactly one predecessor and the control transfer mechanism between
2207 /// the predecessor and this block is a fall-through.
2209 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2210 // If this is a landing pad, it isn't a fall through. If it has no preds,
2211 // then nothing falls through to it.
2212 if (MBB->isLandingPad() || MBB->pred_empty())
2215 // If there isn't exactly one predecessor, it can't be a fall through.
2216 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2218 if (PI2 != MBB->pred_end())
2221 // The predecessor has to be immediately before this block.
2222 MachineBasicBlock *Pred = *PI;
2224 if (!Pred->isLayoutSuccessor(MBB))
2227 // If the block is completely empty, then it definitely does fall through.
2231 // Check the terminators in the previous blocks
2232 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2233 IE = Pred->end(); II != IE; ++II) {
2234 MachineInstr &MI = *II;
2236 // If it is not a simple branch, we are in a table somewhere.
2237 if (!MI.isBranch() || MI.isIndirectBranch())
2240 // If we are the operands of one of the branches, this is not a fall
2241 // through. Note that targets with delay slots will usually bundle
2242 // terminators with the delay slot instruction.
2243 for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2246 if (OP->isMBB() && OP->getMBB() == MBB)
2256 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2257 if (!S->usesMetadata())
2260 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2261 gcp_map_type::iterator GCPI = GCMap.find(S);
2262 if (GCPI != GCMap.end())
2263 return GCPI->second;
2265 const char *Name = S->getName().c_str();
2267 for (GCMetadataPrinterRegistry::iterator
2268 I = GCMetadataPrinterRegistry::begin(),
2269 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2270 if (strcmp(Name, I->getName()) == 0) {
2271 GCMetadataPrinter *GMP = I->instantiate();
2273 GCMap.insert(std::make_pair(S, GMP));
2277 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2280 /// Pin vtable to this file.
2281 AsmPrinterHandler::~AsmPrinterHandler() {}