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 "WinCodeViewLineTables.h"
19 #include "llvm/ADT/SmallBitVector.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/CodeGen/GCMetadataPrinter.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBundle.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/Mangler.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/MCExpr.h"
39 #include "llvm/MC/MCInst.h"
40 #include "llvm/MC/MCSection.h"
41 #include "llvm/MC/MCStreamer.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/Format.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Target/TargetFrameLowering.h"
48 #include "llvm/Target/TargetInstrInfo.h"
49 #include "llvm/Target/TargetLowering.h"
50 #include "llvm/Target/TargetLoweringObjectFile.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include "llvm/Target/TargetRegisterInfo.h"
53 #include "llvm/Target/TargetSubtargetInfo.h"
54 #include "llvm/Transforms/Utils/GlobalStatus.h"
57 static const char *const DWARFGroupName = "DWARF Emission";
58 static const char *const DbgTimerName = "Debug Info Emission";
59 static const char *const EHTimerName = "DWARF Exception Writer";
60 static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables";
62 STATISTIC(EmittedInsts, "Number of machine instrs printed");
64 char AsmPrinter::ID = 0;
66 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
67 static gcp_map_type &getGCMap(void *&P) {
69 P = new gcp_map_type();
70 return *(gcp_map_type*)P;
74 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
75 /// value in log2 form. This rounds up to the preferred alignment if possible
77 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
78 unsigned InBits = 0) {
80 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
81 NumBits = TD.getPreferredAlignmentLog(GVar);
83 // If InBits is specified, round it to it.
87 // If the GV has a specified alignment, take it into account.
88 if (GV->getAlignment() == 0)
91 unsigned GVAlign = Log2_32(GV->getAlignment());
93 // If the GVAlign is larger than NumBits, or if we are required to obey
94 // NumBits because the GV has an assigned section, obey it.
95 if (GVAlign > NumBits || GV->hasSection())
100 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
101 : MachineFunctionPass(ID),
102 TM(tm), MAI(tm.getMCAsmInfo()), MII(tm.getInstrInfo()),
103 OutContext(Streamer.getContext()),
104 OutStreamer(Streamer),
105 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
106 DD = 0; MMI = 0; LI = 0; MF = 0;
107 CurrentFnSym = CurrentFnSymForSize = 0;
108 GCMetadataPrinters = 0;
109 VerboseAsm = Streamer.isVerboseAsm();
112 AsmPrinter::~AsmPrinter() {
113 assert(DD == 0 && Handlers.empty() && "Debug/EH info didn't get finalized");
115 if (GCMetadataPrinters != 0) {
116 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
118 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
121 GCMetadataPrinters = 0;
127 /// getFunctionNumber - Return a unique ID for the current function.
129 unsigned AsmPrinter::getFunctionNumber() const {
130 return MF->getFunctionNumber();
133 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
134 return TM.getTargetLowering()->getObjFileLowering();
137 /// getDataLayout - Return information about data layout.
138 const DataLayout &AsmPrinter::getDataLayout() const {
139 return *TM.getDataLayout();
142 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
143 return TM.getSubtarget<MCSubtargetInfo>();
146 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
147 S.EmitInstruction(Inst, getSubtargetInfo());
150 StringRef AsmPrinter::getTargetTriple() const {
151 return TM.getTargetTriple();
154 /// getCurrentSection() - Return the current section we are emitting to.
155 const MCSection *AsmPrinter::getCurrentSection() const {
156 return OutStreamer.getCurrentSection().first;
161 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
162 AU.setPreservesAll();
163 MachineFunctionPass::getAnalysisUsage(AU);
164 AU.addRequired<MachineModuleInfo>();
165 AU.addRequired<GCModuleInfo>();
167 AU.addRequired<MachineLoopInfo>();
170 bool AsmPrinter::doInitialization(Module &M) {
171 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
172 MMI->AnalyzeModule(M);
174 // Initialize TargetLoweringObjectFile.
175 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
176 .Initialize(OutContext, TM);
178 OutStreamer.InitSections();
180 Mang = new Mangler(TM.getDataLayout());
182 // Allow the target to emit any magic that it wants at the start of the file.
183 EmitStartOfAsmFile(M);
185 // Very minimal debug info. It is ignored if we emit actual debug info. If we
186 // don't, this at least helps the user find where a global came from.
187 if (MAI->hasSingleParameterDotFile()) {
189 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
192 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
193 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
194 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
195 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
196 MP->beginAssembly(*this);
198 // Emit module-level inline asm if it exists.
199 if (!M.getModuleInlineAsm().empty()) {
200 OutStreamer.AddComment("Start of file scope inline assembly");
201 OutStreamer.AddBlankLine();
202 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
203 OutStreamer.AddComment("End of file scope inline assembly");
204 OutStreamer.AddBlankLine();
207 if (MAI->doesSupportDebugInformation()) {
208 if (Triple(TM.getTargetTriple()).getOS() == Triple::Win32) {
209 Handlers.push_back(HandlerInfo(new WinCodeViewLineTables(this),
211 CodeViewLineTablesGroupName));
213 DD = new DwarfDebug(this, &M);
214 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
218 DwarfException *DE = 0;
219 switch (MAI->getExceptionHandlingType()) {
220 case ExceptionHandling::None:
222 case ExceptionHandling::SjLj:
223 case ExceptionHandling::DwarfCFI:
224 DE = new DwarfCFIException(this);
226 case ExceptionHandling::ARM:
227 DE = new ARMException(this);
229 case ExceptionHandling::Win64:
230 DE = new Win64Exception(this);
234 Handlers.push_back(HandlerInfo(DE, EHTimerName, DWARFGroupName));
238 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
239 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
240 if (Linkage != GlobalValue::LinkOnceODRLinkage)
243 if (!MAI.hasWeakDefCanBeHiddenDirective())
246 if (GV->hasUnnamedAddr())
249 // This is only used for MachO, so right now it doesn't really matter how
250 // we handle alias. Revisit this once the MachO linker implements aliases.
251 if (isa<GlobalAlias>(GV))
254 // If it is a non constant variable, it needs to be uniqued across shared
256 if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
257 if (!Var->isConstant())
262 if (!GlobalStatus::analyzeGlobal(GV, GS) && !GS.IsCompared)
268 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
269 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
271 case GlobalValue::CommonLinkage:
272 case GlobalValue::LinkOnceAnyLinkage:
273 case GlobalValue::LinkOnceODRLinkage:
274 case GlobalValue::WeakAnyLinkage:
275 case GlobalValue::WeakODRLinkage:
276 case GlobalValue::LinkerPrivateWeakLinkage:
277 if (MAI->hasWeakDefDirective()) {
279 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
281 if (!canBeHidden(GV, *MAI))
282 // .weak_definition _foo
283 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
285 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
286 } else if (MAI->hasLinkOnceDirective()) {
288 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
289 //NOTE: linkonce is handled by the section the symbol was assigned to.
292 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
295 case GlobalValue::AppendingLinkage:
296 // FIXME: appending linkage variables should go into a section of
297 // their name or something. For now, just emit them as external.
298 case GlobalValue::ExternalLinkage:
299 // If external or appending, declare as a global symbol.
301 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
303 case GlobalValue::PrivateLinkage:
304 case GlobalValue::InternalLinkage:
305 case GlobalValue::LinkerPrivateLinkage:
307 case GlobalValue::AvailableExternallyLinkage:
308 llvm_unreachable("Should never emit this");
309 case GlobalValue::ExternalWeakLinkage:
310 llvm_unreachable("Don't know how to emit these");
312 llvm_unreachable("Unknown linkage type!");
315 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
316 const GlobalValue *GV) const {
317 TM.getNameWithPrefix(Name, GV, *Mang);
320 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
321 return TM.getSymbol(GV, *Mang);
324 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
325 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
326 if (GV->hasInitializer()) {
327 // Check to see if this is a special global used by LLVM, if so, emit it.
328 if (EmitSpecialLLVMGlobal(GV))
332 GV->printAsOperand(OutStreamer.GetCommentOS(),
333 /*PrintType=*/false, GV->getParent());
334 OutStreamer.GetCommentOS() << '\n';
338 MCSymbol *GVSym = getSymbol(GV);
339 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
341 if (!GV->hasInitializer()) // External globals require no extra code.
344 if (MAI->hasDotTypeDotSizeDirective())
345 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
347 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
349 const DataLayout *DL = TM.getDataLayout();
350 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
352 // If the alignment is specified, we *must* obey it. Overaligning a global
353 // with a specified alignment is a prompt way to break globals emitted to
354 // sections and expected to be contiguous (e.g. ObjC metadata).
355 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
357 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
358 const HandlerInfo &OI = Handlers[I];
359 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName, TimePassesIsEnabled);
360 OI.Handler->setSymbolSize(GVSym, Size);
363 // Handle common and BSS local symbols (.lcomm).
364 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
365 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
366 unsigned Align = 1 << AlignLog;
368 // Handle common symbols.
369 if (GVKind.isCommon()) {
370 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
374 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
378 // Handle local BSS symbols.
379 if (MAI->hasMachoZeroFillDirective()) {
380 const MCSection *TheSection =
381 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
382 // .zerofill __DATA, __bss, _foo, 400, 5
383 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
387 // Use .lcomm only if it supports user-specified alignment.
388 // Otherwise, while it would still be correct to use .lcomm in some
389 // cases (e.g. when Align == 1), the external assembler might enfore
390 // some -unknown- default alignment behavior, which could cause
391 // spurious differences between external and integrated assembler.
392 // Prefer to simply fall back to .local / .comm in this case.
393 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
395 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
399 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
403 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
405 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
409 const MCSection *TheSection =
410 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
412 // Handle the zerofill directive on darwin, which is a special form of BSS
414 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
415 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
418 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
419 // .zerofill __DATA, __common, _foo, 400, 5
420 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
424 // Handle thread local data for mach-o which requires us to output an
425 // additional structure of data and mangle the original symbol so that we
426 // can reference it later.
428 // TODO: This should become an "emit thread local global" method on TLOF.
429 // All of this macho specific stuff should be sunk down into TLOFMachO and
430 // stuff like "TLSExtraDataSection" should no longer be part of the parent
431 // TLOF class. This will also make it more obvious that stuff like
432 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
434 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
435 // Emit the .tbss symbol
437 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
439 if (GVKind.isThreadBSS()) {
440 TheSection = getObjFileLowering().getTLSBSSSection();
441 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
442 } else if (GVKind.isThreadData()) {
443 OutStreamer.SwitchSection(TheSection);
445 EmitAlignment(AlignLog, GV);
446 OutStreamer.EmitLabel(MangSym);
448 EmitGlobalConstant(GV->getInitializer());
451 OutStreamer.AddBlankLine();
453 // Emit the variable struct for the runtime.
454 const MCSection *TLVSect
455 = getObjFileLowering().getTLSExtraDataSection();
457 OutStreamer.SwitchSection(TLVSect);
458 // Emit the linkage here.
459 EmitLinkage(GV, GVSym);
460 OutStreamer.EmitLabel(GVSym);
462 // Three pointers in size:
463 // - __tlv_bootstrap - used to make sure support exists
464 // - spare pointer, used when mapped by the runtime
465 // - pointer to mangled symbol above with initializer
466 unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
467 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
469 OutStreamer.EmitIntValue(0, PtrSize);
470 OutStreamer.EmitSymbolValue(MangSym, PtrSize);
472 OutStreamer.AddBlankLine();
476 OutStreamer.SwitchSection(TheSection);
478 EmitLinkage(GV, GVSym);
479 EmitAlignment(AlignLog, GV);
481 OutStreamer.EmitLabel(GVSym);
483 EmitGlobalConstant(GV->getInitializer());
485 if (MAI->hasDotTypeDotSizeDirective())
487 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
489 OutStreamer.AddBlankLine();
492 /// EmitFunctionHeader - This method emits the header for the current
494 void AsmPrinter::EmitFunctionHeader() {
495 // Print out constants referenced by the function
498 // Print the 'header' of function.
499 const Function *F = MF->getFunction();
501 OutStreamer.SwitchSection(
502 getObjFileLowering().SectionForGlobal(F, *Mang, TM));
503 EmitVisibility(CurrentFnSym, F->getVisibility());
505 EmitLinkage(F, CurrentFnSym);
506 EmitAlignment(MF->getAlignment(), F);
508 if (MAI->hasDotTypeDotSizeDirective())
509 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
512 F->printAsOperand(OutStreamer.GetCommentOS(),
513 /*PrintType=*/false, F->getParent());
514 OutStreamer.GetCommentOS() << '\n';
517 // Emit the CurrentFnSym. This is a virtual function to allow targets to
518 // do their wild and crazy things as required.
519 EmitFunctionEntryLabel();
521 // If the function had address-taken blocks that got deleted, then we have
522 // references to the dangling symbols. Emit them at the start of the function
523 // so that we don't get references to undefined symbols.
524 std::vector<MCSymbol*> DeadBlockSyms;
525 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
526 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
527 OutStreamer.AddComment("Address taken block that was later removed");
528 OutStreamer.EmitLabel(DeadBlockSyms[i]);
531 // Emit pre-function debug and/or EH information.
532 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
533 const HandlerInfo &OI = Handlers[I];
534 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName, TimePassesIsEnabled);
535 OI.Handler->beginFunction(MF);
538 // Emit the prefix data.
539 if (F->hasPrefixData())
540 EmitGlobalConstant(F->getPrefixData());
543 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
544 /// function. This can be overridden by targets as required to do custom stuff.
545 void AsmPrinter::EmitFunctionEntryLabel() {
546 // The function label could have already been emitted if two symbols end up
547 // conflicting due to asm renaming. Detect this and emit an error.
548 if (CurrentFnSym->isUndefined())
549 return OutStreamer.EmitLabel(CurrentFnSym);
551 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
552 "' label emitted multiple times to assembly file");
555 /// emitComments - Pretty-print comments for instructions.
556 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
557 const MachineFunction *MF = MI.getParent()->getParent();
558 const TargetMachine &TM = MF->getTarget();
560 // Check for spills and reloads
563 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
565 // We assume a single instruction only has a spill or reload, not
567 const MachineMemOperand *MMO;
568 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
569 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
570 MMO = *MI.memoperands_begin();
571 CommentOS << MMO->getSize() << "-byte Reload\n";
573 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
574 if (FrameInfo->isSpillSlotObjectIndex(FI))
575 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
576 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
577 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
578 MMO = *MI.memoperands_begin();
579 CommentOS << MMO->getSize() << "-byte Spill\n";
581 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
582 if (FrameInfo->isSpillSlotObjectIndex(FI))
583 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
586 // Check for spill-induced copies
587 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
588 CommentOS << " Reload Reuse\n";
591 /// emitImplicitDef - This method emits the specified machine instruction
592 /// that is an implicit def.
593 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
594 unsigned RegNo = MI->getOperand(0).getReg();
595 OutStreamer.AddComment(Twine("implicit-def: ") +
596 TM.getRegisterInfo()->getName(RegNo));
597 OutStreamer.AddBlankLine();
600 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
601 std::string Str = "kill:";
602 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
603 const MachineOperand &Op = MI->getOperand(i);
604 assert(Op.isReg() && "KILL instruction must have only register operands");
606 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
607 Str += (Op.isDef() ? "<def>" : "<kill>");
609 AP.OutStreamer.AddComment(Str);
610 AP.OutStreamer.AddBlankLine();
613 /// emitDebugValueComment - This method handles the target-independent form
614 /// of DBG_VALUE, returning true if it was able to do so. A false return
615 /// means the target will need to handle MI in EmitInstruction.
616 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
617 // This code handles only the 3-operand target-independent form.
618 if (MI->getNumOperands() != 3)
621 SmallString<128> Str;
622 raw_svector_ostream OS(Str);
623 OS << "DEBUG_VALUE: ";
625 DIVariable V(MI->getOperand(2).getMetadata());
626 if (V.getContext().isSubprogram()) {
627 StringRef Name = DISubprogram(V.getContext()).getDisplayName();
631 OS << V.getName() << " <- ";
633 // The second operand is only an offset if it's an immediate.
634 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
635 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
637 // Register or immediate value. Register 0 means undef.
638 if (MI->getOperand(0).isFPImm()) {
639 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
640 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
641 OS << (double)APF.convertToFloat();
642 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
643 OS << APF.convertToDouble();
645 // There is no good way to print long double. Convert a copy to
646 // double. Ah well, it's only a comment.
648 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
650 OS << "(long double) " << APF.convertToDouble();
652 } else if (MI->getOperand(0).isImm()) {
653 OS << MI->getOperand(0).getImm();
654 } else if (MI->getOperand(0).isCImm()) {
655 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
658 if (MI->getOperand(0).isReg()) {
659 Reg = MI->getOperand(0).getReg();
661 assert(MI->getOperand(0).isFI() && "Unknown operand type");
662 const TargetFrameLowering *TFI = AP.TM.getFrameLowering();
663 Offset += TFI->getFrameIndexReference(*AP.MF,
664 MI->getOperand(0).getIndex(), Reg);
668 // Suppress offset, it is not meaningful here.
670 // NOTE: Want this comment at start of line, don't emit with AddComment.
671 AP.OutStreamer.emitRawComment(OS.str());
676 OS << AP.TM.getRegisterInfo()->getName(Reg);
680 OS << '+' << Offset << ']';
682 // NOTE: Want this comment at start of line, don't emit with AddComment.
683 AP.OutStreamer.emitRawComment(OS.str());
687 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
688 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
689 MF->getFunction()->needsUnwindTableEntry())
692 if (MMI->hasDebugInfo())
698 bool AsmPrinter::needsSEHMoves() {
699 return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
700 MF->getFunction()->needsUnwindTableEntry();
703 void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
704 const MCSymbol *Label = MI.getOperand(0).getMCSymbol();
706 ExceptionHandling::ExceptionsType ExceptionHandlingType =
707 MAI->getExceptionHandlingType();
708 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
709 ExceptionHandlingType != ExceptionHandling::ARM)
712 if (needsCFIMoves() == CFI_M_None)
715 if (MMI->getCompactUnwindEncoding() != 0)
716 OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
718 const MachineModuleInfo &MMI = MF->getMMI();
719 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
720 bool FoundOne = false;
722 for (std::vector<MCCFIInstruction>::const_iterator I = Instrs.begin(),
723 E = Instrs.end(); I != E; ++I) {
724 if (I->getLabel() == Label) {
725 emitCFIInstruction(*I);
732 /// EmitFunctionBody - This method emits the body and trailer for a
734 void AsmPrinter::EmitFunctionBody() {
735 // Emit target-specific gunk before the function body.
736 EmitFunctionBodyStart();
738 bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
740 // Print out code for the function.
741 bool HasAnyRealCode = false;
742 const MachineInstr *LastMI = 0;
743 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
745 // Print a label for the basic block.
746 EmitBasicBlockStart(I);
747 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
751 // Print the assembly for the instruction.
752 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
753 !II->isDebugValue()) {
754 HasAnyRealCode = true;
758 if (ShouldPrintDebugScopes) {
759 for (unsigned III = 0, EEE = Handlers.size(); III != EEE; ++III) {
760 const HandlerInfo &OI = Handlers[III];
761 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
762 TimePassesIsEnabled);
763 OI.Handler->beginInstruction(II);
768 emitComments(*II, OutStreamer.GetCommentOS());
770 switch (II->getOpcode()) {
771 case TargetOpcode::PROLOG_LABEL:
772 emitPrologLabel(*II);
775 case TargetOpcode::EH_LABEL:
776 case TargetOpcode::GC_LABEL:
777 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
779 case TargetOpcode::INLINEASM:
782 case TargetOpcode::DBG_VALUE:
784 if (!emitDebugValueComment(II, *this))
788 case TargetOpcode::IMPLICIT_DEF:
789 if (isVerbose()) emitImplicitDef(II);
791 case TargetOpcode::KILL:
792 if (isVerbose()) emitKill(II, *this);
799 if (ShouldPrintDebugScopes) {
800 for (unsigned III = 0, EEE = Handlers.size(); III != EEE; ++III) {
801 const HandlerInfo &OI = Handlers[III];
802 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
803 TimePassesIsEnabled);
804 OI.Handler->endInstruction();
810 // If the last instruction was a prolog label, then we have a situation where
811 // we emitted a prolog but no function body. This results in the ending prolog
812 // label equaling the end of function label and an invalid "row" in the
813 // FDE. We need to emit a noop in this situation so that the FDE's rows are
815 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
817 // If the function is empty and the object file uses .subsections_via_symbols,
818 // then we need to emit *something* to the function body to prevent the
819 // labels from collapsing together. Just emit a noop.
820 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
822 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
823 if (Noop.getOpcode()) {
824 OutStreamer.AddComment("avoids zero-length function");
825 OutStreamer.EmitInstruction(Noop, getSubtargetInfo());
826 } else // Target not mc-ized yet.
827 OutStreamer.EmitRawText(StringRef("\tnop\n"));
830 const Function *F = MF->getFunction();
831 for (Function::const_iterator i = F->begin(), e = F->end(); i != e; ++i) {
832 const BasicBlock *BB = i;
833 if (!BB->hasAddressTaken())
835 MCSymbol *Sym = GetBlockAddressSymbol(BB);
836 if (Sym->isDefined())
838 OutStreamer.AddComment("Address of block that was removed by CodeGen");
839 OutStreamer.EmitLabel(Sym);
842 // Emit target-specific gunk after the function body.
843 EmitFunctionBodyEnd();
845 // If the target wants a .size directive for the size of the function, emit
847 if (MAI->hasDotTypeDotSizeDirective()) {
848 // Create a symbol for the end of function, so we can get the size as
849 // difference between the function label and the temp label.
850 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
851 OutStreamer.EmitLabel(FnEndLabel);
853 const MCExpr *SizeExp =
854 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
855 MCSymbolRefExpr::Create(CurrentFnSymForSize,
858 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
861 // Emit post-function debug and/or EH information.
862 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
863 const HandlerInfo &OI = Handlers[I];
864 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName, TimePassesIsEnabled);
865 OI.Handler->endFunction(MF);
869 // Print out jump tables referenced by the function.
872 OutStreamer.AddBlankLine();
875 /// Emit a dwarf register operation.
876 static void emitDwarfRegOp(const AsmPrinter &AP, int Reg) {
879 AP.OutStreamer.AddComment(dwarf::
880 OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
881 AP.EmitInt8(dwarf::DW_OP_reg0 + Reg);
883 AP.OutStreamer.AddComment("DW_OP_regx");
884 AP.EmitInt8(dwarf::DW_OP_regx);
885 AP.OutStreamer.AddComment(Twine(Reg));
890 /// Emit an (double-)indirect dwarf register operation.
891 static void emitDwarfRegOpIndirect(const AsmPrinter &AP,
892 int Reg, int Offset, bool Deref) {
895 AP.OutStreamer.AddComment(dwarf::
896 OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
897 AP.EmitInt8(dwarf::DW_OP_breg0 + Reg);
899 AP.OutStreamer.AddComment("DW_OP_bregx");
900 AP.EmitInt8(dwarf::DW_OP_bregx);
901 AP.OutStreamer.AddComment(Twine(Reg));
904 AP.EmitSLEB128(Offset);
906 AP.EmitInt8(dwarf::DW_OP_deref);
909 /// Emit a dwarf register operation for describing
910 /// - a small value occupying only part of a register or
911 /// - a small register representing only part of a value.
912 static void emitDwarfOpPiece(const AsmPrinter &AP,
913 unsigned Size, unsigned Offset) {
916 AP.OutStreamer.AddComment("DW_OP_bit_piece");
917 AP.EmitInt8(dwarf::DW_OP_bit_piece);
918 AP.OutStreamer.AddComment(Twine(Size));
919 AP.EmitULEB128(Size);
920 AP.OutStreamer.AddComment(Twine(Offset));
921 AP.EmitULEB128(Offset);
923 AP.OutStreamer.AddComment("DW_OP_piece");
924 AP.EmitInt8(dwarf::DW_OP_piece);
925 unsigned ByteSize = Size / 8; // Assuming 8 bits per byte.
926 AP.OutStreamer.AddComment(Twine(ByteSize));
927 AP.EmitULEB128(ByteSize);
931 /// Some targets do not provide a DWARF register number for every
932 /// register. This function attempts to emit a dwarf register by
933 /// emitting a piece of a super-register or by piecing together
934 /// multiple subregisters that alias the register.
935 static void EmitDwarfRegOpPiece(const AsmPrinter &AP,
936 const MachineLocation &MLoc) {
937 assert(!MLoc.isIndirect());
938 const TargetRegisterInfo *TRI = AP.TM.getRegisterInfo();
939 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
941 // Walk up the super-register chain until we find a valid number.
942 // For example, EAX on x86_64 is a 32-bit piece of RAX with offset 0.
943 for (MCSuperRegIterator SR(MLoc.getReg(), TRI); SR.isValid(); ++SR) {
944 Reg = TRI->getDwarfRegNum(*SR, false);
946 unsigned Idx = TRI->getSubRegIndex(*SR, MLoc.getReg());
947 unsigned Size = TRI->getSubRegIdxSize(Idx);
948 unsigned Offset = TRI->getSubRegIdxOffset(Idx);
949 AP.OutStreamer.AddComment("super-register");
950 emitDwarfRegOp(AP, Reg);
951 emitDwarfOpPiece(AP, Size, Offset);
956 // Otherwise, attempt to find a covering set of sub-register numbers.
957 // For example, Q0 on ARM is a composition of D0+D1.
959 // Keep track of the current position so we can emit the more
960 // efficient DW_OP_piece.
962 // The size of the register in bits, assuming 8 bits per byte.
963 unsigned RegSize = TRI->getMinimalPhysRegClass(MLoc.getReg())->getSize()*8;
964 // Keep track of the bits in the register we already emitted, so we
965 // can avoid emitting redundant aliasing subregs.
966 SmallBitVector Coverage(RegSize, false);
967 for (MCSubRegIterator SR(MLoc.getReg(), TRI); SR.isValid(); ++SR) {
968 unsigned Idx = TRI->getSubRegIndex(MLoc.getReg(), *SR);
969 unsigned Size = TRI->getSubRegIdxSize(Idx);
970 unsigned Offset = TRI->getSubRegIdxOffset(Idx);
971 Reg = TRI->getDwarfRegNum(*SR, false);
973 // Intersection between the bits we already emitted and the bits
974 // covered by this subregister.
975 SmallBitVector Intersection(RegSize, false);
976 Intersection.set(Offset, Offset+Size);
977 Intersection ^= Coverage;
979 // If this sub-register has a DWARF number and we haven't covered
980 // its range, emit a DWARF piece for it.
981 if (Reg >= 0 && Intersection.any()) {
982 AP.OutStreamer.AddComment("sub-register");
983 emitDwarfRegOp(AP, Reg);
984 emitDwarfOpPiece(AP, Size, Offset == CurPos ? 0 : Offset);
985 CurPos = Offset+Size;
987 // Mark it as emitted.
988 Coverage.set(Offset, Offset+Size);
993 // FIXME: We have no reasonable way of handling errors in here.
994 AP.OutStreamer.AddComment("nop (could not find a dwarf register number)");
995 AP.EmitInt8(dwarf::DW_OP_nop);
999 /// EmitDwarfRegOp - Emit dwarf register operation.
1000 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc,
1001 bool Indirect) const {
1002 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
1003 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
1005 // We assume that pointers are always in an addressable register.
1006 if (Indirect || MLoc.isIndirect()) {
1007 // FIXME: We have no reasonable way of handling errors in here. The
1008 // caller might be in the middle of a dwarf expression. We should
1009 // probably assert that Reg >= 0 once debug info generation is more mature.
1010 OutStreamer.AddComment("nop (invalid dwarf register number for indirect loc)");
1011 EmitInt8(dwarf::DW_OP_nop);
1015 // Attempt to find a valid super- or sub-register.
1016 if (!Indirect && !MLoc.isIndirect())
1017 return EmitDwarfRegOpPiece(*this, MLoc);
1020 if (MLoc.isIndirect())
1021 emitDwarfRegOpIndirect(*this, Reg, MLoc.getOffset(), Indirect);
1023 emitDwarfRegOpIndirect(*this, Reg, 0, false);
1025 emitDwarfRegOp(*this, Reg);
1028 bool AsmPrinter::doFinalization(Module &M) {
1029 // Emit global variables.
1030 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1032 EmitGlobalVariable(I);
1034 // Emit visibility info for declarations
1035 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
1036 const Function &F = *I;
1037 if (!F.isDeclaration())
1039 GlobalValue::VisibilityTypes V = F.getVisibility();
1040 if (V == GlobalValue::DefaultVisibility)
1043 MCSymbol *Name = getSymbol(&F);
1044 EmitVisibility(Name, V, false);
1047 // Emit module flags.
1048 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
1049 M.getModuleFlagsMetadata(ModuleFlags);
1050 if (!ModuleFlags.empty())
1051 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, *Mang, TM);
1053 // Make sure we wrote out everything we need.
1054 OutStreamer.Flush();
1056 // Finalize debug and EH information.
1057 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
1058 const HandlerInfo &OI = Handlers[I];
1059 NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
1060 TimePassesIsEnabled);
1061 OI.Handler->endModule();
1067 // If the target wants to know about weak references, print them all.
1068 if (MAI->getWeakRefDirective()) {
1069 // FIXME: This is not lazy, it would be nice to only print weak references
1070 // to stuff that is actually used. Note that doing so would require targets
1071 // to notice uses in operands (due to constant exprs etc). This should
1072 // happen with the MC stuff eventually.
1074 // Print out module-level global variables here.
1075 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1077 if (!I->hasExternalWeakLinkage()) continue;
1078 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
1081 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
1082 if (!I->hasExternalWeakLinkage()) continue;
1083 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
1087 if (MAI->hasSetDirective()) {
1088 OutStreamer.AddBlankLine();
1089 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
1091 MCSymbol *Name = getSymbol(I);
1093 const GlobalValue *GV = I->getAliasedGlobal();
1094 if (GV->isDeclaration()) {
1095 report_fatal_error(Name->getName() +
1096 ": Target doesn't support aliases to declarations");
1099 MCSymbol *Target = getSymbol(GV);
1101 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
1102 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
1103 else if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1104 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
1106 assert(I->hasLocalLinkage() && "Invalid alias linkage");
1108 EmitVisibility(Name, I->getVisibility());
1110 // Emit the directives as assignments aka .set:
1111 OutStreamer.EmitAssignment(Name,
1112 MCSymbolRefExpr::Create(Target, OutContext));
1116 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1117 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1118 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1119 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
1120 MP->finishAssembly(*this);
1122 // Emit llvm.ident metadata in an '.ident' directive.
1123 EmitModuleIdents(M);
1125 // If we don't have any trampolines, then we don't require stack memory
1126 // to be executable. Some targets have a directive to declare this.
1127 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1128 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1129 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1130 OutStreamer.SwitchSection(S);
1132 // Allow the target to emit any magic that it wants at the end of the file,
1133 // after everything else has gone out.
1134 EmitEndOfAsmFile(M);
1136 delete Mang; Mang = 0;
1139 OutStreamer.Finish();
1140 OutStreamer.reset();
1145 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1147 // Get the function symbol.
1148 CurrentFnSym = getSymbol(MF.getFunction());
1149 CurrentFnSymForSize = CurrentFnSym;
1152 LI = &getAnalysis<MachineLoopInfo>();
1156 // SectionCPs - Keep track the alignment, constpool entries per Section.
1160 SmallVector<unsigned, 4> CPEs;
1161 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1165 /// EmitConstantPool - Print to the current output stream assembly
1166 /// representations of the constants in the constant pool MCP. This is
1167 /// used to print out constants which have been "spilled to memory" by
1168 /// the code generator.
1170 void AsmPrinter::EmitConstantPool() {
1171 const MachineConstantPool *MCP = MF->getConstantPool();
1172 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1173 if (CP.empty()) return;
1175 // Calculate sections for constant pool entries. We collect entries to go into
1176 // the same section together to reduce amount of section switch statements.
1177 SmallVector<SectionCPs, 4> CPSections;
1178 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1179 const MachineConstantPoolEntry &CPE = CP[i];
1180 unsigned Align = CPE.getAlignment();
1183 switch (CPE.getRelocationInfo()) {
1184 default: llvm_unreachable("Unknown section kind");
1185 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
1187 Kind = SectionKind::getReadOnlyWithRelLocal();
1190 switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) {
1191 case 4: Kind = SectionKind::getMergeableConst4(); break;
1192 case 8: Kind = SectionKind::getMergeableConst8(); break;
1193 case 16: Kind = SectionKind::getMergeableConst16();break;
1194 default: Kind = SectionKind::getMergeableConst(); break;
1198 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
1200 // The number of sections are small, just do a linear search from the
1201 // last section to the first.
1203 unsigned SecIdx = CPSections.size();
1204 while (SecIdx != 0) {
1205 if (CPSections[--SecIdx].S == S) {
1211 SecIdx = CPSections.size();
1212 CPSections.push_back(SectionCPs(S, Align));
1215 if (Align > CPSections[SecIdx].Alignment)
1216 CPSections[SecIdx].Alignment = Align;
1217 CPSections[SecIdx].CPEs.push_back(i);
1220 // Now print stuff into the calculated sections.
1221 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1222 OutStreamer.SwitchSection(CPSections[i].S);
1223 EmitAlignment(Log2_32(CPSections[i].Alignment));
1225 unsigned Offset = 0;
1226 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1227 unsigned CPI = CPSections[i].CPEs[j];
1228 MachineConstantPoolEntry CPE = CP[CPI];
1230 // Emit inter-object padding for alignment.
1231 unsigned AlignMask = CPE.getAlignment() - 1;
1232 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1233 OutStreamer.EmitZeros(NewOffset - Offset);
1235 Type *Ty = CPE.getType();
1236 Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
1237 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1239 if (CPE.isMachineConstantPoolEntry())
1240 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1242 EmitGlobalConstant(CPE.Val.ConstVal);
1247 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1248 /// by the current function to the current output stream.
1250 void AsmPrinter::EmitJumpTableInfo() {
1251 const DataLayout *DL = MF->getTarget().getDataLayout();
1252 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1253 if (MJTI == 0) return;
1254 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1255 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1256 if (JT.empty()) return;
1258 // Pick the directive to use to print the jump table entries, and switch to
1259 // the appropriate section.
1260 const Function *F = MF->getFunction();
1261 bool JTInDiffSection = false;
1262 if (// In PIC mode, we need to emit the jump table to the same section as the
1263 // function body itself, otherwise the label differences won't make sense.
1264 // FIXME: Need a better predicate for this: what about custom entries?
1265 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1266 // We should also do if the section name is NULL or function is declared
1267 // in discardable section
1268 // FIXME: this isn't the right predicate, should be based on the MCSection
1269 // for the function.
1270 F->isWeakForLinker()) {
1271 OutStreamer.SwitchSection(
1272 getObjFileLowering().SectionForGlobal(F, *Mang, TM));
1274 // Otherwise, drop it in the readonly section.
1275 const MCSection *ReadOnlySection =
1276 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1277 OutStreamer.SwitchSection(ReadOnlySection);
1278 JTInDiffSection = true;
1281 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
1283 // Jump tables in code sections are marked with a data_region directive
1284 // where that's supported.
1285 if (!JTInDiffSection)
1286 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1288 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1289 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1291 // If this jump table was deleted, ignore it.
1292 if (JTBBs.empty()) continue;
1294 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1295 // .set directive for each unique entry. This reduces the number of
1296 // relocations the assembler will generate for the jump table.
1297 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1298 MAI->hasSetDirective()) {
1299 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1300 const TargetLowering *TLI = TM.getTargetLowering();
1301 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1302 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1303 const MachineBasicBlock *MBB = JTBBs[ii];
1304 if (!EmittedSets.insert(MBB)) continue;
1306 // .set LJTSet, LBB32-base
1308 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1309 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1310 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1314 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1315 // before each jump table. The first label is never referenced, but tells
1316 // the assembler and linker the extents of the jump table object. The
1317 // second label is actually referenced by the code.
1318 if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
1319 // FIXME: This doesn't have to have any specific name, just any randomly
1320 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1321 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1323 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1325 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1326 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1328 if (!JTInDiffSection)
1329 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1332 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1334 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1335 const MachineBasicBlock *MBB,
1336 unsigned UID) const {
1337 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1338 const MCExpr *Value = 0;
1339 switch (MJTI->getEntryKind()) {
1340 case MachineJumpTableInfo::EK_Inline:
1341 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1342 case MachineJumpTableInfo::EK_Custom32:
1343 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1346 case MachineJumpTableInfo::EK_BlockAddress:
1347 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1349 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1351 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1352 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1353 // with a relocation as gp-relative, e.g.:
1355 MCSymbol *MBBSym = MBB->getSymbol();
1356 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1360 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1361 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1362 // with a relocation as gp-relative, e.g.:
1364 MCSymbol *MBBSym = MBB->getSymbol();
1365 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1369 case MachineJumpTableInfo::EK_LabelDifference32: {
1370 // EK_LabelDifference32 - Each entry is the address of the block minus
1371 // the address of the jump table. This is used for PIC jump tables where
1372 // gprel32 is not supported. e.g.:
1373 // .word LBB123 - LJTI1_2
1374 // If the .set directive is supported, this is emitted as:
1375 // .set L4_5_set_123, LBB123 - LJTI1_2
1376 // .word L4_5_set_123
1378 // If we have emitted set directives for the jump table entries, print
1379 // them rather than the entries themselves. If we're emitting PIC, then
1380 // emit the table entries as differences between two text section labels.
1381 if (MAI->hasSetDirective()) {
1382 // If we used .set, reference the .set's symbol.
1383 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1387 // Otherwise, use the difference as the jump table entry.
1388 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1389 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1390 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1395 assert(Value && "Unknown entry kind!");
1397 unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
1398 OutStreamer.EmitValue(Value, EntrySize);
1402 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1403 /// special global used by LLVM. If so, emit it and return true, otherwise
1404 /// do nothing and return false.
1405 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1406 if (GV->getName() == "llvm.used") {
1407 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1408 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1412 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1413 if (GV->getSection() == "llvm.metadata" ||
1414 GV->hasAvailableExternallyLinkage())
1417 if (!GV->hasAppendingLinkage()) return false;
1419 assert(GV->hasInitializer() && "Not a special LLVM global!");
1421 if (GV->getName() == "llvm.global_ctors") {
1422 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1424 if (TM.getRelocationModel() == Reloc::Static &&
1425 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1426 StringRef Sym(".constructors_used");
1427 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1433 if (GV->getName() == "llvm.global_dtors") {
1434 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1436 if (TM.getRelocationModel() == Reloc::Static &&
1437 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1438 StringRef Sym(".destructors_used");
1439 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1448 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1449 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1450 /// is true, as being used with this directive.
1451 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1452 // Should be an array of 'i8*'.
1453 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1454 const GlobalValue *GV =
1455 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1457 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1461 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1463 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1464 // Should be an array of '{ int, void ()* }' structs. The first value is the
1466 if (!isa<ConstantArray>(List)) return;
1468 // Sanity check the structors list.
1469 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1470 if (!InitList) return; // Not an array!
1471 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1472 if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1473 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1474 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1476 // Gather the structors in a form that's convenient for sorting by priority.
1477 typedef std::pair<unsigned, Constant *> Structor;
1478 SmallVector<Structor, 8> Structors;
1479 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1480 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1481 if (!CS) continue; // Malformed.
1482 if (CS->getOperand(1)->isNullValue())
1483 break; // Found a null terminator, skip the rest.
1484 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1485 if (!Priority) continue; // Malformed.
1486 Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1487 CS->getOperand(1)));
1490 // Emit the function pointers in the target-specific order
1491 const DataLayout *DL = TM.getDataLayout();
1492 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1493 std::stable_sort(Structors.begin(), Structors.end(), less_first());
1494 for (unsigned i = 0, e = Structors.size(); i != e; ++i) {
1495 const MCSection *OutputSection =
1497 getObjFileLowering().getStaticCtorSection(Structors[i].first) :
1498 getObjFileLowering().getStaticDtorSection(Structors[i].first));
1499 OutStreamer.SwitchSection(OutputSection);
1500 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1501 EmitAlignment(Align);
1502 EmitXXStructor(Structors[i].second);
1506 void AsmPrinter::EmitModuleIdents(Module &M) {
1507 if (!MAI->hasIdentDirective())
1510 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1511 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1512 const MDNode *N = NMD->getOperand(i);
1513 assert(N->getNumOperands() == 1 &&
1514 "llvm.ident metadata entry can have only one operand");
1515 const MDString *S = cast<MDString>(N->getOperand(0));
1516 OutStreamer.EmitIdent(S->getString());
1521 //===--------------------------------------------------------------------===//
1522 // Emission and print routines
1525 /// EmitInt8 - Emit a byte directive and value.
1527 void AsmPrinter::EmitInt8(int Value) const {
1528 OutStreamer.EmitIntValue(Value, 1);
1531 /// EmitInt16 - Emit a short directive and value.
1533 void AsmPrinter::EmitInt16(int Value) const {
1534 OutStreamer.EmitIntValue(Value, 2);
1537 /// EmitInt32 - Emit a long directive and value.
1539 void AsmPrinter::EmitInt32(int Value) const {
1540 OutStreamer.EmitIntValue(Value, 4);
1543 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1544 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1545 /// labels. This implicitly uses .set if it is available.
1546 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1547 unsigned Size) const {
1548 // Get the Hi-Lo expression.
1549 const MCExpr *Diff =
1550 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1551 MCSymbolRefExpr::Create(Lo, OutContext),
1554 if (!MAI->hasSetDirective()) {
1555 OutStreamer.EmitValue(Diff, Size);
1559 // Otherwise, emit with .set (aka assignment).
1560 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1561 OutStreamer.EmitAssignment(SetLabel, Diff);
1562 OutStreamer.EmitSymbolValue(SetLabel, Size);
1565 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1566 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1567 /// specify the labels. This implicitly uses .set if it is available.
1568 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1570 unsigned Size) const {
1572 // Emit Hi+Offset - Lo
1573 // Get the Hi+Offset expression.
1574 const MCExpr *Plus =
1575 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1576 MCConstantExpr::Create(Offset, OutContext),
1579 // Get the Hi+Offset-Lo expression.
1580 const MCExpr *Diff =
1581 MCBinaryExpr::CreateSub(Plus,
1582 MCSymbolRefExpr::Create(Lo, OutContext),
1585 if (!MAI->hasSetDirective())
1586 OutStreamer.EmitValue(Diff, Size);
1588 // Otherwise, emit with .set (aka assignment).
1589 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1590 OutStreamer.EmitAssignment(SetLabel, Diff);
1591 OutStreamer.EmitSymbolValue(SetLabel, Size);
1595 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1596 /// where the size in bytes of the directive is specified by Size and Label
1597 /// specifies the label. This implicitly uses .set if it is available.
1598 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1600 bool IsSectionRelative) const {
1601 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1602 OutStreamer.EmitCOFFSecRel32(Label);
1606 // Emit Label+Offset (or just Label if Offset is zero)
1607 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1609 Expr = MCBinaryExpr::CreateAdd(
1610 Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
1612 OutStreamer.EmitValue(Expr, Size);
1615 //===----------------------------------------------------------------------===//
1617 // EmitAlignment - Emit an alignment directive to the specified power of
1618 // two boundary. For example, if you pass in 3 here, you will get an 8
1619 // byte alignment. If a global value is specified, and if that global has
1620 // an explicit alignment requested, it will override the alignment request
1621 // if required for correctness.
1623 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1624 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
1626 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1628 if (getCurrentSection()->getKind().isText())
1629 OutStreamer.EmitCodeAlignment(1 << NumBits);
1631 OutStreamer.EmitValueToAlignment(1 << NumBits);
1634 //===----------------------------------------------------------------------===//
1635 // Constant emission.
1636 //===----------------------------------------------------------------------===//
1638 /// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
1640 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
1641 MCContext &Ctx = AP.OutContext;
1643 if (CV->isNullValue() || isa<UndefValue>(CV))
1644 return MCConstantExpr::Create(0, Ctx);
1646 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1647 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1649 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1650 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
1652 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1653 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1655 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1657 llvm_unreachable("Unknown constant value to lower!");
1660 if (const MCExpr *RelocExpr =
1661 AP.getObjFileLowering().getExecutableRelativeSymbol(CE, *AP.Mang,
1665 switch (CE->getOpcode()) {
1667 // If the code isn't optimized, there may be outstanding folding
1668 // opportunities. Attempt to fold the expression using DataLayout as a
1669 // last resort before giving up.
1671 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
1673 return lowerConstant(C, AP);
1675 // Otherwise report the problem to the user.
1678 raw_string_ostream OS(S);
1679 OS << "Unsupported expression in static initializer: ";
1680 CE->printAsOperand(OS, /*PrintType=*/false,
1681 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1682 report_fatal_error(OS.str());
1684 case Instruction::GetElementPtr: {
1685 const DataLayout &DL = *AP.TM.getDataLayout();
1686 // Generate a symbolic expression for the byte address
1687 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1688 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1690 const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
1694 int64_t Offset = OffsetAI.getSExtValue();
1695 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1699 case Instruction::Trunc:
1700 // We emit the value and depend on the assembler to truncate the generated
1701 // expression properly. This is important for differences between
1702 // blockaddress labels. Since the two labels are in the same function, it
1703 // is reasonable to treat their delta as a 32-bit value.
1705 case Instruction::BitCast:
1706 return lowerConstant(CE->getOperand(0), AP);
1708 case Instruction::IntToPtr: {
1709 const DataLayout &DL = *AP.TM.getDataLayout();
1710 // Handle casts to pointers by changing them into casts to the appropriate
1711 // integer type. This promotes constant folding and simplifies this code.
1712 Constant *Op = CE->getOperand(0);
1713 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1715 return lowerConstant(Op, AP);
1718 case Instruction::PtrToInt: {
1719 const DataLayout &DL = *AP.TM.getDataLayout();
1720 // Support only foldable casts to/from pointers that can be eliminated by
1721 // changing the pointer to the appropriately sized integer type.
1722 Constant *Op = CE->getOperand(0);
1723 Type *Ty = CE->getType();
1725 const MCExpr *OpExpr = lowerConstant(Op, AP);
1727 // We can emit the pointer value into this slot if the slot is an
1728 // integer slot equal to the size of the pointer.
1729 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1732 // Otherwise the pointer is smaller than the resultant integer, mask off
1733 // the high bits so we are sure to get a proper truncation if the input is
1735 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1736 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1737 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1740 // The MC library also has a right-shift operator, but it isn't consistently
1741 // signed or unsigned between different targets.
1742 case Instruction::Add:
1743 case Instruction::Sub:
1744 case Instruction::Mul:
1745 case Instruction::SDiv:
1746 case Instruction::SRem:
1747 case Instruction::Shl:
1748 case Instruction::And:
1749 case Instruction::Or:
1750 case Instruction::Xor: {
1751 const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1752 const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
1753 switch (CE->getOpcode()) {
1754 default: llvm_unreachable("Unknown binary operator constant cast expr");
1755 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1756 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1757 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1758 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1759 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1760 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1761 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1762 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1763 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1769 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
1771 /// isRepeatedByteSequence - Determine whether the given value is
1772 /// composed of a repeated sequence of identical bytes and return the
1773 /// byte value. If it is not a repeated sequence, return -1.
1774 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1775 StringRef Data = V->getRawDataValues();
1776 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1778 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1779 if (Data[i] != C) return -1;
1780 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1784 /// isRepeatedByteSequence - Determine whether the given value is
1785 /// composed of a repeated sequence of identical bytes and return the
1786 /// byte value. If it is not a repeated sequence, return -1.
1787 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1789 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1790 if (CI->getBitWidth() > 64) return -1;
1792 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
1793 uint64_t Value = CI->getZExtValue();
1795 // Make sure the constant is at least 8 bits long and has a power
1796 // of 2 bit width. This guarantees the constant bit width is
1797 // always a multiple of 8 bits, avoiding issues with padding out
1798 // to Size and other such corner cases.
1799 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1801 uint8_t Byte = static_cast<uint8_t>(Value);
1803 for (unsigned i = 1; i < Size; ++i) {
1805 if (static_cast<uint8_t>(Value) != Byte) return -1;
1809 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1810 // Make sure all array elements are sequences of the same repeated
1812 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1813 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1814 if (Byte == -1) return -1;
1816 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1817 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1818 if (ThisByte == -1) return -1;
1819 if (Byte != ThisByte) return -1;
1824 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1825 return isRepeatedByteSequence(CDS);
1830 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1833 // See if we can aggregate this into a .fill, if so, emit it as such.
1834 int Value = isRepeatedByteSequence(CDS, AP.TM);
1836 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
1837 // Don't emit a 1-byte object as a .fill.
1839 return AP.OutStreamer.EmitFill(Bytes, Value);
1842 // If this can be emitted with .ascii/.asciz, emit it as such.
1843 if (CDS->isString())
1844 return AP.OutStreamer.EmitBytes(CDS->getAsString());
1846 // Otherwise, emit the values in successive locations.
1847 unsigned ElementByteSize = CDS->getElementByteSize();
1848 if (isa<IntegerType>(CDS->getElementType())) {
1849 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1851 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1852 CDS->getElementAsInteger(i));
1853 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1856 } else if (ElementByteSize == 4) {
1857 // FP Constants are printed as integer constants to avoid losing
1859 assert(CDS->getElementType()->isFloatTy());
1860 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1866 F = CDS->getElementAsFloat(i);
1868 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1869 AP.OutStreamer.EmitIntValue(I, 4);
1872 assert(CDS->getElementType()->isDoubleTy());
1873 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1879 F = CDS->getElementAsDouble(i);
1881 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1882 AP.OutStreamer.EmitIntValue(I, 8);
1886 const DataLayout &DL = *AP.TM.getDataLayout();
1887 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1888 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1889 CDS->getNumElements();
1890 if (unsigned Padding = Size - EmittedSize)
1891 AP.OutStreamer.EmitZeros(Padding);
1895 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
1896 // See if we can aggregate some values. Make sure it can be
1897 // represented as a series of bytes of the constant value.
1898 int Value = isRepeatedByteSequence(CA, AP.TM);
1901 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
1902 AP.OutStreamer.EmitFill(Bytes, Value);
1905 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1906 emitGlobalConstantImpl(CA->getOperand(i), AP);
1910 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1911 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1912 emitGlobalConstantImpl(CV->getOperand(i), AP);
1914 const DataLayout &DL = *AP.TM.getDataLayout();
1915 unsigned Size = DL.getTypeAllocSize(CV->getType());
1916 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1917 CV->getType()->getNumElements();
1918 if (unsigned Padding = Size - EmittedSize)
1919 AP.OutStreamer.EmitZeros(Padding);
1922 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
1923 // Print the fields in successive locations. Pad to align if needed!
1924 const DataLayout *DL = AP.TM.getDataLayout();
1925 unsigned Size = DL->getTypeAllocSize(CS->getType());
1926 const StructLayout *Layout = DL->getStructLayout(CS->getType());
1927 uint64_t SizeSoFar = 0;
1928 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1929 const Constant *Field = CS->getOperand(i);
1931 // Check if padding is needed and insert one or more 0s.
1932 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1933 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1934 - Layout->getElementOffset(i)) - FieldSize;
1935 SizeSoFar += FieldSize + PadSize;
1937 // Now print the actual field value.
1938 emitGlobalConstantImpl(Field, AP);
1940 // Insert padding - this may include padding to increase the size of the
1941 // current field up to the ABI size (if the struct is not packed) as well
1942 // as padding to ensure that the next field starts at the right offset.
1943 AP.OutStreamer.EmitZeros(PadSize);
1945 assert(SizeSoFar == Layout->getSizeInBytes() &&
1946 "Layout of constant struct may be incorrect!");
1949 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1950 APInt API = CFP->getValueAPF().bitcastToAPInt();
1952 // First print a comment with what we think the original floating-point value
1953 // should have been.
1954 if (AP.isVerbose()) {
1955 SmallString<8> StrVal;
1956 CFP->getValueAPF().toString(StrVal);
1958 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1959 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1962 // Now iterate through the APInt chunks, emitting them in endian-correct
1963 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1965 unsigned NumBytes = API.getBitWidth() / 8;
1966 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1967 const uint64_t *p = API.getRawData();
1969 // PPC's long double has odd notions of endianness compared to how LLVM
1970 // handles it: p[0] goes first for *big* endian on PPC.
1971 if (AP.TM.getDataLayout()->isBigEndian() != CFP->getType()->isPPC_FP128Ty()) {
1972 int Chunk = API.getNumWords() - 1;
1975 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1977 for (; Chunk >= 0; --Chunk)
1978 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1981 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1982 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1985 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
1988 // Emit the tail padding for the long double.
1989 const DataLayout &DL = *AP.TM.getDataLayout();
1990 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1991 DL.getTypeStoreSize(CFP->getType()));
1994 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
1995 const DataLayout *DL = AP.TM.getDataLayout();
1996 unsigned BitWidth = CI->getBitWidth();
1998 // Copy the value as we may massage the layout for constants whose bit width
1999 // is not a multiple of 64-bits.
2000 APInt Realigned(CI->getValue());
2001 uint64_t ExtraBits = 0;
2002 unsigned ExtraBitsSize = BitWidth & 63;
2004 if (ExtraBitsSize) {
2005 // The bit width of the data is not a multiple of 64-bits.
2006 // The extra bits are expected to be at the end of the chunk of the memory.
2008 // * Nothing to be done, just record the extra bits to emit.
2010 // * Record the extra bits to emit.
2011 // * Realign the raw data to emit the chunks of 64-bits.
2012 if (DL->isBigEndian()) {
2013 // Basically the structure of the raw data is a chunk of 64-bits cells:
2014 // 0 1 BitWidth / 64
2015 // [chunk1][chunk2] ... [chunkN].
2016 // The most significant chunk is chunkN and it should be emitted first.
2017 // However, due to the alignment issue chunkN contains useless bits.
2018 // Realign the chunks so that they contain only useless information:
2019 // ExtraBits 0 1 (BitWidth / 64) - 1
2020 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2021 ExtraBits = Realigned.getRawData()[0] &
2022 (((uint64_t)-1) >> (64 - ExtraBitsSize));
2023 Realigned = Realigned.lshr(ExtraBitsSize);
2025 ExtraBits = Realigned.getRawData()[BitWidth / 64];
2028 // We don't expect assemblers to support integer data directives
2029 // for more than 64 bits, so we emit the data in at most 64-bit
2030 // quantities at a time.
2031 const uint64_t *RawData = Realigned.getRawData();
2032 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2033 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
2034 AP.OutStreamer.EmitIntValue(Val, 8);
2037 if (ExtraBitsSize) {
2038 // Emit the extra bits after the 64-bits chunks.
2040 // Emit a directive that fills the expected size.
2041 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(CI->getType());
2042 Size -= (BitWidth / 64) * 8;
2043 assert(Size && Size * 8 >= ExtraBitsSize &&
2044 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2045 == ExtraBits && "Directive too small for extra bits.");
2046 AP.OutStreamer.EmitIntValue(ExtraBits, Size);
2050 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
2051 const DataLayout *DL = AP.TM.getDataLayout();
2052 uint64_t Size = DL->getTypeAllocSize(CV->getType());
2053 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2054 return AP.OutStreamer.EmitZeros(Size);
2056 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2063 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
2064 CI->getZExtValue());
2065 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
2068 emitGlobalConstantLargeInt(CI, AP);
2073 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2074 return emitGlobalConstantFP(CFP, AP);
2076 if (isa<ConstantPointerNull>(CV)) {
2077 AP.OutStreamer.EmitIntValue(0, Size);
2081 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2082 return emitGlobalConstantDataSequential(CDS, AP);
2084 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2085 return emitGlobalConstantArray(CVA, AP);
2087 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2088 return emitGlobalConstantStruct(CVS, AP);
2090 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2091 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2093 if (CE->getOpcode() == Instruction::BitCast)
2094 return emitGlobalConstantImpl(CE->getOperand(0), AP);
2097 // If the constant expression's size is greater than 64-bits, then we have
2098 // to emit the value in chunks. Try to constant fold the value and emit it
2100 Constant *New = ConstantFoldConstantExpression(CE, DL);
2101 if (New && New != CE)
2102 return emitGlobalConstantImpl(New, AP);
2106 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2107 return emitGlobalConstantVector(V, AP);
2109 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
2110 // thread the streamer with EmitValue.
2111 AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
2114 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2115 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
2116 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
2118 emitGlobalConstantImpl(CV, *this);
2119 else if (MAI->hasSubsectionsViaSymbols()) {
2120 // If the global has zero size, emit a single byte so that two labels don't
2121 // look like they are at the same location.
2122 OutStreamer.EmitIntValue(0, 1);
2126 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2127 // Target doesn't support this yet!
2128 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2131 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2133 OS << '+' << Offset;
2134 else if (Offset < 0)
2138 //===----------------------------------------------------------------------===//
2139 // Symbol Lowering Routines.
2140 //===----------------------------------------------------------------------===//
2142 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
2143 /// temporary label with the specified stem and unique ID.
2144 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
2145 const DataLayout *DL = TM.getDataLayout();
2146 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix()) +
2150 /// GetTempSymbol - Return an assembler temporary label with the specified
2152 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
2153 const DataLayout *DL = TM.getDataLayout();
2154 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
2159 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2160 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2163 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2164 return MMI->getAddrLabelSymbol(BB);
2167 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2168 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2169 const DataLayout *DL = TM.getDataLayout();
2170 return OutContext.GetOrCreateSymbol
2171 (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2172 + "_" + Twine(CPID));
2175 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2176 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2177 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2180 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2181 /// FIXME: privatize to AsmPrinter.
2182 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2183 const DataLayout *DL = TM.getDataLayout();
2184 return OutContext.GetOrCreateSymbol
2185 (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2186 Twine(UID) + "_set_" + Twine(MBBID));
2189 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2190 StringRef Suffix) const {
2191 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
2195 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2197 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2198 SmallString<60> NameStr;
2199 Mang->getNameWithPrefix(NameStr, Sym);
2200 return OutContext.GetOrCreateSymbol(NameStr.str());
2205 /// PrintParentLoopComment - Print comments about parent loops of this one.
2206 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2207 unsigned FunctionNumber) {
2208 if (Loop == 0) return;
2209 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2210 OS.indent(Loop->getLoopDepth()*2)
2211 << "Parent Loop BB" << FunctionNumber << "_"
2212 << Loop->getHeader()->getNumber()
2213 << " Depth=" << Loop->getLoopDepth() << '\n';
2217 /// PrintChildLoopComment - Print comments about child loops within
2218 /// the loop for this basic block, with nesting.
2219 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2220 unsigned FunctionNumber) {
2221 // Add child loop information
2222 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
2223 OS.indent((*CL)->getLoopDepth()*2)
2224 << "Child Loop BB" << FunctionNumber << "_"
2225 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
2227 PrintChildLoopComment(OS, *CL, FunctionNumber);
2231 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2232 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2233 const MachineLoopInfo *LI,
2234 const AsmPrinter &AP) {
2235 // Add loop depth information
2236 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2237 if (Loop == 0) return;
2239 MachineBasicBlock *Header = Loop->getHeader();
2240 assert(Header && "No header for loop");
2242 // If this block is not a loop header, just print out what is the loop header
2244 if (Header != &MBB) {
2245 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2246 Twine(AP.getFunctionNumber())+"_" +
2247 Twine(Loop->getHeader()->getNumber())+
2248 " Depth="+Twine(Loop->getLoopDepth()));
2252 // Otherwise, it is a loop header. Print out information about child and
2254 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2256 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2259 OS.indent(Loop->getLoopDepth()*2-2);
2264 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2266 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2270 /// EmitBasicBlockStart - This method prints the label for the specified
2271 /// MachineBasicBlock, an alignment (if present) and a comment describing
2272 /// it if appropriate.
2273 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
2274 // Emit an alignment directive for this block, if needed.
2275 if (unsigned Align = MBB->getAlignment())
2276 EmitAlignment(Align);
2278 // If the block has its address taken, emit any labels that were used to
2279 // reference the block. It is possible that there is more than one label
2280 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2281 // the references were generated.
2282 if (MBB->hasAddressTaken()) {
2283 const BasicBlock *BB = MBB->getBasicBlock();
2285 OutStreamer.AddComment("Block address taken");
2287 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
2289 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
2290 OutStreamer.EmitLabel(Syms[i]);
2293 // Print some verbose block comments.
2295 if (const BasicBlock *BB = MBB->getBasicBlock())
2297 OutStreamer.AddComment("%" + BB->getName());
2298 emitBasicBlockLoopComments(*MBB, LI, *this);
2301 // Print the main label for the block.
2302 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
2304 // NOTE: Want this comment at start of line, don't emit with AddComment.
2305 OutStreamer.emitRawComment(" BB#" + Twine(MBB->getNumber()) + ":", false);
2308 OutStreamer.EmitLabel(MBB->getSymbol());
2312 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2313 bool IsDefinition) const {
2314 MCSymbolAttr Attr = MCSA_Invalid;
2316 switch (Visibility) {
2318 case GlobalValue::HiddenVisibility:
2320 Attr = MAI->getHiddenVisibilityAttr();
2322 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2324 case GlobalValue::ProtectedVisibility:
2325 Attr = MAI->getProtectedVisibilityAttr();
2329 if (Attr != MCSA_Invalid)
2330 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2333 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2334 /// exactly one predecessor and the control transfer mechanism between
2335 /// the predecessor and this block is a fall-through.
2337 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2338 // If this is a landing pad, it isn't a fall through. If it has no preds,
2339 // then nothing falls through to it.
2340 if (MBB->isLandingPad() || MBB->pred_empty())
2343 // If there isn't exactly one predecessor, it can't be a fall through.
2344 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2346 if (PI2 != MBB->pred_end())
2349 // The predecessor has to be immediately before this block.
2350 MachineBasicBlock *Pred = *PI;
2352 if (!Pred->isLayoutSuccessor(MBB))
2355 // If the block is completely empty, then it definitely does fall through.
2359 // Check the terminators in the previous blocks
2360 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2361 IE = Pred->end(); II != IE; ++II) {
2362 MachineInstr &MI = *II;
2364 // If it is not a simple branch, we are in a table somewhere.
2365 if (!MI.isBranch() || MI.isIndirectBranch())
2368 // If we are the operands of one of the branches, this is not a fall
2369 // through. Note that targets with delay slots will usually bundle
2370 // terminators with the delay slot instruction.
2371 for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2374 if (OP->isMBB() && OP->getMBB() == MBB)
2384 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2385 if (!S->usesMetadata())
2388 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2389 gcp_map_type::iterator GCPI = GCMap.find(S);
2390 if (GCPI != GCMap.end())
2391 return GCPI->second;
2393 const char *Name = S->getName().c_str();
2395 for (GCMetadataPrinterRegistry::iterator
2396 I = GCMetadataPrinterRegistry::begin(),
2397 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2398 if (strcmp(Name, I->getName()) == 0) {
2399 GCMetadataPrinter *GMP = I->instantiate();
2401 GCMap.insert(std::make_pair(S, GMP));
2405 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2408 /// Pin vtable to this file.
2409 AsmPrinterHandler::~AsmPrinterHandler() {}