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/MachineJumpTableInfo.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/DebugInfo.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Mangler.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/IR/Writer.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/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; MMI = 0; LI = 0; MF = 0;
103 CurrentFnSym = CurrentFnSymForSize = 0;
104 GCMetadataPrinters = 0;
105 VerboseAsm = Streamer.isVerboseAsm();
108 AsmPrinter::~AsmPrinter() {
109 assert(DD == 0 && Handlers.empty() && "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.getDataLayout());
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);
197 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
200 DwarfException *DE = 0;
201 switch (MAI->getExceptionHandlingType()) {
202 case ExceptionHandling::None:
204 case ExceptionHandling::SjLj:
205 case ExceptionHandling::DwarfCFI:
206 DE = new DwarfCFIException(this);
208 case ExceptionHandling::ARM:
209 DE = new ARMException(this);
211 case ExceptionHandling::Win64:
212 DE = new Win64Exception(this);
216 Handlers.push_back(HandlerInfo(DE, EHTimerName, DWARFGroupName));
220 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
221 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
223 case GlobalValue::CommonLinkage:
224 case GlobalValue::LinkOnceAnyLinkage:
225 case GlobalValue::LinkOnceODRLinkage:
226 case GlobalValue::WeakAnyLinkage:
227 case GlobalValue::WeakODRLinkage:
228 case GlobalValue::LinkerPrivateWeakLinkage:
229 if (MAI->hasWeakDefDirective()) {
231 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
233 bool CanBeHidden = false;
235 if (Linkage == GlobalValue::LinkOnceODRLinkage &&
236 MAI->hasWeakDefCanBeHiddenDirective()) {
237 if (GV->hasUnnamedAddr()) {
241 if (!GlobalStatus::analyzeGlobal(GV, GS) && !GS.IsCompared)
247 // .weak_definition _foo
248 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
250 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
251 } else if (MAI->hasLinkOnceDirective()) {
253 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
254 //NOTE: linkonce is handled by the section the symbol was assigned to.
257 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
260 case GlobalValue::DLLExportLinkage:
261 case GlobalValue::AppendingLinkage:
262 // FIXME: appending linkage variables should go into a section of
263 // their name or something. For now, just emit them as external.
264 case GlobalValue::ExternalLinkage:
265 // If external or appending, declare as a global symbol.
267 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
269 case GlobalValue::PrivateLinkage:
270 case GlobalValue::InternalLinkage:
271 case GlobalValue::LinkerPrivateLinkage:
273 case GlobalValue::AvailableExternallyLinkage:
274 llvm_unreachable("Should never emit this");
275 case GlobalValue::DLLImportLinkage:
276 case GlobalValue::ExternalWeakLinkage:
277 llvm_unreachable("Don't know how to emit these");
279 llvm_unreachable("Unknown linkage type!");
282 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
283 return getObjFileLowering().getSymbol(*Mang, GV);
286 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
287 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
288 if (GV->hasInitializer()) {
289 // Check to see if this is a special global used by LLVM, if so, emit it.
290 if (EmitSpecialLLVMGlobal(GV))
294 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
295 /*PrintType=*/false, GV->getParent());
296 OutStreamer.GetCommentOS() << '\n';
300 MCSymbol *GVSym = getSymbol(GV);
301 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
303 if (!GV->hasInitializer()) // External globals require no extra code.
306 if (MAI->hasDotTypeDotSizeDirective())
307 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
309 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
311 const DataLayout *DL = TM.getDataLayout();
312 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
314 // If the alignment is specified, we *must* obey it. Overaligning a global
315 // with a specified alignment is a prompt way to break globals emitted to
316 // sections and expected to be contiguous (e.g. ObjC metadata).
317 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
319 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
320 const HandlerInfo &OI = Handlers[I];
321 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName, TimePassesIsEnabled);
322 OI.Handler->setSymbolSize(GVSym, Size);
325 // Handle common and BSS local symbols (.lcomm).
326 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
327 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
328 unsigned Align = 1 << AlignLog;
330 // Handle common symbols.
331 if (GVKind.isCommon()) {
332 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
336 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
340 // Handle local BSS symbols.
341 if (MAI->hasMachoZeroFillDirective()) {
342 const MCSection *TheSection =
343 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
344 // .zerofill __DATA, __bss, _foo, 400, 5
345 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
349 // Use .lcomm only if it supports user-specified alignment.
350 // Otherwise, while it would still be correct to use .lcomm in some
351 // cases (e.g. when Align == 1), the external assembler might enfore
352 // some -unknown- default alignment behavior, which could cause
353 // spurious differences between external and integrated assembler.
354 // Prefer to simply fall back to .local / .comm in this case.
355 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
357 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
361 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
365 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
367 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
371 const MCSection *TheSection =
372 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
374 // Handle the zerofill directive on darwin, which is a special form of BSS
376 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
377 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
380 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
381 // .zerofill __DATA, __common, _foo, 400, 5
382 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
386 // Handle thread local data for mach-o which requires us to output an
387 // additional structure of data and mangle the original symbol so that we
388 // can reference it later.
390 // TODO: This should become an "emit thread local global" method on TLOF.
391 // All of this macho specific stuff should be sunk down into TLOFMachO and
392 // stuff like "TLSExtraDataSection" should no longer be part of the parent
393 // TLOF class. This will also make it more obvious that stuff like
394 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
396 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
397 // Emit the .tbss symbol
399 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
401 if (GVKind.isThreadBSS()) {
402 TheSection = getObjFileLowering().getTLSBSSSection();
403 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
404 } else if (GVKind.isThreadData()) {
405 OutStreamer.SwitchSection(TheSection);
407 EmitAlignment(AlignLog, GV);
408 OutStreamer.EmitLabel(MangSym);
410 EmitGlobalConstant(GV->getInitializer());
413 OutStreamer.AddBlankLine();
415 // Emit the variable struct for the runtime.
416 const MCSection *TLVSect
417 = getObjFileLowering().getTLSExtraDataSection();
419 OutStreamer.SwitchSection(TLVSect);
420 // Emit the linkage here.
421 EmitLinkage(GV, GVSym);
422 OutStreamer.EmitLabel(GVSym);
424 // Three pointers in size:
425 // - __tlv_bootstrap - used to make sure support exists
426 // - spare pointer, used when mapped by the runtime
427 // - pointer to mangled symbol above with initializer
428 unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
429 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
431 OutStreamer.EmitIntValue(0, PtrSize);
432 OutStreamer.EmitSymbolValue(MangSym, PtrSize);
434 OutStreamer.AddBlankLine();
438 OutStreamer.SwitchSection(TheSection);
440 EmitLinkage(GV, GVSym);
441 EmitAlignment(AlignLog, GV);
443 OutStreamer.EmitLabel(GVSym);
445 EmitGlobalConstant(GV->getInitializer());
447 if (MAI->hasDotTypeDotSizeDirective())
449 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
451 OutStreamer.AddBlankLine();
454 /// EmitFunctionHeader - This method emits the header for the current
456 void AsmPrinter::EmitFunctionHeader() {
457 // Print out constants referenced by the function
460 // Print the 'header' of function.
461 const Function *F = MF->getFunction();
463 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
464 EmitVisibility(CurrentFnSym, F->getVisibility());
466 EmitLinkage(F, CurrentFnSym);
467 EmitAlignment(MF->getAlignment(), F);
469 if (MAI->hasDotTypeDotSizeDirective())
470 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
473 WriteAsOperand(OutStreamer.GetCommentOS(), F,
474 /*PrintType=*/false, F->getParent());
475 OutStreamer.GetCommentOS() << '\n';
478 // Emit the CurrentFnSym. This is a virtual function to allow targets to
479 // do their wild and crazy things as required.
480 EmitFunctionEntryLabel();
482 // If the function had address-taken blocks that got deleted, then we have
483 // references to the dangling symbols. Emit them at the start of the function
484 // so that we don't get references to undefined symbols.
485 std::vector<MCSymbol*> DeadBlockSyms;
486 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
487 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
488 OutStreamer.AddComment("Address taken block that was later removed");
489 OutStreamer.EmitLabel(DeadBlockSyms[i]);
492 // Emit pre-function debug and/or EH information.
493 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
494 const HandlerInfo &OI = Handlers[I];
495 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName, TimePassesIsEnabled);
496 OI.Handler->beginFunction(MF);
499 // Emit the prefix data.
500 if (F->hasPrefixData())
501 EmitGlobalConstant(F->getPrefixData());
504 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
505 /// function. This can be overridden by targets as required to do custom stuff.
506 void AsmPrinter::EmitFunctionEntryLabel() {
507 // The function label could have already been emitted if two symbols end up
508 // conflicting due to asm renaming. Detect this and emit an error.
509 if (CurrentFnSym->isUndefined())
510 return OutStreamer.EmitLabel(CurrentFnSym);
512 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
513 "' label emitted multiple times to assembly file");
516 /// emitComments - Pretty-print comments for instructions.
517 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
518 const MachineFunction *MF = MI.getParent()->getParent();
519 const TargetMachine &TM = MF->getTarget();
521 // Check for spills and reloads
524 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
526 // We assume a single instruction only has a spill or reload, not
528 const MachineMemOperand *MMO;
529 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
530 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
531 MMO = *MI.memoperands_begin();
532 CommentOS << MMO->getSize() << "-byte Reload\n";
534 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
535 if (FrameInfo->isSpillSlotObjectIndex(FI))
536 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
537 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
538 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
539 MMO = *MI.memoperands_begin();
540 CommentOS << MMO->getSize() << "-byte Spill\n";
542 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
543 if (FrameInfo->isSpillSlotObjectIndex(FI))
544 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
547 // Check for spill-induced copies
548 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
549 CommentOS << " Reload Reuse\n";
552 /// emitImplicitDef - This method emits the specified machine instruction
553 /// that is an implicit def.
554 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
555 unsigned RegNo = MI->getOperand(0).getReg();
556 OutStreamer.AddComment(Twine("implicit-def: ") +
557 TM.getRegisterInfo()->getName(RegNo));
558 OutStreamer.AddBlankLine();
561 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
562 std::string Str = "kill:";
563 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
564 const MachineOperand &Op = MI->getOperand(i);
565 assert(Op.isReg() && "KILL instruction must have only register operands");
567 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
568 Str += (Op.isDef() ? "<def>" : "<kill>");
570 AP.OutStreamer.AddComment(Str);
571 AP.OutStreamer.AddBlankLine();
574 /// emitDebugValueComment - This method handles the target-independent form
575 /// of DBG_VALUE, returning true if it was able to do so. A false return
576 /// means the target will need to handle MI in EmitInstruction.
577 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
578 // This code handles only the 3-operand target-independent form.
579 if (MI->getNumOperands() != 3)
582 SmallString<128> Str;
583 raw_svector_ostream OS(Str);
584 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
586 DIVariable V(MI->getOperand(2).getMetadata());
587 if (V.getContext().isSubprogram()) {
588 StringRef Name = DISubprogram(V.getContext()).getDisplayName();
592 OS << V.getName() << " <- ";
594 // The second operand is only an offset if it's an immediate.
595 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
596 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
598 // Register or immediate value. Register 0 means undef.
599 if (MI->getOperand(0).isFPImm()) {
600 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
601 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
602 OS << (double)APF.convertToFloat();
603 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
604 OS << APF.convertToDouble();
606 // There is no good way to print long double. Convert a copy to
607 // double. Ah well, it's only a comment.
609 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
611 OS << "(long double) " << APF.convertToDouble();
613 } else if (MI->getOperand(0).isImm()) {
614 OS << MI->getOperand(0).getImm();
615 } else if (MI->getOperand(0).isCImm()) {
616 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
619 if (MI->getOperand(0).isReg()) {
620 Reg = MI->getOperand(0).getReg();
622 assert(MI->getOperand(0).isFI() && "Unknown operand type");
623 const TargetFrameLowering *TFI = AP.TM.getFrameLowering();
624 Offset += TFI->getFrameIndexReference(*AP.MF,
625 MI->getOperand(0).getIndex(), Reg);
629 // Suppress offset, it is not meaningful here.
631 // NOTE: Want this comment at start of line, don't emit with AddComment.
632 AP.OutStreamer.EmitRawText(OS.str());
637 OS << AP.TM.getRegisterInfo()->getName(Reg);
641 OS << '+' << Offset << ']';
643 // NOTE: Want this comment at start of line, don't emit with AddComment.
644 AP.OutStreamer.EmitRawText(OS.str());
648 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
649 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
650 MF->getFunction()->needsUnwindTableEntry())
653 if (MMI->hasDebugInfo())
659 bool AsmPrinter::needsSEHMoves() {
660 return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
661 MF->getFunction()->needsUnwindTableEntry();
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 = 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 for (unsigned III = 0, EEE = Handlers.size(); III != EEE; ++III) {
718 const HandlerInfo &OI = Handlers[III];
719 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
720 TimePassesIsEnabled);
721 OI.Handler->beginInstruction(II);
726 emitComments(*II, OutStreamer.GetCommentOS());
728 switch (II->getOpcode()) {
729 case TargetOpcode::PROLOG_LABEL:
730 emitPrologLabel(*II);
733 case TargetOpcode::EH_LABEL:
734 case TargetOpcode::GC_LABEL:
735 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
737 case TargetOpcode::INLINEASM:
740 case TargetOpcode::DBG_VALUE:
742 if (!emitDebugValueComment(II, *this))
746 case TargetOpcode::IMPLICIT_DEF:
747 if (isVerbose()) emitImplicitDef(II);
749 case TargetOpcode::KILL:
750 if (isVerbose()) emitKill(II, *this);
753 if (!TM.hasMCUseLoc())
754 MCLineEntry::Make(&OutStreamer, getCurrentSection());
760 if (ShouldPrintDebugScopes) {
761 for (unsigned III = 0, EEE = Handlers.size(); III != EEE; ++III) {
762 const HandlerInfo &OI = Handlers[III];
763 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
764 TimePassesIsEnabled);
765 OI.Handler->endInstruction();
771 // If the last instruction was a prolog label, then we have a situation where
772 // we emitted a prolog but no function body. This results in the ending prolog
773 // label equaling the end of function label and an invalid "row" in the
774 // FDE. We need to emit a noop in this situation so that the FDE's rows are
776 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
778 // If the function is empty and the object file uses .subsections_via_symbols,
779 // then we need to emit *something* to the function body to prevent the
780 // labels from collapsing together. Just emit a noop.
781 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
783 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
784 if (Noop.getOpcode()) {
785 OutStreamer.AddComment("avoids zero-length function");
786 OutStreamer.EmitInstruction(Noop);
787 } else // Target not mc-ized yet.
788 OutStreamer.EmitRawText(StringRef("\tnop\n"));
791 const Function *F = MF->getFunction();
792 for (Function::const_iterator i = F->begin(), e = F->end(); i != e; ++i) {
793 const BasicBlock *BB = i;
794 if (!BB->hasAddressTaken())
796 MCSymbol *Sym = GetBlockAddressSymbol(BB);
797 if (Sym->isDefined())
799 OutStreamer.AddComment("Address of block that was removed by CodeGen");
800 OutStreamer.EmitLabel(Sym);
803 // Emit target-specific gunk after the function body.
804 EmitFunctionBodyEnd();
806 // If the target wants a .size directive for the size of the function, emit
808 if (MAI->hasDotTypeDotSizeDirective()) {
809 // Create a symbol for the end of function, so we can get the size as
810 // difference between the function label and the temp label.
811 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
812 OutStreamer.EmitLabel(FnEndLabel);
814 const MCExpr *SizeExp =
815 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
816 MCSymbolRefExpr::Create(CurrentFnSymForSize,
819 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
822 // Emit post-function debug and/or EH information.
823 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
824 const HandlerInfo &OI = Handlers[I];
825 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName, TimePassesIsEnabled);
826 OI.Handler->endFunction(MF);
830 // Print out jump tables referenced by the function.
833 OutStreamer.AddBlankLine();
836 /// EmitDwarfRegOp - Emit dwarf register operation.
837 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc,
838 bool Indirect) const {
839 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
840 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
842 for (MCSuperRegIterator SR(MLoc.getReg(), TRI); SR.isValid() && Reg < 0;
844 Reg = TRI->getDwarfRegNum(*SR, false);
845 // FIXME: Get the bit range this register uses of the superregister
846 // so that we can produce a DW_OP_bit_piece
849 // FIXME: Handle cases like a super register being encoded as
850 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
852 // FIXME: We have no reasonable way of handling errors in here. The
853 // caller might be in the middle of an dwarf expression. We should
854 // probably assert that Reg >= 0 once debug info generation is more mature.
856 if (MLoc.isIndirect() || Indirect) {
858 OutStreamer.AddComment(
859 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
860 EmitInt8(dwarf::DW_OP_breg0 + Reg);
862 OutStreamer.AddComment("DW_OP_bregx");
863 EmitInt8(dwarf::DW_OP_bregx);
864 OutStreamer.AddComment(Twine(Reg));
867 EmitSLEB128(!MLoc.isIndirect() ? 0 : MLoc.getOffset());
868 if (MLoc.isIndirect() && Indirect)
869 EmitInt8(dwarf::DW_OP_deref);
872 OutStreamer.AddComment(
873 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
874 EmitInt8(dwarf::DW_OP_reg0 + Reg);
876 OutStreamer.AddComment("DW_OP_regx");
877 EmitInt8(dwarf::DW_OP_regx);
878 OutStreamer.AddComment(Twine(Reg));
883 // FIXME: Produce a DW_OP_bit_piece if we used a superregister
886 bool AsmPrinter::doFinalization(Module &M) {
887 // Emit global variables.
888 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
890 EmitGlobalVariable(I);
892 // Emit visibility info for declarations
893 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
894 const Function &F = *I;
895 if (!F.isDeclaration())
897 GlobalValue::VisibilityTypes V = F.getVisibility();
898 if (V == GlobalValue::DefaultVisibility)
901 MCSymbol *Name = getSymbol(&F);
902 EmitVisibility(Name, V, false);
905 // Emit module flags.
906 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
907 M.getModuleFlagsMetadata(ModuleFlags);
908 if (!ModuleFlags.empty())
909 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, Mang, TM);
911 // Make sure we wrote out everything we need.
914 // Finalize debug and EH information.
915 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
916 const HandlerInfo &OI = Handlers[I];
917 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
918 TimePassesIsEnabled);
919 OI.Handler->endModule();
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 if (GV->isDeclaration()) {
953 report_fatal_error(Name->getName() +
954 ": Target doesn't support aliases to declarations");
957 MCSymbol *Target = getSymbol(GV);
959 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
960 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
961 else if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
962 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
964 assert(I->hasLocalLinkage() && "Invalid alias linkage");
966 EmitVisibility(Name, I->getVisibility());
968 // Emit the directives as assignments aka .set:
969 OutStreamer.EmitAssignment(Name,
970 MCSymbolRefExpr::Create(Target, OutContext));
974 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
975 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
976 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
977 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
978 MP->finishAssembly(*this);
980 // Emit llvm.ident metadata in an '.ident' directive.
983 // If we don't have any trampolines, then we don't require stack memory
984 // to be executable. Some targets have a directive to declare this.
985 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
986 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
987 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
988 OutStreamer.SwitchSection(S);
990 // Allow the target to emit any magic that it wants at the end of the file,
991 // after everything else has gone out.
994 delete Mang; Mang = 0;
997 OutStreamer.Finish();
1003 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1005 // Get the function symbol.
1006 CurrentFnSym = getSymbol(MF.getFunction());
1007 CurrentFnSymForSize = CurrentFnSym;
1010 LI = &getAnalysis<MachineLoopInfo>();
1014 // SectionCPs - Keep track the alignment, constpool entries per Section.
1018 SmallVector<unsigned, 4> CPEs;
1019 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1023 /// EmitConstantPool - Print to the current output stream assembly
1024 /// representations of the constants in the constant pool MCP. This is
1025 /// used to print out constants which have been "spilled to memory" by
1026 /// the code generator.
1028 void AsmPrinter::EmitConstantPool() {
1029 const MachineConstantPool *MCP = MF->getConstantPool();
1030 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1031 if (CP.empty()) return;
1033 // Calculate sections for constant pool entries. We collect entries to go into
1034 // the same section together to reduce amount of section switch statements.
1035 SmallVector<SectionCPs, 4> CPSections;
1036 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1037 const MachineConstantPoolEntry &CPE = CP[i];
1038 unsigned Align = CPE.getAlignment();
1041 switch (CPE.getRelocationInfo()) {
1042 default: llvm_unreachable("Unknown section kind");
1043 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
1045 Kind = SectionKind::getReadOnlyWithRelLocal();
1048 switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) {
1049 case 4: Kind = SectionKind::getMergeableConst4(); break;
1050 case 8: Kind = SectionKind::getMergeableConst8(); break;
1051 case 16: Kind = SectionKind::getMergeableConst16();break;
1052 default: Kind = SectionKind::getMergeableConst(); break;
1056 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
1058 // The number of sections are small, just do a linear search from the
1059 // last section to the first.
1061 unsigned SecIdx = CPSections.size();
1062 while (SecIdx != 0) {
1063 if (CPSections[--SecIdx].S == S) {
1069 SecIdx = CPSections.size();
1070 CPSections.push_back(SectionCPs(S, Align));
1073 if (Align > CPSections[SecIdx].Alignment)
1074 CPSections[SecIdx].Alignment = Align;
1075 CPSections[SecIdx].CPEs.push_back(i);
1078 // Now print stuff into the calculated sections.
1079 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1080 OutStreamer.SwitchSection(CPSections[i].S);
1081 EmitAlignment(Log2_32(CPSections[i].Alignment));
1083 unsigned Offset = 0;
1084 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1085 unsigned CPI = CPSections[i].CPEs[j];
1086 MachineConstantPoolEntry CPE = CP[CPI];
1088 // Emit inter-object padding for alignment.
1089 unsigned AlignMask = CPE.getAlignment() - 1;
1090 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1091 OutStreamer.EmitZeros(NewOffset - Offset);
1093 Type *Ty = CPE.getType();
1094 Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
1095 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1097 if (CPE.isMachineConstantPoolEntry())
1098 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1100 EmitGlobalConstant(CPE.Val.ConstVal);
1105 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1106 /// by the current function to the current output stream.
1108 void AsmPrinter::EmitJumpTableInfo() {
1109 const DataLayout *DL = MF->getTarget().getDataLayout();
1110 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1111 if (MJTI == 0) return;
1112 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1113 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1114 if (JT.empty()) return;
1116 // Pick the directive to use to print the jump table entries, and switch to
1117 // the appropriate section.
1118 const Function *F = MF->getFunction();
1119 bool JTInDiffSection = false;
1120 if (// In PIC mode, we need to emit the jump table to the same section as the
1121 // function body itself, otherwise the label differences won't make sense.
1122 // FIXME: Need a better predicate for this: what about custom entries?
1123 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1124 // We should also do if the section name is NULL or function is declared
1125 // in discardable section
1126 // FIXME: this isn't the right predicate, should be based on the MCSection
1127 // for the function.
1128 F->isWeakForLinker()) {
1129 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1131 // Otherwise, drop it in the readonly section.
1132 const MCSection *ReadOnlySection =
1133 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1134 OutStreamer.SwitchSection(ReadOnlySection);
1135 JTInDiffSection = true;
1138 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
1140 // Jump tables in code sections are marked with a data_region directive
1141 // where that's supported.
1142 if (!JTInDiffSection)
1143 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1145 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1146 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1148 // If this jump table was deleted, ignore it.
1149 if (JTBBs.empty()) continue;
1151 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1152 // .set directive for each unique entry. This reduces the number of
1153 // relocations the assembler will generate for the jump table.
1154 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1155 MAI->hasSetDirective()) {
1156 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1157 const TargetLowering *TLI = TM.getTargetLowering();
1158 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1159 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1160 const MachineBasicBlock *MBB = JTBBs[ii];
1161 if (!EmittedSets.insert(MBB)) continue;
1163 // .set LJTSet, LBB32-base
1165 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1166 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1167 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1171 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1172 // before each jump table. The first label is never referenced, but tells
1173 // the assembler and linker the extents of the jump table object. The
1174 // second label is actually referenced by the code.
1175 if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
1176 // FIXME: This doesn't have to have any specific name, just any randomly
1177 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1178 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1180 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1182 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1183 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1185 if (!JTInDiffSection)
1186 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1189 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1191 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1192 const MachineBasicBlock *MBB,
1193 unsigned UID) const {
1194 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1195 const MCExpr *Value = 0;
1196 switch (MJTI->getEntryKind()) {
1197 case MachineJumpTableInfo::EK_Inline:
1198 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1199 case MachineJumpTableInfo::EK_Custom32:
1200 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1203 case MachineJumpTableInfo::EK_BlockAddress:
1204 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1206 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1208 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1209 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1210 // with a relocation as gp-relative, e.g.:
1212 MCSymbol *MBBSym = MBB->getSymbol();
1213 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1217 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1218 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1219 // with a relocation as gp-relative, e.g.:
1221 MCSymbol *MBBSym = MBB->getSymbol();
1222 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1226 case MachineJumpTableInfo::EK_LabelDifference32: {
1227 // EK_LabelDifference32 - Each entry is the address of the block minus
1228 // the address of the jump table. This is used for PIC jump tables where
1229 // gprel32 is not supported. e.g.:
1230 // .word LBB123 - LJTI1_2
1231 // If the .set directive is supported, this is emitted as:
1232 // .set L4_5_set_123, LBB123 - LJTI1_2
1233 // .word L4_5_set_123
1235 // If we have emitted set directives for the jump table entries, print
1236 // them rather than the entries themselves. If we're emitting PIC, then
1237 // emit the table entries as differences between two text section labels.
1238 if (MAI->hasSetDirective()) {
1239 // If we used .set, reference the .set's symbol.
1240 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1244 // Otherwise, use the difference as the jump table entry.
1245 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1246 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1247 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1252 assert(Value && "Unknown entry kind!");
1254 unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
1255 OutStreamer.EmitValue(Value, EntrySize);
1259 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1260 /// special global used by LLVM. If so, emit it and return true, otherwise
1261 /// do nothing and return false.
1262 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1263 if (GV->getName() == "llvm.used") {
1264 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1265 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1269 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1270 if (GV->getSection() == "llvm.metadata" ||
1271 GV->hasAvailableExternallyLinkage())
1274 if (!GV->hasAppendingLinkage()) return false;
1276 assert(GV->hasInitializer() && "Not a special LLVM global!");
1278 if (GV->getName() == "llvm.global_ctors") {
1279 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1281 if (TM.getRelocationModel() == Reloc::Static &&
1282 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1283 StringRef Sym(".constructors_used");
1284 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1290 if (GV->getName() == "llvm.global_dtors") {
1291 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1293 if (TM.getRelocationModel() == Reloc::Static &&
1294 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1295 StringRef Sym(".destructors_used");
1296 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1305 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1306 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1307 /// is true, as being used with this directive.
1308 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1309 // Should be an array of 'i8*'.
1310 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1311 const GlobalValue *GV =
1312 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1313 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1314 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1318 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1320 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1321 // Should be an array of '{ int, void ()* }' structs. The first value is the
1323 if (!isa<ConstantArray>(List)) return;
1325 // Sanity check the structors list.
1326 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1327 if (!InitList) return; // Not an array!
1328 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1329 if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1330 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1331 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1333 // Gather the structors in a form that's convenient for sorting by priority.
1334 typedef std::pair<unsigned, Constant *> Structor;
1335 SmallVector<Structor, 8> Structors;
1336 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1337 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1338 if (!CS) continue; // Malformed.
1339 if (CS->getOperand(1)->isNullValue())
1340 break; // Found a null terminator, skip the rest.
1341 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1342 if (!Priority) continue; // Malformed.
1343 Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1344 CS->getOperand(1)));
1347 // Emit the function pointers in the target-specific order
1348 const DataLayout *DL = TM.getDataLayout();
1349 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1350 std::stable_sort(Structors.begin(), Structors.end(), less_first());
1351 for (unsigned i = 0, e = Structors.size(); i != e; ++i) {
1352 const MCSection *OutputSection =
1354 getObjFileLowering().getStaticCtorSection(Structors[i].first) :
1355 getObjFileLowering().getStaticDtorSection(Structors[i].first));
1356 OutStreamer.SwitchSection(OutputSection);
1357 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1358 EmitAlignment(Align);
1359 EmitXXStructor(Structors[i].second);
1363 void AsmPrinter::EmitModuleIdents(Module &M) {
1364 if (!MAI->hasIdentDirective())
1367 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1368 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1369 const MDNode *N = NMD->getOperand(i);
1370 assert(N->getNumOperands() == 1 &&
1371 "llvm.ident metadata entry can have only one operand");
1372 const MDString *S = cast<MDString>(N->getOperand(0));
1373 OutStreamer.EmitIdent(S->getString());
1378 //===--------------------------------------------------------------------===//
1379 // Emission and print routines
1382 /// EmitInt8 - Emit a byte directive and value.
1384 void AsmPrinter::EmitInt8(int Value) const {
1385 OutStreamer.EmitIntValue(Value, 1);
1388 /// EmitInt16 - Emit a short directive and value.
1390 void AsmPrinter::EmitInt16(int Value) const {
1391 OutStreamer.EmitIntValue(Value, 2);
1394 /// EmitInt32 - Emit a long directive and value.
1396 void AsmPrinter::EmitInt32(int Value) const {
1397 OutStreamer.EmitIntValue(Value, 4);
1400 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1401 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1402 /// labels. This implicitly uses .set if it is available.
1403 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1404 unsigned Size) const {
1405 // Get the Hi-Lo expression.
1406 const MCExpr *Diff =
1407 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1408 MCSymbolRefExpr::Create(Lo, OutContext),
1411 if (!MAI->hasSetDirective()) {
1412 OutStreamer.EmitValue(Diff, Size);
1416 // Otherwise, emit with .set (aka assignment).
1417 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1418 OutStreamer.EmitAssignment(SetLabel, Diff);
1419 OutStreamer.EmitSymbolValue(SetLabel, Size);
1422 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1423 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1424 /// specify the labels. This implicitly uses .set if it is available.
1425 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1427 unsigned Size) const {
1429 // Emit Hi+Offset - Lo
1430 // Get the Hi+Offset expression.
1431 const MCExpr *Plus =
1432 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1433 MCConstantExpr::Create(Offset, OutContext),
1436 // Get the Hi+Offset-Lo expression.
1437 const MCExpr *Diff =
1438 MCBinaryExpr::CreateSub(Plus,
1439 MCSymbolRefExpr::Create(Lo, OutContext),
1442 if (!MAI->hasSetDirective())
1443 OutStreamer.EmitValue(Diff, Size);
1445 // Otherwise, emit with .set (aka assignment).
1446 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1447 OutStreamer.EmitAssignment(SetLabel, Diff);
1448 OutStreamer.EmitSymbolValue(SetLabel, Size);
1452 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1453 /// where the size in bytes of the directive is specified by Size and Label
1454 /// specifies the label. This implicitly uses .set if it is available.
1455 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1457 bool IsSectionRelative) const {
1458 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1459 OutStreamer.EmitCOFFSecRel32(Label);
1463 // Emit Label+Offset (or just Label if Offset is zero)
1464 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1466 Expr = MCBinaryExpr::CreateAdd(
1467 Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
1469 OutStreamer.EmitValue(Expr, Size);
1472 //===----------------------------------------------------------------------===//
1474 // EmitAlignment - Emit an alignment directive to the specified power of
1475 // two boundary. For example, if you pass in 3 here, you will get an 8
1476 // byte alignment. If a global value is specified, and if that global has
1477 // an explicit alignment requested, it will override the alignment request
1478 // if required for correctness.
1480 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1481 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
1483 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1485 if (getCurrentSection()->getKind().isText())
1486 OutStreamer.EmitCodeAlignment(1 << NumBits);
1488 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1491 //===----------------------------------------------------------------------===//
1492 // Constant emission.
1493 //===----------------------------------------------------------------------===//
1495 /// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
1497 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
1498 MCContext &Ctx = AP.OutContext;
1500 if (CV->isNullValue() || isa<UndefValue>(CV))
1501 return MCConstantExpr::Create(0, Ctx);
1503 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1504 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1506 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1507 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
1509 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1510 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1512 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1514 llvm_unreachable("Unknown constant value to lower!");
1517 switch (CE->getOpcode()) {
1519 // If the code isn't optimized, there may be outstanding folding
1520 // opportunities. Attempt to fold the expression using DataLayout as a
1521 // last resort before giving up.
1523 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
1525 return lowerConstant(C, AP);
1527 // Otherwise report the problem to the user.
1530 raw_string_ostream OS(S);
1531 OS << "Unsupported expression in static initializer: ";
1532 WriteAsOperand(OS, CE, /*PrintType=*/false,
1533 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1534 report_fatal_error(OS.str());
1536 case Instruction::GetElementPtr: {
1537 const DataLayout &DL = *AP.TM.getDataLayout();
1538 // Generate a symbolic expression for the byte address
1539 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1540 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1542 const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
1546 int64_t Offset = OffsetAI.getSExtValue();
1547 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1551 case Instruction::Trunc:
1552 // We emit the value and depend on the assembler to truncate the generated
1553 // expression properly. This is important for differences between
1554 // blockaddress labels. Since the two labels are in the same function, it
1555 // is reasonable to treat their delta as a 32-bit value.
1557 case Instruction::BitCast:
1558 return lowerConstant(CE->getOperand(0), AP);
1560 case Instruction::IntToPtr: {
1561 const DataLayout &DL = *AP.TM.getDataLayout();
1562 // Handle casts to pointers by changing them into casts to the appropriate
1563 // integer type. This promotes constant folding and simplifies this code.
1564 Constant *Op = CE->getOperand(0);
1565 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1567 return lowerConstant(Op, AP);
1570 case Instruction::PtrToInt: {
1571 const DataLayout &DL = *AP.TM.getDataLayout();
1572 // Support only foldable casts to/from pointers that can be eliminated by
1573 // changing the pointer to the appropriately sized integer type.
1574 Constant *Op = CE->getOperand(0);
1575 Type *Ty = CE->getType();
1577 const MCExpr *OpExpr = lowerConstant(Op, AP);
1579 // We can emit the pointer value into this slot if the slot is an
1580 // integer slot equal to the size of the pointer.
1581 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1584 // Otherwise the pointer is smaller than the resultant integer, mask off
1585 // the high bits so we are sure to get a proper truncation if the input is
1587 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1588 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1589 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1592 // The MC library also has a right-shift operator, but it isn't consistently
1593 // signed or unsigned between different targets.
1594 case Instruction::Add:
1595 case Instruction::Sub:
1596 case Instruction::Mul:
1597 case Instruction::SDiv:
1598 case Instruction::SRem:
1599 case Instruction::Shl:
1600 case Instruction::And:
1601 case Instruction::Or:
1602 case Instruction::Xor: {
1603 const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1604 const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
1605 switch (CE->getOpcode()) {
1606 default: llvm_unreachable("Unknown binary operator constant cast expr");
1607 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1608 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1609 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1610 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1611 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1612 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1613 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1614 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1615 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1621 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
1623 /// isRepeatedByteSequence - Determine whether the given value is
1624 /// composed of a repeated sequence of identical bytes and return the
1625 /// byte value. If it is not a repeated sequence, return -1.
1626 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1627 StringRef Data = V->getRawDataValues();
1628 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1630 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1631 if (Data[i] != C) return -1;
1632 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1636 /// isRepeatedByteSequence - Determine whether the given value is
1637 /// composed of a repeated sequence of identical bytes and return the
1638 /// byte value. If it is not a repeated sequence, return -1.
1639 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1641 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1642 if (CI->getBitWidth() > 64) return -1;
1644 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
1645 uint64_t Value = CI->getZExtValue();
1647 // Make sure the constant is at least 8 bits long and has a power
1648 // of 2 bit width. This guarantees the constant bit width is
1649 // always a multiple of 8 bits, avoiding issues with padding out
1650 // to Size and other such corner cases.
1651 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1653 uint8_t Byte = static_cast<uint8_t>(Value);
1655 for (unsigned i = 1; i < Size; ++i) {
1657 if (static_cast<uint8_t>(Value) != Byte) return -1;
1661 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1662 // Make sure all array elements are sequences of the same repeated
1664 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1665 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1666 if (Byte == -1) return -1;
1668 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1669 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1670 if (ThisByte == -1) return -1;
1671 if (Byte != ThisByte) return -1;
1676 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1677 return isRepeatedByteSequence(CDS);
1682 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1685 // See if we can aggregate this into a .fill, if so, emit it as such.
1686 int Value = isRepeatedByteSequence(CDS, AP.TM);
1688 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
1689 // Don't emit a 1-byte object as a .fill.
1691 return AP.OutStreamer.EmitFill(Bytes, Value);
1694 // If this can be emitted with .ascii/.asciz, emit it as such.
1695 if (CDS->isString())
1696 return AP.OutStreamer.EmitBytes(CDS->getAsString());
1698 // Otherwise, emit the values in successive locations.
1699 unsigned ElementByteSize = CDS->getElementByteSize();
1700 if (isa<IntegerType>(CDS->getElementType())) {
1701 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1703 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1704 CDS->getElementAsInteger(i));
1705 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1708 } else if (ElementByteSize == 4) {
1709 // FP Constants are printed as integer constants to avoid losing
1711 assert(CDS->getElementType()->isFloatTy());
1712 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1718 F = CDS->getElementAsFloat(i);
1720 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1721 AP.OutStreamer.EmitIntValue(I, 4);
1724 assert(CDS->getElementType()->isDoubleTy());
1725 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1731 F = CDS->getElementAsDouble(i);
1733 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1734 AP.OutStreamer.EmitIntValue(I, 8);
1738 const DataLayout &DL = *AP.TM.getDataLayout();
1739 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1740 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1741 CDS->getNumElements();
1742 if (unsigned Padding = Size - EmittedSize)
1743 AP.OutStreamer.EmitZeros(Padding);
1747 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
1748 // See if we can aggregate some values. Make sure it can be
1749 // represented as a series of bytes of the constant value.
1750 int Value = isRepeatedByteSequence(CA, AP.TM);
1753 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
1754 AP.OutStreamer.EmitFill(Bytes, Value);
1757 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1758 emitGlobalConstantImpl(CA->getOperand(i), AP);
1762 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1763 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1764 emitGlobalConstantImpl(CV->getOperand(i), AP);
1766 const DataLayout &DL = *AP.TM.getDataLayout();
1767 unsigned Size = DL.getTypeAllocSize(CV->getType());
1768 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1769 CV->getType()->getNumElements();
1770 if (unsigned Padding = Size - EmittedSize)
1771 AP.OutStreamer.EmitZeros(Padding);
1774 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
1775 // Print the fields in successive locations. Pad to align if needed!
1776 const DataLayout *DL = AP.TM.getDataLayout();
1777 unsigned Size = DL->getTypeAllocSize(CS->getType());
1778 const StructLayout *Layout = DL->getStructLayout(CS->getType());
1779 uint64_t SizeSoFar = 0;
1780 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1781 const Constant *Field = CS->getOperand(i);
1783 // Check if padding is needed and insert one or more 0s.
1784 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1785 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1786 - Layout->getElementOffset(i)) - FieldSize;
1787 SizeSoFar += FieldSize + PadSize;
1789 // Now print the actual field value.
1790 emitGlobalConstantImpl(Field, AP);
1792 // Insert padding - this may include padding to increase the size of the
1793 // current field up to the ABI size (if the struct is not packed) as well
1794 // as padding to ensure that the next field starts at the right offset.
1795 AP.OutStreamer.EmitZeros(PadSize);
1797 assert(SizeSoFar == Layout->getSizeInBytes() &&
1798 "Layout of constant struct may be incorrect!");
1801 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1802 APInt API = CFP->getValueAPF().bitcastToAPInt();
1804 // First print a comment with what we think the original floating-point value
1805 // should have been.
1806 if (AP.isVerbose()) {
1807 SmallString<8> StrVal;
1808 CFP->getValueAPF().toString(StrVal);
1810 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1811 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1814 // Now iterate through the APInt chunks, emitting them in endian-correct
1815 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1817 unsigned NumBytes = API.getBitWidth() / 8;
1818 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1819 const uint64_t *p = API.getRawData();
1821 // PPC's long double has odd notions of endianness compared to how LLVM
1822 // handles it: p[0] goes first for *big* endian on PPC.
1823 if (AP.TM.getDataLayout()->isBigEndian() != CFP->getType()->isPPC_FP128Ty()) {
1824 int Chunk = API.getNumWords() - 1;
1827 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1829 for (; Chunk >= 0; --Chunk)
1830 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1833 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1834 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1837 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
1840 // Emit the tail padding for the long double.
1841 const DataLayout &DL = *AP.TM.getDataLayout();
1842 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1843 DL.getTypeStoreSize(CFP->getType()));
1846 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
1847 const DataLayout *DL = AP.TM.getDataLayout();
1848 unsigned BitWidth = CI->getBitWidth();
1850 // Copy the value as we may massage the layout for constants whose bit width
1851 // is not a multiple of 64-bits.
1852 APInt Realigned(CI->getValue());
1853 uint64_t ExtraBits = 0;
1854 unsigned ExtraBitsSize = BitWidth & 63;
1856 if (ExtraBitsSize) {
1857 // The bit width of the data is not a multiple of 64-bits.
1858 // The extra bits are expected to be at the end of the chunk of the memory.
1860 // * Nothing to be done, just record the extra bits to emit.
1862 // * Record the extra bits to emit.
1863 // * Realign the raw data to emit the chunks of 64-bits.
1864 if (DL->isBigEndian()) {
1865 // Basically the structure of the raw data is a chunk of 64-bits cells:
1866 // 0 1 BitWidth / 64
1867 // [chunk1][chunk2] ... [chunkN].
1868 // The most significant chunk is chunkN and it should be emitted first.
1869 // However, due to the alignment issue chunkN contains useless bits.
1870 // Realign the chunks so that they contain only useless information:
1871 // ExtraBits 0 1 (BitWidth / 64) - 1
1872 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
1873 ExtraBits = Realigned.getRawData()[0] &
1874 (((uint64_t)-1) >> (64 - ExtraBitsSize));
1875 Realigned = Realigned.lshr(ExtraBitsSize);
1877 ExtraBits = Realigned.getRawData()[BitWidth / 64];
1880 // We don't expect assemblers to support integer data directives
1881 // for more than 64 bits, so we emit the data in at most 64-bit
1882 // quantities at a time.
1883 const uint64_t *RawData = Realigned.getRawData();
1884 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1885 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1886 AP.OutStreamer.EmitIntValue(Val, 8);
1889 if (ExtraBitsSize) {
1890 // Emit the extra bits after the 64-bits chunks.
1892 // Emit a directive that fills the expected size.
1893 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(CI->getType());
1894 Size -= (BitWidth / 64) * 8;
1895 assert(Size && Size * 8 >= ExtraBitsSize &&
1896 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
1897 == ExtraBits && "Directive too small for extra bits.");
1898 AP.OutStreamer.EmitIntValue(ExtraBits, Size);
1902 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
1903 const DataLayout *DL = AP.TM.getDataLayout();
1904 uint64_t Size = DL->getTypeAllocSize(CV->getType());
1905 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
1906 return AP.OutStreamer.EmitZeros(Size);
1908 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1915 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1916 CI->getZExtValue());
1917 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
1920 emitGlobalConstantLargeInt(CI, AP);
1925 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1926 return emitGlobalConstantFP(CFP, AP);
1928 if (isa<ConstantPointerNull>(CV)) {
1929 AP.OutStreamer.EmitIntValue(0, Size);
1933 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
1934 return emitGlobalConstantDataSequential(CDS, AP);
1936 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1937 return emitGlobalConstantArray(CVA, AP);
1939 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1940 return emitGlobalConstantStruct(CVS, AP);
1942 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1943 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
1945 if (CE->getOpcode() == Instruction::BitCast)
1946 return emitGlobalConstantImpl(CE->getOperand(0), AP);
1949 // If the constant expression's size is greater than 64-bits, then we have
1950 // to emit the value in chunks. Try to constant fold the value and emit it
1952 Constant *New = ConstantFoldConstantExpression(CE, DL);
1953 if (New && New != CE)
1954 return emitGlobalConstantImpl(New, AP);
1958 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1959 return emitGlobalConstantVector(V, AP);
1961 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1962 // thread the streamer with EmitValue.
1963 AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
1966 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1967 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
1968 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
1970 emitGlobalConstantImpl(CV, *this);
1971 else if (MAI->hasSubsectionsViaSymbols()) {
1972 // If the global has zero size, emit a single byte so that two labels don't
1973 // look like they are at the same location.
1974 OutStreamer.EmitIntValue(0, 1);
1978 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1979 // Target doesn't support this yet!
1980 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1983 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1985 OS << '+' << Offset;
1986 else if (Offset < 0)
1990 //===----------------------------------------------------------------------===//
1991 // Symbol Lowering Routines.
1992 //===----------------------------------------------------------------------===//
1994 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1995 /// temporary label with the specified stem and unique ID.
1996 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1997 const DataLayout *DL = TM.getDataLayout();
1998 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix()) +
2002 /// GetTempSymbol - Return an assembler temporary label with the specified
2004 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
2005 const DataLayout *DL = TM.getDataLayout();
2006 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
2011 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2012 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2015 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2016 return MMI->getAddrLabelSymbol(BB);
2019 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2020 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2021 const DataLayout *DL = TM.getDataLayout();
2022 return OutContext.GetOrCreateSymbol
2023 (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2024 + "_" + Twine(CPID));
2027 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2028 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2029 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2032 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2033 /// FIXME: privatize to AsmPrinter.
2034 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2035 const DataLayout *DL = TM.getDataLayout();
2036 return OutContext.GetOrCreateSymbol
2037 (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2038 Twine(UID) + "_set_" + Twine(MBBID));
2041 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2042 StringRef Suffix) const {
2043 return getObjFileLowering().getSymbolWithGlobalValueBase(*Mang, GV, Suffix);
2046 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2048 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2049 SmallString<60> NameStr;
2050 Mang->getNameWithPrefix(NameStr, Sym);
2051 return OutContext.GetOrCreateSymbol(NameStr.str());
2056 /// PrintParentLoopComment - Print comments about parent loops of this one.
2057 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2058 unsigned FunctionNumber) {
2059 if (Loop == 0) return;
2060 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2061 OS.indent(Loop->getLoopDepth()*2)
2062 << "Parent Loop BB" << FunctionNumber << "_"
2063 << Loop->getHeader()->getNumber()
2064 << " Depth=" << Loop->getLoopDepth() << '\n';
2068 /// PrintChildLoopComment - Print comments about child loops within
2069 /// the loop for this basic block, with nesting.
2070 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2071 unsigned FunctionNumber) {
2072 // Add child loop information
2073 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
2074 OS.indent((*CL)->getLoopDepth()*2)
2075 << "Child Loop BB" << FunctionNumber << "_"
2076 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
2078 PrintChildLoopComment(OS, *CL, FunctionNumber);
2082 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2083 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2084 const MachineLoopInfo *LI,
2085 const AsmPrinter &AP) {
2086 // Add loop depth information
2087 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2088 if (Loop == 0) return;
2090 MachineBasicBlock *Header = Loop->getHeader();
2091 assert(Header && "No header for loop");
2093 // If this block is not a loop header, just print out what is the loop header
2095 if (Header != &MBB) {
2096 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2097 Twine(AP.getFunctionNumber())+"_" +
2098 Twine(Loop->getHeader()->getNumber())+
2099 " Depth="+Twine(Loop->getLoopDepth()));
2103 // Otherwise, it is a loop header. Print out information about child and
2105 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2107 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2110 OS.indent(Loop->getLoopDepth()*2-2);
2115 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2117 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2121 /// EmitBasicBlockStart - This method prints the label for the specified
2122 /// MachineBasicBlock, an alignment (if present) and a comment describing
2123 /// it if appropriate.
2124 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
2125 // Emit an alignment directive for this block, if needed.
2126 if (unsigned Align = MBB->getAlignment())
2127 EmitAlignment(Align);
2129 // If the block has its address taken, emit any labels that were used to
2130 // reference the block. It is possible that there is more than one label
2131 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2132 // the references were generated.
2133 if (MBB->hasAddressTaken()) {
2134 const BasicBlock *BB = MBB->getBasicBlock();
2136 OutStreamer.AddComment("Block address taken");
2138 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
2140 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
2141 OutStreamer.EmitLabel(Syms[i]);
2144 // Print some verbose block comments.
2146 if (const BasicBlock *BB = MBB->getBasicBlock())
2148 OutStreamer.AddComment("%" + BB->getName());
2149 emitBasicBlockLoopComments(*MBB, LI, *this);
2152 // Print the main label for the block.
2153 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
2154 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
2155 // NOTE: Want this comment at start of line, don't emit with AddComment.
2156 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
2157 Twine(MBB->getNumber()) + ":");
2160 OutStreamer.EmitLabel(MBB->getSymbol());
2164 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2165 bool IsDefinition) const {
2166 MCSymbolAttr Attr = MCSA_Invalid;
2168 switch (Visibility) {
2170 case GlobalValue::HiddenVisibility:
2172 Attr = MAI->getHiddenVisibilityAttr();
2174 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2176 case GlobalValue::ProtectedVisibility:
2177 Attr = MAI->getProtectedVisibilityAttr();
2181 if (Attr != MCSA_Invalid)
2182 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2185 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2186 /// exactly one predecessor and the control transfer mechanism between
2187 /// the predecessor and this block is a fall-through.
2189 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2190 // If this is a landing pad, it isn't a fall through. If it has no preds,
2191 // then nothing falls through to it.
2192 if (MBB->isLandingPad() || MBB->pred_empty())
2195 // If there isn't exactly one predecessor, it can't be a fall through.
2196 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2198 if (PI2 != MBB->pred_end())
2201 // The predecessor has to be immediately before this block.
2202 MachineBasicBlock *Pred = *PI;
2204 if (!Pred->isLayoutSuccessor(MBB))
2207 // If the block is completely empty, then it definitely does fall through.
2211 // Check the terminators in the previous blocks
2212 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2213 IE = Pred->end(); II != IE; ++II) {
2214 MachineInstr &MI = *II;
2216 // If it is not a simple branch, we are in a table somewhere.
2217 if (!MI.isBranch() || MI.isIndirectBranch())
2220 // If we are the operands of one of the branches, this is not
2222 for (MachineInstr::mop_iterator OI = MI.operands_begin(),
2223 OE = MI.operands_end(); OI != OE; ++OI) {
2224 const MachineOperand& OP = *OI;
2227 if (OP.isMBB() && OP.getMBB() == MBB)
2237 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2238 if (!S->usesMetadata())
2241 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2242 gcp_map_type::iterator GCPI = GCMap.find(S);
2243 if (GCPI != GCMap.end())
2244 return GCPI->second;
2246 const char *Name = S->getName().c_str();
2248 for (GCMetadataPrinterRegistry::iterator
2249 I = GCMetadataPrinterRegistry::begin(),
2250 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2251 if (strcmp(Name, I->getName()) == 0) {
2252 GCMetadataPrinter *GMP = I->instantiate();
2254 GCMap.insert(std::make_pair(S, GMP));
2258 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2261 /// Pin vtable to this file.
2262 AsmPrinterHandler::~AsmPrinterHandler() {}