1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AsmPrinter class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "CodeViewDebug.h"
16 #include "DwarfDebug.h"
17 #include "DwarfException.h"
18 #include "WinException.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/ConstantFolding.h"
21 #include "llvm/CodeGen/Analysis.h"
22 #include "llvm/CodeGen/GCMetadataPrinter.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBundle.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/Mangler.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCContext.h"
37 #include "llvm/MC/MCExpr.h"
38 #include "llvm/MC/MCInst.h"
39 #include "llvm/MC/MCSection.h"
40 #include "llvm/MC/MCStreamer.h"
41 #include "llvm/MC/MCSymbolELF.h"
42 #include "llvm/MC/MCValue.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/Format.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Target/TargetFrameLowering.h"
49 #include "llvm/Target/TargetInstrInfo.h"
50 #include "llvm/Target/TargetLowering.h"
51 #include "llvm/Target/TargetLoweringObjectFile.h"
52 #include "llvm/Target/TargetRegisterInfo.h"
53 #include "llvm/Target/TargetSubtargetInfo.h"
54 using namespace llvm;
55
56 #define DEBUG_TYPE "asm-printer"
57
58 static const char *const DWARFGroupName = "DWARF Emission";
59 static const char *const DbgTimerName = "Debug Info Emission";
60 static const char *const EHTimerName = "DWARF Exception Writer";
61 static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables";
62
63 STATISTIC(EmittedInsts, "Number of machine instrs printed");
64
65 char AsmPrinter::ID = 0;
66
67 typedef DenseMap<GCStrategy*, std::unique_ptr<GCMetadataPrinter>> gcp_map_type;
getGCMap(void * & P)68 static gcp_map_type &getGCMap(void *&P) {
69 if (!P)
70 P = new gcp_map_type();
71 return *(gcp_map_type*)P;
72 }
73
74
75 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
76 /// value in log2 form. This rounds up to the preferred alignment if possible
77 /// and legal.
getGVAlignmentLog2(const GlobalValue * GV,const DataLayout & DL,unsigned InBits=0)78 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &DL,
79 unsigned InBits = 0) {
80 unsigned NumBits = 0;
81 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
82 NumBits = DL.getPreferredAlignmentLog(GVar);
83
84 // If InBits is specified, round it to it.
85 if (InBits > NumBits)
86 NumBits = InBits;
87
88 // If the GV has a specified alignment, take it into account.
89 if (GV->getAlignment() == 0)
90 return NumBits;
91
92 unsigned GVAlign = Log2_32(GV->getAlignment());
93
94 // If the GVAlign is larger than NumBits, or if we are required to obey
95 // NumBits because the GV has an assigned section, obey it.
96 if (GVAlign > NumBits || GV->hasSection())
97 NumBits = GVAlign;
98 return NumBits;
99 }
100
AsmPrinter(TargetMachine & tm,std::unique_ptr<MCStreamer> Streamer)101 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
102 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
103 OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)),
104 LastMI(nullptr), LastFn(0), Counter(~0U) {
105 DD = nullptr;
106 MMI = nullptr;
107 LI = nullptr;
108 MF = nullptr;
109 CurExceptionSym = CurrentFnSym = CurrentFnSymForSize = nullptr;
110 CurrentFnBegin = nullptr;
111 CurrentFnEnd = nullptr;
112 GCMetadataPrinters = nullptr;
113 VerboseAsm = OutStreamer->isVerboseAsm();
114 }
115
~AsmPrinter()116 AsmPrinter::~AsmPrinter() {
117 assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
118
119 if (GCMetadataPrinters) {
120 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
121
122 delete &GCMap;
123 GCMetadataPrinters = nullptr;
124 }
125 }
126
isPositionIndependent() const127 bool AsmPrinter::isPositionIndependent() const {
128 return TM.isPositionIndependent();
129 }
130
131 /// getFunctionNumber - Return a unique ID for the current function.
132 ///
getFunctionNumber() const133 unsigned AsmPrinter::getFunctionNumber() const {
134 return MF->getFunctionNumber();
135 }
136
getObjFileLowering() const137 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
138 return *TM.getObjFileLowering();
139 }
140
getDataLayout() const141 const DataLayout &AsmPrinter::getDataLayout() const {
142 return MMI->getModule()->getDataLayout();
143 }
144
145 // Do not use the cached DataLayout because some client use it without a Module
146 // (llmv-dsymutil, llvm-dwarfdump).
getPointerSize() const147 unsigned AsmPrinter::getPointerSize() const { return TM.getPointerSize(); }
148
getSubtargetInfo() const149 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
150 assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
151 return MF->getSubtarget<MCSubtargetInfo>();
152 }
153
EmitToStreamer(MCStreamer & S,const MCInst & Inst)154 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
155 S.EmitInstruction(Inst, getSubtargetInfo());
156 }
157
getTargetTriple() const158 StringRef AsmPrinter::getTargetTriple() const {
159 return TM.getTargetTriple().str();
160 }
161
162 /// getCurrentSection() - Return the current section we are emitting to.
getCurrentSection() const163 const MCSection *AsmPrinter::getCurrentSection() const {
164 return OutStreamer->getCurrentSection().first;
165 }
166
167
168
getAnalysisUsage(AnalysisUsage & AU) const169 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
170 AU.setPreservesAll();
171 MachineFunctionPass::getAnalysisUsage(AU);
172 AU.addRequired<MachineModuleInfo>();
173 AU.addRequired<GCModuleInfo>();
174 if (isVerbose())
175 AU.addRequired<MachineLoopInfo>();
176 }
177
doInitialization(Module & M)178 bool AsmPrinter::doInitialization(Module &M) {
179 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
180
181 // Initialize TargetLoweringObjectFile.
182 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
183 .Initialize(OutContext, TM);
184
185 OutStreamer->InitSections(false);
186
187 Mang = new Mangler();
188
189 // Emit the version-min deplyment target directive if needed.
190 //
191 // FIXME: If we end up with a collection of these sorts of Darwin-specific
192 // or ELF-specific things, it may make sense to have a platform helper class
193 // that will work with the target helper class. For now keep it here, as the
194 // alternative is duplicated code in each of the target asm printers that
195 // use the directive, where it would need the same conditionalization
196 // anyway.
197 Triple TT(getTargetTriple());
198 // If there is a version specified, Major will be non-zero.
199 if (TT.isOSDarwin() && TT.getOSMajorVersion() != 0) {
200 unsigned Major, Minor, Update;
201 MCVersionMinType VersionType;
202 if (TT.isWatchOS()) {
203 VersionType = MCVM_WatchOSVersionMin;
204 TT.getWatchOSVersion(Major, Minor, Update);
205 } else if (TT.isTvOS()) {
206 VersionType = MCVM_TvOSVersionMin;
207 TT.getiOSVersion(Major, Minor, Update);
208 } else if (TT.isMacOSX()) {
209 VersionType = MCVM_OSXVersionMin;
210 if (!TT.getMacOSXVersion(Major, Minor, Update))
211 Major = 0;
212 } else {
213 VersionType = MCVM_IOSVersionMin;
214 TT.getiOSVersion(Major, Minor, Update);
215 }
216 if (Major != 0)
217 OutStreamer->EmitVersionMin(VersionType, Major, Minor, Update);
218 }
219
220 // Allow the target to emit any magic that it wants at the start of the file.
221 EmitStartOfAsmFile(M);
222
223 // Very minimal debug info. It is ignored if we emit actual debug info. If we
224 // don't, this at least helps the user find where a global came from.
225 if (MAI->hasSingleParameterDotFile()) {
226 // .file "foo.c"
227 OutStreamer->EmitFileDirective(M.getModuleIdentifier());
228 }
229
230 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
231 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
232 for (auto &I : *MI)
233 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
234 MP->beginAssembly(M, *MI, *this);
235
236 // Emit module-level inline asm if it exists.
237 if (!M.getModuleInlineAsm().empty()) {
238 // We're at the module level. Construct MCSubtarget from the default CPU
239 // and target triple.
240 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
241 TM.getTargetTriple().str(), TM.getTargetCPU(),
242 TM.getTargetFeatureString()));
243 OutStreamer->AddComment("Start of file scope inline assembly");
244 OutStreamer->AddBlankLine();
245 EmitInlineAsm(M.getModuleInlineAsm()+"\n",
246 OutContext.getSubtargetCopy(*STI), TM.Options.MCOptions);
247 OutStreamer->AddComment("End of file scope inline assembly");
248 OutStreamer->AddBlankLine();
249 }
250
251 if (MAI->doesSupportDebugInformation()) {
252 bool EmitCodeView = MMI->getModule()->getCodeViewFlag();
253 if (EmitCodeView && TM.getTargetTriple().isKnownWindowsMSVCEnvironment()) {
254 Handlers.push_back(HandlerInfo(new CodeViewDebug(this),
255 DbgTimerName,
256 CodeViewLineTablesGroupName));
257 }
258 if (!EmitCodeView || MMI->getModule()->getDwarfVersion()) {
259 DD = new DwarfDebug(this, &M);
260 DD->beginModule();
261 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
262 }
263 }
264
265 EHStreamer *ES = nullptr;
266 switch (MAI->getExceptionHandlingType()) {
267 case ExceptionHandling::None:
268 break;
269 case ExceptionHandling::SjLj:
270 case ExceptionHandling::DwarfCFI:
271 ES = new DwarfCFIException(this);
272 break;
273 case ExceptionHandling::ARM:
274 ES = new ARMException(this);
275 break;
276 case ExceptionHandling::WinEH:
277 switch (MAI->getWinEHEncodingType()) {
278 default: llvm_unreachable("unsupported unwinding information encoding");
279 case WinEH::EncodingType::Invalid:
280 break;
281 case WinEH::EncodingType::X86:
282 case WinEH::EncodingType::Itanium:
283 ES = new WinException(this);
284 break;
285 }
286 break;
287 }
288 if (ES)
289 Handlers.push_back(HandlerInfo(ES, EHTimerName, DWARFGroupName));
290 return false;
291 }
292
canBeHidden(const GlobalValue * GV,const MCAsmInfo & MAI)293 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
294 if (!MAI.hasWeakDefCanBeHiddenDirective())
295 return false;
296
297 return canBeOmittedFromSymbolTable(GV);
298 }
299
EmitLinkage(const GlobalValue * GV,MCSymbol * GVSym) const300 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
301 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
302 switch (Linkage) {
303 case GlobalValue::CommonLinkage:
304 case GlobalValue::LinkOnceAnyLinkage:
305 case GlobalValue::LinkOnceODRLinkage:
306 case GlobalValue::WeakAnyLinkage:
307 case GlobalValue::WeakODRLinkage:
308 if (MAI->hasWeakDefDirective()) {
309 // .globl _foo
310 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
311
312 if (!canBeHidden(GV, *MAI))
313 // .weak_definition _foo
314 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
315 else
316 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
317 } else if (MAI->hasLinkOnceDirective()) {
318 // .globl _foo
319 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
320 //NOTE: linkonce is handled by the section the symbol was assigned to.
321 } else {
322 // .weak _foo
323 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak);
324 }
325 return;
326 case GlobalValue::ExternalLinkage:
327 // If external, declare as a global symbol: .globl _foo
328 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
329 return;
330 case GlobalValue::PrivateLinkage:
331 case GlobalValue::InternalLinkage:
332 return;
333 case GlobalValue::AppendingLinkage:
334 case GlobalValue::AvailableExternallyLinkage:
335 case GlobalValue::ExternalWeakLinkage:
336 llvm_unreachable("Should never emit this");
337 }
338 llvm_unreachable("Unknown linkage type!");
339 }
340
getNameWithPrefix(SmallVectorImpl<char> & Name,const GlobalValue * GV) const341 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
342 const GlobalValue *GV) const {
343 TM.getNameWithPrefix(Name, GV, *Mang);
344 }
345
getSymbol(const GlobalValue * GV) const346 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
347 return TM.getSymbol(GV, *Mang);
348 }
349
350 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
EmitGlobalVariable(const GlobalVariable * GV)351 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
352 bool IsEmuTLSVar = TM.Options.EmulatedTLS && GV->isThreadLocal();
353 assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
354 "No emulated TLS variables in the common section");
355
356 // Never emit TLS variable xyz in emulated TLS model.
357 // The initialization value is in __emutls_t.xyz instead of xyz.
358 if (IsEmuTLSVar)
359 return;
360
361 if (GV->hasInitializer()) {
362 // Check to see if this is a special global used by LLVM, if so, emit it.
363 if (EmitSpecialLLVMGlobal(GV))
364 return;
365
366 // Skip the emission of global equivalents. The symbol can be emitted later
367 // on by emitGlobalGOTEquivs in case it turns out to be needed.
368 if (GlobalGOTEquivs.count(getSymbol(GV)))
369 return;
370
371 if (isVerbose()) {
372 // When printing the control variable __emutls_v.*,
373 // we don't need to print the original TLS variable name.
374 GV->printAsOperand(OutStreamer->GetCommentOS(),
375 /*PrintType=*/false, GV->getParent());
376 OutStreamer->GetCommentOS() << '\n';
377 }
378 }
379
380 MCSymbol *GVSym = getSymbol(GV);
381 MCSymbol *EmittedSym = GVSym;
382
383 // getOrCreateEmuTLSControlSym only creates the symbol with name and default
384 // attributes.
385 // GV's or GVSym's attributes will be used for the EmittedSym.
386 EmitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
387
388 if (!GV->hasInitializer()) // External globals require no extra code.
389 return;
390
391 GVSym->redefineIfPossible();
392 if (GVSym->isDefined() || GVSym->isVariable())
393 report_fatal_error("symbol '" + Twine(GVSym->getName()) +
394 "' is already defined");
395
396 if (MAI->hasDotTypeDotSizeDirective())
397 OutStreamer->EmitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
398
399 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
400
401 const DataLayout &DL = GV->getParent()->getDataLayout();
402 uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
403
404 // If the alignment is specified, we *must* obey it. Overaligning a global
405 // with a specified alignment is a prompt way to break globals emitted to
406 // sections and expected to be contiguous (e.g. ObjC metadata).
407 unsigned AlignLog = getGVAlignmentLog2(GV, DL);
408
409 for (const HandlerInfo &HI : Handlers) {
410 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
411 HI.Handler->setSymbolSize(GVSym, Size);
412 }
413
414 // Handle common symbols
415 if (GVKind.isCommon()) {
416 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
417 unsigned Align = 1 << AlignLog;
418 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
419 Align = 0;
420
421 // .comm _foo, 42, 4
422 OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
423 return;
424 }
425
426 // Determine to which section this global should be emitted.
427 MCSection *TheSection =
428 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
429
430 // If we have a bss global going to a section that supports the
431 // zerofill directive, do so here.
432 if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() &&
433 TheSection->isVirtualSection()) {
434 if (Size == 0)
435 Size = 1; // zerofill of 0 bytes is undefined.
436 unsigned Align = 1 << AlignLog;
437 EmitLinkage(GV, GVSym);
438 // .zerofill __DATA, __bss, _foo, 400, 5
439 OutStreamer->EmitZerofill(TheSection, GVSym, Size, Align);
440 return;
441 }
442
443 // If this is a BSS local symbol and we are emitting in the BSS
444 // section use .lcomm/.comm directive.
445 if (GVKind.isBSSLocal() &&
446 getObjFileLowering().getBSSSection() == TheSection) {
447 if (Size == 0)
448 Size = 1; // .comm Foo, 0 is undefined, avoid it.
449 unsigned Align = 1 << AlignLog;
450
451 // Use .lcomm only if it supports user-specified alignment.
452 // Otherwise, while it would still be correct to use .lcomm in some
453 // cases (e.g. when Align == 1), the external assembler might enfore
454 // some -unknown- default alignment behavior, which could cause
455 // spurious differences between external and integrated assembler.
456 // Prefer to simply fall back to .local / .comm in this case.
457 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
458 // .lcomm _foo, 42
459 OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Align);
460 return;
461 }
462
463 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
464 Align = 0;
465
466 // .local _foo
467 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local);
468 // .comm _foo, 42, 4
469 OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
470 return;
471 }
472
473 // Handle thread local data for mach-o which requires us to output an
474 // additional structure of data and mangle the original symbol so that we
475 // can reference it later.
476 //
477 // TODO: This should become an "emit thread local global" method on TLOF.
478 // All of this macho specific stuff should be sunk down into TLOFMachO and
479 // stuff like "TLSExtraDataSection" should no longer be part of the parent
480 // TLOF class. This will also make it more obvious that stuff like
481 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
482 // specific code.
483 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
484 // Emit the .tbss symbol
485 MCSymbol *MangSym =
486 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
487
488 if (GVKind.isThreadBSS()) {
489 TheSection = getObjFileLowering().getTLSBSSSection();
490 OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
491 } else if (GVKind.isThreadData()) {
492 OutStreamer->SwitchSection(TheSection);
493
494 EmitAlignment(AlignLog, GV);
495 OutStreamer->EmitLabel(MangSym);
496
497 EmitGlobalConstant(GV->getParent()->getDataLayout(),
498 GV->getInitializer());
499 }
500
501 OutStreamer->AddBlankLine();
502
503 // Emit the variable struct for the runtime.
504 MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
505
506 OutStreamer->SwitchSection(TLVSect);
507 // Emit the linkage here.
508 EmitLinkage(GV, GVSym);
509 OutStreamer->EmitLabel(GVSym);
510
511 // Three pointers in size:
512 // - __tlv_bootstrap - used to make sure support exists
513 // - spare pointer, used when mapped by the runtime
514 // - pointer to mangled symbol above with initializer
515 unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
516 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
517 PtrSize);
518 OutStreamer->EmitIntValue(0, PtrSize);
519 OutStreamer->EmitSymbolValue(MangSym, PtrSize);
520
521 OutStreamer->AddBlankLine();
522 return;
523 }
524
525 MCSymbol *EmittedInitSym = GVSym;
526
527 OutStreamer->SwitchSection(TheSection);
528
529 EmitLinkage(GV, EmittedInitSym);
530 EmitAlignment(AlignLog, GV);
531
532 OutStreamer->EmitLabel(EmittedInitSym);
533
534 EmitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
535
536 if (MAI->hasDotTypeDotSizeDirective())
537 // .size foo, 42
538 OutStreamer->emitELFSize(cast<MCSymbolELF>(EmittedInitSym),
539 MCConstantExpr::create(Size, OutContext));
540
541 OutStreamer->AddBlankLine();
542 }
543
544 /// EmitFunctionHeader - This method emits the header for the current
545 /// function.
EmitFunctionHeader()546 void AsmPrinter::EmitFunctionHeader() {
547 // Print out constants referenced by the function
548 EmitConstantPool();
549
550 // Print the 'header' of function.
551 const Function *F = MF->getFunction();
552
553 OutStreamer->SwitchSection(
554 getObjFileLowering().SectionForGlobal(F, *Mang, TM));
555 EmitVisibility(CurrentFnSym, F->getVisibility());
556
557 EmitLinkage(F, CurrentFnSym);
558 if (MAI->hasFunctionAlignment())
559 EmitAlignment(MF->getAlignment(), F);
560
561 if (MAI->hasDotTypeDotSizeDirective())
562 OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
563
564 if (isVerbose()) {
565 F->printAsOperand(OutStreamer->GetCommentOS(),
566 /*PrintType=*/false, F->getParent());
567 OutStreamer->GetCommentOS() << '\n';
568 }
569
570 // Emit the prefix data.
571 if (F->hasPrefixData())
572 EmitGlobalConstant(F->getParent()->getDataLayout(), F->getPrefixData());
573
574 // Emit the CurrentFnSym. This is a virtual function to allow targets to
575 // do their wild and crazy things as required.
576 EmitFunctionEntryLabel();
577
578 // If the function had address-taken blocks that got deleted, then we have
579 // references to the dangling symbols. Emit them at the start of the function
580 // so that we don't get references to undefined symbols.
581 std::vector<MCSymbol*> DeadBlockSyms;
582 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
583 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
584 OutStreamer->AddComment("Address taken block that was later removed");
585 OutStreamer->EmitLabel(DeadBlockSyms[i]);
586 }
587
588 if (CurrentFnBegin) {
589 if (MAI->useAssignmentForEHBegin()) {
590 MCSymbol *CurPos = OutContext.createTempSymbol();
591 OutStreamer->EmitLabel(CurPos);
592 OutStreamer->EmitAssignment(CurrentFnBegin,
593 MCSymbolRefExpr::create(CurPos, OutContext));
594 } else {
595 OutStreamer->EmitLabel(CurrentFnBegin);
596 }
597 }
598
599 // Emit pre-function debug and/or EH information.
600 for (const HandlerInfo &HI : Handlers) {
601 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
602 HI.Handler->beginFunction(MF);
603 }
604
605 // Emit the prologue data.
606 if (F->hasPrologueData())
607 EmitGlobalConstant(F->getParent()->getDataLayout(), F->getPrologueData());
608 }
609
610 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
611 /// function. This can be overridden by targets as required to do custom stuff.
EmitFunctionEntryLabel()612 void AsmPrinter::EmitFunctionEntryLabel() {
613 CurrentFnSym->redefineIfPossible();
614
615 // The function label could have already been emitted if two symbols end up
616 // conflicting due to asm renaming. Detect this and emit an error.
617 if (CurrentFnSym->isVariable())
618 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
619 "' is a protected alias");
620 if (CurrentFnSym->isDefined())
621 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
622 "' label emitted multiple times to assembly file");
623
624 return OutStreamer->EmitLabel(CurrentFnSym);
625 }
626
627 /// emitComments - Pretty-print comments for instructions.
emitComments(const MachineInstr & MI,raw_ostream & CommentOS)628 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
629 const MachineFunction *MF = MI.getParent()->getParent();
630 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
631
632 // Check for spills and reloads
633 int FI;
634
635 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
636
637 // We assume a single instruction only has a spill or reload, not
638 // both.
639 const MachineMemOperand *MMO;
640 if (TII->isLoadFromStackSlotPostFE(MI, FI)) {
641 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
642 MMO = *MI.memoperands_begin();
643 CommentOS << MMO->getSize() << "-byte Reload\n";
644 }
645 } else if (TII->hasLoadFromStackSlot(MI, MMO, FI)) {
646 if (FrameInfo->isSpillSlotObjectIndex(FI))
647 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
648 } else if (TII->isStoreToStackSlotPostFE(MI, FI)) {
649 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
650 MMO = *MI.memoperands_begin();
651 CommentOS << MMO->getSize() << "-byte Spill\n";
652 }
653 } else if (TII->hasStoreToStackSlot(MI, MMO, FI)) {
654 if (FrameInfo->isSpillSlotObjectIndex(FI))
655 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
656 }
657
658 // Check for spill-induced copies
659 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
660 CommentOS << " Reload Reuse\n";
661 }
662
663 /// emitImplicitDef - This method emits the specified machine instruction
664 /// that is an implicit def.
emitImplicitDef(const MachineInstr * MI) const665 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
666 unsigned RegNo = MI->getOperand(0).getReg();
667
668 SmallString<128> Str;
669 raw_svector_ostream OS(Str);
670 OS << "implicit-def: "
671 << PrintReg(RegNo, MF->getSubtarget().getRegisterInfo());
672
673 OutStreamer->AddComment(OS.str());
674 OutStreamer->AddBlankLine();
675 }
676
emitKill(const MachineInstr * MI,AsmPrinter & AP)677 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
678 std::string Str;
679 raw_string_ostream OS(Str);
680 OS << "kill:";
681 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
682 const MachineOperand &Op = MI->getOperand(i);
683 assert(Op.isReg() && "KILL instruction must have only register operands");
684 OS << ' '
685 << PrintReg(Op.getReg(),
686 AP.MF->getSubtarget().getRegisterInfo())
687 << (Op.isDef() ? "<def>" : "<kill>");
688 }
689 AP.OutStreamer->AddComment(OS.str());
690 AP.OutStreamer->AddBlankLine();
691 }
692
693 /// emitDebugValueComment - This method handles the target-independent form
694 /// of DBG_VALUE, returning true if it was able to do so. A false return
695 /// means the target will need to handle MI in EmitInstruction.
emitDebugValueComment(const MachineInstr * MI,AsmPrinter & AP)696 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
697 // This code handles only the 4-operand target-independent form.
698 if (MI->getNumOperands() != 4)
699 return false;
700
701 SmallString<128> Str;
702 raw_svector_ostream OS(Str);
703 OS << "DEBUG_VALUE: ";
704
705 const DILocalVariable *V = MI->getDebugVariable();
706 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
707 StringRef Name = SP->getDisplayName();
708 if (!Name.empty())
709 OS << Name << ":";
710 }
711 OS << V->getName();
712
713 const DIExpression *Expr = MI->getDebugExpression();
714 if (Expr->isBitPiece())
715 OS << " [bit_piece offset=" << Expr->getBitPieceOffset()
716 << " size=" << Expr->getBitPieceSize() << "]";
717 OS << " <- ";
718
719 // The second operand is only an offset if it's an immediate.
720 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
721 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
722
723 for (unsigned i = 0; i < Expr->getNumElements(); ++i) {
724 if (Deref) {
725 // We currently don't support extra Offsets or derefs after the first
726 // one. Bail out early instead of emitting an incorrect comment
727 OS << " [complex expression]";
728 AP.OutStreamer->emitRawComment(OS.str());
729 return true;
730 }
731 uint64_t Op = Expr->getElement(i);
732 if (Op == dwarf::DW_OP_deref) {
733 Deref = true;
734 continue;
735 } else if (Op == dwarf::DW_OP_bit_piece) {
736 // There can't be any operands after this in a valid expression
737 break;
738 }
739 uint64_t ExtraOffset = Expr->getElement(i++);
740 if (Op == dwarf::DW_OP_plus)
741 Offset += ExtraOffset;
742 else {
743 assert(Op == dwarf::DW_OP_minus);
744 Offset -= ExtraOffset;
745 }
746 }
747
748 // Register or immediate value. Register 0 means undef.
749 if (MI->getOperand(0).isFPImm()) {
750 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
751 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
752 OS << (double)APF.convertToFloat();
753 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
754 OS << APF.convertToDouble();
755 } else {
756 // There is no good way to print long double. Convert a copy to
757 // double. Ah well, it's only a comment.
758 bool ignored;
759 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
760 &ignored);
761 OS << "(long double) " << APF.convertToDouble();
762 }
763 } else if (MI->getOperand(0).isImm()) {
764 OS << MI->getOperand(0).getImm();
765 } else if (MI->getOperand(0).isCImm()) {
766 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
767 } else {
768 unsigned Reg;
769 if (MI->getOperand(0).isReg()) {
770 Reg = MI->getOperand(0).getReg();
771 } else {
772 assert(MI->getOperand(0).isFI() && "Unknown operand type");
773 const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering();
774 Offset += TFI->getFrameIndexReference(*AP.MF,
775 MI->getOperand(0).getIndex(), Reg);
776 Deref = true;
777 }
778 if (Reg == 0) {
779 // Suppress offset, it is not meaningful here.
780 OS << "undef";
781 // NOTE: Want this comment at start of line, don't emit with AddComment.
782 AP.OutStreamer->emitRawComment(OS.str());
783 return true;
784 }
785 if (Deref)
786 OS << '[';
787 OS << PrintReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
788 }
789
790 if (Deref)
791 OS << '+' << Offset << ']';
792
793 // NOTE: Want this comment at start of line, don't emit with AddComment.
794 AP.OutStreamer->emitRawComment(OS.str());
795 return true;
796 }
797
needsCFIMoves()798 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
799 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
800 MF->getFunction()->needsUnwindTableEntry())
801 return CFI_M_EH;
802
803 if (MMI->hasDebugInfo())
804 return CFI_M_Debug;
805
806 return CFI_M_None;
807 }
808
needsSEHMoves()809 bool AsmPrinter::needsSEHMoves() {
810 return MAI->usesWindowsCFI() && MF->getFunction()->needsUnwindTableEntry();
811 }
812
emitCFIInstruction(const MachineInstr & MI)813 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
814 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
815 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
816 ExceptionHandlingType != ExceptionHandling::ARM)
817 return;
818
819 if (needsCFIMoves() == CFI_M_None)
820 return;
821
822 const MachineModuleInfo &MMI = MF->getMMI();
823 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
824 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
825 const MCCFIInstruction &CFI = Instrs[CFIIndex];
826 emitCFIInstruction(CFI);
827 }
828
emitFrameAlloc(const MachineInstr & MI)829 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
830 // The operands are the MCSymbol and the frame offset of the allocation.
831 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
832 int FrameOffset = MI.getOperand(1).getImm();
833
834 // Emit a symbol assignment.
835 OutStreamer->EmitAssignment(FrameAllocSym,
836 MCConstantExpr::create(FrameOffset, OutContext));
837 }
838
839 /// EmitFunctionBody - This method emits the body and trailer for a
840 /// function.
EmitFunctionBody()841 void AsmPrinter::EmitFunctionBody() {
842 EmitFunctionHeader();
843
844 // Emit target-specific gunk before the function body.
845 EmitFunctionBodyStart();
846
847 bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
848
849 // Print out code for the function.
850 bool HasAnyRealCode = false;
851 for (auto &MBB : *MF) {
852 // Print a label for the basic block.
853 EmitBasicBlockStart(MBB);
854 for (auto &MI : MBB) {
855
856 // Print the assembly for the instruction.
857 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
858 !MI.isDebugValue()) {
859 HasAnyRealCode = true;
860 ++EmittedInsts;
861 }
862
863 if (ShouldPrintDebugScopes) {
864 for (const HandlerInfo &HI : Handlers) {
865 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
866 TimePassesIsEnabled);
867 HI.Handler->beginInstruction(&MI);
868 }
869 }
870
871 if (isVerbose())
872 emitComments(MI, OutStreamer->GetCommentOS());
873
874 switch (MI.getOpcode()) {
875 case TargetOpcode::CFI_INSTRUCTION:
876 emitCFIInstruction(MI);
877 break;
878
879 case TargetOpcode::LOCAL_ESCAPE:
880 emitFrameAlloc(MI);
881 break;
882
883 case TargetOpcode::EH_LABEL:
884 case TargetOpcode::GC_LABEL:
885 OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol());
886 break;
887 case TargetOpcode::INLINEASM:
888 EmitInlineAsm(&MI);
889 break;
890 case TargetOpcode::DBG_VALUE:
891 if (isVerbose()) {
892 if (!emitDebugValueComment(&MI, *this))
893 EmitInstruction(&MI);
894 }
895 break;
896 case TargetOpcode::IMPLICIT_DEF:
897 if (isVerbose()) emitImplicitDef(&MI);
898 break;
899 case TargetOpcode::KILL:
900 if (isVerbose()) emitKill(&MI, *this);
901 break;
902 default:
903 EmitInstruction(&MI);
904 break;
905 }
906
907 if (ShouldPrintDebugScopes) {
908 for (const HandlerInfo &HI : Handlers) {
909 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
910 TimePassesIsEnabled);
911 HI.Handler->endInstruction();
912 }
913 }
914 }
915
916 EmitBasicBlockEnd(MBB);
917 }
918
919 // If the function is empty and the object file uses .subsections_via_symbols,
920 // then we need to emit *something* to the function body to prevent the
921 // labels from collapsing together. Just emit a noop.
922 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)) {
923 MCInst Noop;
924 MF->getSubtarget().getInstrInfo()->getNoopForMachoTarget(Noop);
925 OutStreamer->AddComment("avoids zero-length function");
926
927 // Targets can opt-out of emitting the noop here by leaving the opcode
928 // unspecified.
929 if (Noop.getOpcode())
930 OutStreamer->EmitInstruction(Noop, getSubtargetInfo());
931 }
932
933 const Function *F = MF->getFunction();
934 for (const auto &BB : *F) {
935 if (!BB.hasAddressTaken())
936 continue;
937 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
938 if (Sym->isDefined())
939 continue;
940 OutStreamer->AddComment("Address of block that was removed by CodeGen");
941 OutStreamer->EmitLabel(Sym);
942 }
943
944 // Emit target-specific gunk after the function body.
945 EmitFunctionBodyEnd();
946
947 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
948 MMI->hasEHFunclets() || MAI->hasDotTypeDotSizeDirective()) {
949 // Create a symbol for the end of function.
950 CurrentFnEnd = createTempSymbol("func_end");
951 OutStreamer->EmitLabel(CurrentFnEnd);
952 }
953
954 // If the target wants a .size directive for the size of the function, emit
955 // it.
956 if (MAI->hasDotTypeDotSizeDirective()) {
957 // We can get the size as difference between the function label and the
958 // temp label.
959 const MCExpr *SizeExp = MCBinaryExpr::createSub(
960 MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
961 MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext);
962 if (auto Sym = dyn_cast<MCSymbolELF>(CurrentFnSym))
963 OutStreamer->emitELFSize(Sym, SizeExp);
964 }
965
966 for (const HandlerInfo &HI : Handlers) {
967 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
968 HI.Handler->markFunctionEnd();
969 }
970
971 // Print out jump tables referenced by the function.
972 EmitJumpTableInfo();
973
974 // Emit post-function debug and/or EH information.
975 for (const HandlerInfo &HI : Handlers) {
976 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
977 HI.Handler->endFunction(MF);
978 }
979 MMI->EndFunction();
980
981 OutStreamer->AddBlankLine();
982 }
983
984 /// \brief Compute the number of Global Variables that uses a Constant.
getNumGlobalVariableUses(const Constant * C)985 static unsigned getNumGlobalVariableUses(const Constant *C) {
986 if (!C)
987 return 0;
988
989 if (isa<GlobalVariable>(C))
990 return 1;
991
992 unsigned NumUses = 0;
993 for (auto *CU : C->users())
994 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
995
996 return NumUses;
997 }
998
999 /// \brief Only consider global GOT equivalents if at least one user is a
1000 /// cstexpr inside an initializer of another global variables. Also, don't
1001 /// handle cstexpr inside instructions. During global variable emission,
1002 /// candidates are skipped and are emitted later in case at least one cstexpr
1003 /// isn't replaced by a PC relative GOT entry access.
isGOTEquivalentCandidate(const GlobalVariable * GV,unsigned & NumGOTEquivUsers)1004 static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
1005 unsigned &NumGOTEquivUsers) {
1006 // Global GOT equivalents are unnamed private globals with a constant
1007 // pointer initializer to another global symbol. They must point to a
1008 // GlobalVariable or Function, i.e., as GlobalValue.
1009 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
1010 !GV->isConstant() || !GV->isDiscardableIfUnused() ||
1011 !dyn_cast<GlobalValue>(GV->getOperand(0)))
1012 return false;
1013
1014 // To be a got equivalent, at least one of its users need to be a constant
1015 // expression used by another global variable.
1016 for (auto *U : GV->users())
1017 NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
1018
1019 return NumGOTEquivUsers > 0;
1020 }
1021
1022 /// \brief Unnamed constant global variables solely contaning a pointer to
1023 /// another globals variable is equivalent to a GOT table entry; it contains the
1024 /// the address of another symbol. Optimize it and replace accesses to these
1025 /// "GOT equivalents" by using the GOT entry for the final global instead.
1026 /// Compute GOT equivalent candidates among all global variables to avoid
1027 /// emitting them if possible later on, after it use is replaced by a GOT entry
1028 /// access.
computeGlobalGOTEquivs(Module & M)1029 void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
1030 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1031 return;
1032
1033 for (const auto &G : M.globals()) {
1034 unsigned NumGOTEquivUsers = 0;
1035 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
1036 continue;
1037
1038 const MCSymbol *GOTEquivSym = getSymbol(&G);
1039 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
1040 }
1041 }
1042
1043 /// \brief Constant expressions using GOT equivalent globals may not be eligible
1044 /// for PC relative GOT entry conversion, in such cases we need to emit such
1045 /// globals we previously omitted in EmitGlobalVariable.
emitGlobalGOTEquivs()1046 void AsmPrinter::emitGlobalGOTEquivs() {
1047 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1048 return;
1049
1050 SmallVector<const GlobalVariable *, 8> FailedCandidates;
1051 for (auto &I : GlobalGOTEquivs) {
1052 const GlobalVariable *GV = I.second.first;
1053 unsigned Cnt = I.second.second;
1054 if (Cnt)
1055 FailedCandidates.push_back(GV);
1056 }
1057 GlobalGOTEquivs.clear();
1058
1059 for (auto *GV : FailedCandidates)
1060 EmitGlobalVariable(GV);
1061 }
1062
emitGlobalIndirectSymbol(Module & M,const GlobalIndirectSymbol & GIS)1063 void AsmPrinter::emitGlobalIndirectSymbol(Module &M,
1064 const GlobalIndirectSymbol& GIS) {
1065 MCSymbol *Name = getSymbol(&GIS);
1066
1067 if (GIS.hasExternalLinkage() || !MAI->getWeakRefDirective())
1068 OutStreamer->EmitSymbolAttribute(Name, MCSA_Global);
1069 else if (GIS.hasWeakLinkage() || GIS.hasLinkOnceLinkage())
1070 OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference);
1071 else
1072 assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage");
1073
1074 // Set the symbol type to function if the alias has a function type.
1075 // This affects codegen when the aliasee is not a function.
1076 if (GIS.getType()->getPointerElementType()->isFunctionTy()) {
1077 OutStreamer->EmitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
1078 if (isa<GlobalIFunc>(GIS))
1079 OutStreamer->EmitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction);
1080 }
1081
1082 EmitVisibility(Name, GIS.getVisibility());
1083
1084 const MCExpr *Expr = lowerConstant(GIS.getIndirectSymbol());
1085
1086 if (isa<GlobalAlias>(&GIS) && MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr))
1087 OutStreamer->EmitSymbolAttribute(Name, MCSA_AltEntry);
1088
1089 // Emit the directives as assignments aka .set:
1090 OutStreamer->EmitAssignment(Name, Expr);
1091
1092 if (auto *GA = dyn_cast<GlobalAlias>(&GIS)) {
1093 // If the aliasee does not correspond to a symbol in the output, i.e. the
1094 // alias is not of an object or the aliased object is private, then set the
1095 // size of the alias symbol from the type of the alias. We don't do this in
1096 // other situations as the alias and aliasee having differing types but same
1097 // size may be intentional.
1098 const GlobalObject *BaseObject = GA->getBaseObject();
1099 if (MAI->hasDotTypeDotSizeDirective() && GA->getValueType()->isSized() &&
1100 (!BaseObject || BaseObject->hasPrivateLinkage())) {
1101 const DataLayout &DL = M.getDataLayout();
1102 uint64_t Size = DL.getTypeAllocSize(GA->getValueType());
1103 OutStreamer->emitELFSize(cast<MCSymbolELF>(Name),
1104 MCConstantExpr::create(Size, OutContext));
1105 }
1106 }
1107 }
1108
doFinalization(Module & M)1109 bool AsmPrinter::doFinalization(Module &M) {
1110 // Set the MachineFunction to nullptr so that we can catch attempted
1111 // accesses to MF specific features at the module level and so that
1112 // we can conditionalize accesses based on whether or not it is nullptr.
1113 MF = nullptr;
1114
1115 // Gather all GOT equivalent globals in the module. We really need two
1116 // passes over the globals: one to compute and another to avoid its emission
1117 // in EmitGlobalVariable, otherwise we would not be able to handle cases
1118 // where the got equivalent shows up before its use.
1119 computeGlobalGOTEquivs(M);
1120
1121 // Emit global variables.
1122 for (const auto &G : M.globals())
1123 EmitGlobalVariable(&G);
1124
1125 // Emit remaining GOT equivalent globals.
1126 emitGlobalGOTEquivs();
1127
1128 // Emit visibility info for declarations
1129 for (const Function &F : M) {
1130 if (!F.isDeclarationForLinker())
1131 continue;
1132 GlobalValue::VisibilityTypes V = F.getVisibility();
1133 if (V == GlobalValue::DefaultVisibility)
1134 continue;
1135
1136 MCSymbol *Name = getSymbol(&F);
1137 EmitVisibility(Name, V, false);
1138 }
1139
1140 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1141
1142 // Emit module flags.
1143 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
1144 M.getModuleFlagsMetadata(ModuleFlags);
1145 if (!ModuleFlags.empty())
1146 TLOF.emitModuleFlags(*OutStreamer, ModuleFlags, *Mang, TM);
1147
1148 if (TM.getTargetTriple().isOSBinFormatELF()) {
1149 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
1150
1151 // Output stubs for external and common global variables.
1152 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
1153 if (!Stubs.empty()) {
1154 OutStreamer->SwitchSection(TLOF.getDataSection());
1155 const DataLayout &DL = M.getDataLayout();
1156
1157 for (const auto &Stub : Stubs) {
1158 OutStreamer->EmitLabel(Stub.first);
1159 OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
1160 DL.getPointerSize());
1161 }
1162 }
1163 }
1164
1165 // Finalize debug and EH information.
1166 for (const HandlerInfo &HI : Handlers) {
1167 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
1168 TimePassesIsEnabled);
1169 HI.Handler->endModule();
1170 delete HI.Handler;
1171 }
1172 Handlers.clear();
1173 DD = nullptr;
1174
1175 // If the target wants to know about weak references, print them all.
1176 if (MAI->getWeakRefDirective()) {
1177 // FIXME: This is not lazy, it would be nice to only print weak references
1178 // to stuff that is actually used. Note that doing so would require targets
1179 // to notice uses in operands (due to constant exprs etc). This should
1180 // happen with the MC stuff eventually.
1181
1182 // Print out module-level global objects here.
1183 for (const auto &GO : M.global_objects()) {
1184 if (!GO.hasExternalWeakLinkage())
1185 continue;
1186 OutStreamer->EmitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
1187 }
1188 }
1189
1190 OutStreamer->AddBlankLine();
1191
1192 // Print aliases in topological order, that is, for each alias a = b,
1193 // b must be printed before a.
1194 // This is because on some targets (e.g. PowerPC) linker expects aliases in
1195 // such an order to generate correct TOC information.
1196 SmallVector<const GlobalAlias *, 16> AliasStack;
1197 SmallPtrSet<const GlobalAlias *, 16> AliasVisited;
1198 for (const auto &Alias : M.aliases()) {
1199 for (const GlobalAlias *Cur = &Alias; Cur;
1200 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
1201 if (!AliasVisited.insert(Cur).second)
1202 break;
1203 AliasStack.push_back(Cur);
1204 }
1205 for (const GlobalAlias *AncestorAlias : reverse(AliasStack))
1206 emitGlobalIndirectSymbol(M, *AncestorAlias);
1207 AliasStack.clear();
1208 }
1209 for (const auto &IFunc : M.ifuncs())
1210 emitGlobalIndirectSymbol(M, IFunc);
1211
1212 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1213 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1214 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1215 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1216 MP->finishAssembly(M, *MI, *this);
1217
1218 // Emit llvm.ident metadata in an '.ident' directive.
1219 EmitModuleIdents(M);
1220
1221 // Emit __morestack address if needed for indirect calls.
1222 if (MMI->usesMorestackAddr()) {
1223 unsigned Align = 1;
1224 MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
1225 getDataLayout(), SectionKind::getReadOnly(),
1226 /*C=*/nullptr, Align);
1227 OutStreamer->SwitchSection(ReadOnlySection);
1228
1229 MCSymbol *AddrSymbol =
1230 OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1231 OutStreamer->EmitLabel(AddrSymbol);
1232
1233 unsigned PtrSize = M.getDataLayout().getPointerSize(0);
1234 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1235 PtrSize);
1236 }
1237
1238 // If we don't have any trampolines, then we don't require stack memory
1239 // to be executable. Some targets have a directive to declare this.
1240 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1241 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1242 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1243 OutStreamer->SwitchSection(S);
1244
1245 // Allow the target to emit any magic that it wants at the end of the file,
1246 // after everything else has gone out.
1247 EmitEndOfAsmFile(M);
1248
1249 delete Mang; Mang = nullptr;
1250 MMI = nullptr;
1251
1252 OutStreamer->Finish();
1253 OutStreamer->reset();
1254
1255 return false;
1256 }
1257
getCurExceptionSym()1258 MCSymbol *AsmPrinter::getCurExceptionSym() {
1259 if (!CurExceptionSym)
1260 CurExceptionSym = createTempSymbol("exception");
1261 return CurExceptionSym;
1262 }
1263
SetupMachineFunction(MachineFunction & MF)1264 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1265 this->MF = &MF;
1266 // Get the function symbol.
1267 CurrentFnSym = getSymbol(MF.getFunction());
1268 CurrentFnSymForSize = CurrentFnSym;
1269 CurrentFnBegin = nullptr;
1270 CurExceptionSym = nullptr;
1271 bool NeedsLocalForSize = MAI->needsLocalForSize();
1272 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
1273 MMI->hasEHFunclets() || NeedsLocalForSize) {
1274 CurrentFnBegin = createTempSymbol("func_begin");
1275 if (NeedsLocalForSize)
1276 CurrentFnSymForSize = CurrentFnBegin;
1277 }
1278
1279 if (isVerbose())
1280 LI = &getAnalysis<MachineLoopInfo>();
1281 }
1282
1283 namespace {
1284 // Keep track the alignment, constpool entries per Section.
1285 struct SectionCPs {
1286 MCSection *S;
1287 unsigned Alignment;
1288 SmallVector<unsigned, 4> CPEs;
SectionCPs__anon82389a6e0111::SectionCPs1289 SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
1290 };
1291 }
1292
1293 /// EmitConstantPool - Print to the current output stream assembly
1294 /// representations of the constants in the constant pool MCP. This is
1295 /// used to print out constants which have been "spilled to memory" by
1296 /// the code generator.
1297 ///
EmitConstantPool()1298 void AsmPrinter::EmitConstantPool() {
1299 const MachineConstantPool *MCP = MF->getConstantPool();
1300 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1301 if (CP.empty()) return;
1302
1303 // Calculate sections for constant pool entries. We collect entries to go into
1304 // the same section together to reduce amount of section switch statements.
1305 SmallVector<SectionCPs, 4> CPSections;
1306 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1307 const MachineConstantPoolEntry &CPE = CP[i];
1308 unsigned Align = CPE.getAlignment();
1309
1310 SectionKind Kind = CPE.getSectionKind(&getDataLayout());
1311
1312 const Constant *C = nullptr;
1313 if (!CPE.isMachineConstantPoolEntry())
1314 C = CPE.Val.ConstVal;
1315
1316 MCSection *S = getObjFileLowering().getSectionForConstant(getDataLayout(),
1317 Kind, C, Align);
1318
1319 // The number of sections are small, just do a linear search from the
1320 // last section to the first.
1321 bool Found = false;
1322 unsigned SecIdx = CPSections.size();
1323 while (SecIdx != 0) {
1324 if (CPSections[--SecIdx].S == S) {
1325 Found = true;
1326 break;
1327 }
1328 }
1329 if (!Found) {
1330 SecIdx = CPSections.size();
1331 CPSections.push_back(SectionCPs(S, Align));
1332 }
1333
1334 if (Align > CPSections[SecIdx].Alignment)
1335 CPSections[SecIdx].Alignment = Align;
1336 CPSections[SecIdx].CPEs.push_back(i);
1337 }
1338
1339 // Now print stuff into the calculated sections.
1340 const MCSection *CurSection = nullptr;
1341 unsigned Offset = 0;
1342 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1343 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1344 unsigned CPI = CPSections[i].CPEs[j];
1345 MCSymbol *Sym = GetCPISymbol(CPI);
1346 if (!Sym->isUndefined())
1347 continue;
1348
1349 if (CurSection != CPSections[i].S) {
1350 OutStreamer->SwitchSection(CPSections[i].S);
1351 EmitAlignment(Log2_32(CPSections[i].Alignment));
1352 CurSection = CPSections[i].S;
1353 Offset = 0;
1354 }
1355
1356 MachineConstantPoolEntry CPE = CP[CPI];
1357
1358 // Emit inter-object padding for alignment.
1359 unsigned AlignMask = CPE.getAlignment() - 1;
1360 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1361 OutStreamer->EmitZeros(NewOffset - Offset);
1362
1363 Type *Ty = CPE.getType();
1364 Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty);
1365
1366 OutStreamer->EmitLabel(Sym);
1367 if (CPE.isMachineConstantPoolEntry())
1368 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1369 else
1370 EmitGlobalConstant(getDataLayout(), CPE.Val.ConstVal);
1371 }
1372 }
1373 }
1374
1375 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1376 /// by the current function to the current output stream.
1377 ///
EmitJumpTableInfo()1378 void AsmPrinter::EmitJumpTableInfo() {
1379 const DataLayout &DL = MF->getDataLayout();
1380 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1381 if (!MJTI) return;
1382 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1383 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1384 if (JT.empty()) return;
1385
1386 // Pick the directive to use to print the jump table entries, and switch to
1387 // the appropriate section.
1388 const Function *F = MF->getFunction();
1389 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1390 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1391 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
1392 *F);
1393 if (JTInDiffSection) {
1394 // Drop it in the readonly section.
1395 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(*F, *Mang, TM);
1396 OutStreamer->SwitchSection(ReadOnlySection);
1397 }
1398
1399 EmitAlignment(Log2_32(MJTI->getEntryAlignment(DL)));
1400
1401 // Jump tables in code sections are marked with a data_region directive
1402 // where that's supported.
1403 if (!JTInDiffSection)
1404 OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
1405
1406 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1407 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1408
1409 // If this jump table was deleted, ignore it.
1410 if (JTBBs.empty()) continue;
1411
1412 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1413 /// emit a .set directive for each unique entry.
1414 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1415 MAI->doesSetDirectiveSuppressReloc()) {
1416 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1417 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1418 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1419 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1420 const MachineBasicBlock *MBB = JTBBs[ii];
1421 if (!EmittedSets.insert(MBB).second)
1422 continue;
1423
1424 // .set LJTSet, LBB32-base
1425 const MCExpr *LHS =
1426 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1427 OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1428 MCBinaryExpr::createSub(LHS, Base,
1429 OutContext));
1430 }
1431 }
1432
1433 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1434 // before each jump table. The first label is never referenced, but tells
1435 // the assembler and linker the extents of the jump table object. The
1436 // second label is actually referenced by the code.
1437 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
1438 // FIXME: This doesn't have to have any specific name, just any randomly
1439 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1440 OutStreamer->EmitLabel(GetJTISymbol(JTI, true));
1441
1442 OutStreamer->EmitLabel(GetJTISymbol(JTI));
1443
1444 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1445 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1446 }
1447 if (!JTInDiffSection)
1448 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1449 }
1450
1451 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1452 /// current stream.
EmitJumpTableEntry(const MachineJumpTableInfo * MJTI,const MachineBasicBlock * MBB,unsigned UID) const1453 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1454 const MachineBasicBlock *MBB,
1455 unsigned UID) const {
1456 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1457 const MCExpr *Value = nullptr;
1458 switch (MJTI->getEntryKind()) {
1459 case MachineJumpTableInfo::EK_Inline:
1460 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1461 case MachineJumpTableInfo::EK_Custom32:
1462 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
1463 MJTI, MBB, UID, OutContext);
1464 break;
1465 case MachineJumpTableInfo::EK_BlockAddress:
1466 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1467 // .word LBB123
1468 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1469 break;
1470 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1471 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1472 // with a relocation as gp-relative, e.g.:
1473 // .gprel32 LBB123
1474 MCSymbol *MBBSym = MBB->getSymbol();
1475 OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1476 return;
1477 }
1478
1479 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1480 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1481 // with a relocation as gp-relative, e.g.:
1482 // .gpdword LBB123
1483 MCSymbol *MBBSym = MBB->getSymbol();
1484 OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1485 return;
1486 }
1487
1488 case MachineJumpTableInfo::EK_LabelDifference32: {
1489 // Each entry is the address of the block minus the address of the jump
1490 // table. This is used for PIC jump tables where gprel32 is not supported.
1491 // e.g.:
1492 // .word LBB123 - LJTI1_2
1493 // If the .set directive avoids relocations, this is emitted as:
1494 // .set L4_5_set_123, LBB123 - LJTI1_2
1495 // .word L4_5_set_123
1496 if (MAI->doesSetDirectiveSuppressReloc()) {
1497 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
1498 OutContext);
1499 break;
1500 }
1501 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1502 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1503 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1504 Value = MCBinaryExpr::createSub(Value, Base, OutContext);
1505 break;
1506 }
1507 }
1508
1509 assert(Value && "Unknown entry kind!");
1510
1511 unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
1512 OutStreamer->EmitValue(Value, EntrySize);
1513 }
1514
1515
1516 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1517 /// special global used by LLVM. If so, emit it and return true, otherwise
1518 /// do nothing and return false.
EmitSpecialLLVMGlobal(const GlobalVariable * GV)1519 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1520 if (GV->getName() == "llvm.used") {
1521 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1522 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1523 return true;
1524 }
1525
1526 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1527 if (GV->getSection() == "llvm.metadata" ||
1528 GV->hasAvailableExternallyLinkage())
1529 return true;
1530
1531 if (!GV->hasAppendingLinkage()) return false;
1532
1533 assert(GV->hasInitializer() && "Not a special LLVM global!");
1534
1535 if (GV->getName() == "llvm.global_ctors") {
1536 EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1537 /* isCtor */ true);
1538
1539 if (TM.getRelocationModel() == Reloc::Static &&
1540 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1541 StringRef Sym(".constructors_used");
1542 OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym),
1543 MCSA_Reference);
1544 }
1545 return true;
1546 }
1547
1548 if (GV->getName() == "llvm.global_dtors") {
1549 EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1550 /* isCtor */ false);
1551
1552 if (TM.getRelocationModel() == Reloc::Static &&
1553 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1554 StringRef Sym(".destructors_used");
1555 OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym),
1556 MCSA_Reference);
1557 }
1558 return true;
1559 }
1560
1561 report_fatal_error("unknown special variable");
1562 }
1563
1564 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1565 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1566 /// is true, as being used with this directive.
EmitLLVMUsedList(const ConstantArray * InitList)1567 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1568 // Should be an array of 'i8*'.
1569 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1570 const GlobalValue *GV =
1571 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1572 if (GV)
1573 OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1574 }
1575 }
1576
1577 namespace {
1578 struct Structor {
Structor__anon82389a6e0211::Structor1579 Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
1580 int Priority;
1581 llvm::Constant *Func;
1582 llvm::GlobalValue *ComdatKey;
1583 };
1584 } // end namespace
1585
1586 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1587 /// priority.
EmitXXStructorList(const DataLayout & DL,const Constant * List,bool isCtor)1588 void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List,
1589 bool isCtor) {
1590 // Should be an array of '{ int, void ()* }' structs. The first value is the
1591 // init priority.
1592 if (!isa<ConstantArray>(List)) return;
1593
1594 // Sanity check the structors list.
1595 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1596 if (!InitList) return; // Not an array!
1597 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1598 // FIXME: Only allow the 3-field form in LLVM 4.0.
1599 if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
1600 return; // Not an array of two or three elements!
1601 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1602 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1603 if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1604 return; // Not (int, ptr, ptr).
1605
1606 // Gather the structors in a form that's convenient for sorting by priority.
1607 SmallVector<Structor, 8> Structors;
1608 for (Value *O : InitList->operands()) {
1609 ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
1610 if (!CS) continue; // Malformed.
1611 if (CS->getOperand(1)->isNullValue())
1612 break; // Found a null terminator, skip the rest.
1613 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1614 if (!Priority) continue; // Malformed.
1615 Structors.push_back(Structor());
1616 Structor &S = Structors.back();
1617 S.Priority = Priority->getLimitedValue(65535);
1618 S.Func = CS->getOperand(1);
1619 if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
1620 S.ComdatKey =
1621 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
1622 }
1623
1624 // Emit the function pointers in the target-specific order
1625 unsigned Align = Log2_32(DL.getPointerPrefAlignment());
1626 std::stable_sort(Structors.begin(), Structors.end(),
1627 [](const Structor &L,
1628 const Structor &R) { return L.Priority < R.Priority; });
1629 for (Structor &S : Structors) {
1630 const TargetLoweringObjectFile &Obj = getObjFileLowering();
1631 const MCSymbol *KeySym = nullptr;
1632 if (GlobalValue *GV = S.ComdatKey) {
1633 if (GV->hasAvailableExternallyLinkage())
1634 // If the associated variable is available_externally, some other TU
1635 // will provide its dynamic initializer.
1636 continue;
1637
1638 KeySym = getSymbol(GV);
1639 }
1640 MCSection *OutputSection =
1641 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
1642 : Obj.getStaticDtorSection(S.Priority, KeySym));
1643 OutStreamer->SwitchSection(OutputSection);
1644 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
1645 EmitAlignment(Align);
1646 EmitXXStructor(DL, S.Func);
1647 }
1648 }
1649
EmitModuleIdents(Module & M)1650 void AsmPrinter::EmitModuleIdents(Module &M) {
1651 if (!MAI->hasIdentDirective())
1652 return;
1653
1654 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1655 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1656 const MDNode *N = NMD->getOperand(i);
1657 assert(N->getNumOperands() == 1 &&
1658 "llvm.ident metadata entry can have only one operand");
1659 const MDString *S = cast<MDString>(N->getOperand(0));
1660 OutStreamer->EmitIdent(S->getString());
1661 }
1662 }
1663 }
1664
1665 //===--------------------------------------------------------------------===//
1666 // Emission and print routines
1667 //
1668
1669 /// EmitInt8 - Emit a byte directive and value.
1670 ///
EmitInt8(int Value) const1671 void AsmPrinter::EmitInt8(int Value) const {
1672 OutStreamer->EmitIntValue(Value, 1);
1673 }
1674
1675 /// EmitInt16 - Emit a short directive and value.
1676 ///
EmitInt16(int Value) const1677 void AsmPrinter::EmitInt16(int Value) const {
1678 OutStreamer->EmitIntValue(Value, 2);
1679 }
1680
1681 /// EmitInt32 - Emit a long directive and value.
1682 ///
EmitInt32(int Value) const1683 void AsmPrinter::EmitInt32(int Value) const {
1684 OutStreamer->EmitIntValue(Value, 4);
1685 }
1686
1687 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
1688 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
1689 /// .set if it avoids relocations.
EmitLabelDifference(const MCSymbol * Hi,const MCSymbol * Lo,unsigned Size) const1690 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1691 unsigned Size) const {
1692 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
1693 }
1694
1695 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1696 /// where the size in bytes of the directive is specified by Size and Label
1697 /// specifies the label. This implicitly uses .set if it is available.
EmitLabelPlusOffset(const MCSymbol * Label,uint64_t Offset,unsigned Size,bool IsSectionRelative) const1698 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1699 unsigned Size,
1700 bool IsSectionRelative) const {
1701 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1702 OutStreamer->EmitCOFFSecRel32(Label);
1703 return;
1704 }
1705
1706 // Emit Label+Offset (or just Label if Offset is zero)
1707 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
1708 if (Offset)
1709 Expr = MCBinaryExpr::createAdd(
1710 Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
1711
1712 OutStreamer->EmitValue(Expr, Size);
1713 }
1714
1715 //===----------------------------------------------------------------------===//
1716
1717 // EmitAlignment - Emit an alignment directive to the specified power of
1718 // two boundary. For example, if you pass in 3 here, you will get an 8
1719 // byte alignment. If a global value is specified, and if that global has
1720 // an explicit alignment requested, it will override the alignment request
1721 // if required for correctness.
1722 //
EmitAlignment(unsigned NumBits,const GlobalObject * GV) const1723 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
1724 if (GV)
1725 NumBits = getGVAlignmentLog2(GV, GV->getParent()->getDataLayout(), NumBits);
1726
1727 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1728
1729 assert(NumBits <
1730 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
1731 "undefined behavior");
1732 if (getCurrentSection()->getKind().isText())
1733 OutStreamer->EmitCodeAlignment(1u << NumBits);
1734 else
1735 OutStreamer->EmitValueToAlignment(1u << NumBits);
1736 }
1737
1738 //===----------------------------------------------------------------------===//
1739 // Constant emission.
1740 //===----------------------------------------------------------------------===//
1741
lowerConstant(const Constant * CV)1742 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
1743 MCContext &Ctx = OutContext;
1744
1745 if (CV->isNullValue() || isa<UndefValue>(CV))
1746 return MCConstantExpr::create(0, Ctx);
1747
1748 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1749 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
1750
1751 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1752 return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
1753
1754 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1755 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
1756
1757 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1758 if (!CE) {
1759 llvm_unreachable("Unknown constant value to lower!");
1760 }
1761
1762 switch (CE->getOpcode()) {
1763 default:
1764 // If the code isn't optimized, there may be outstanding folding
1765 // opportunities. Attempt to fold the expression using DataLayout as a
1766 // last resort before giving up.
1767 if (Constant *C = ConstantFoldConstantExpression(CE, getDataLayout()))
1768 if (C != CE)
1769 return lowerConstant(C);
1770
1771 // Otherwise report the problem to the user.
1772 {
1773 std::string S;
1774 raw_string_ostream OS(S);
1775 OS << "Unsupported expression in static initializer: ";
1776 CE->printAsOperand(OS, /*PrintType=*/false,
1777 !MF ? nullptr : MF->getFunction()->getParent());
1778 report_fatal_error(OS.str());
1779 }
1780 case Instruction::GetElementPtr: {
1781 // Generate a symbolic expression for the byte address
1782 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
1783 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
1784
1785 const MCExpr *Base = lowerConstant(CE->getOperand(0));
1786 if (!OffsetAI)
1787 return Base;
1788
1789 int64_t Offset = OffsetAI.getSExtValue();
1790 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
1791 Ctx);
1792 }
1793
1794 case Instruction::Trunc:
1795 // We emit the value and depend on the assembler to truncate the generated
1796 // expression properly. This is important for differences between
1797 // blockaddress labels. Since the two labels are in the same function, it
1798 // is reasonable to treat their delta as a 32-bit value.
1799 // FALL THROUGH.
1800 case Instruction::BitCast:
1801 return lowerConstant(CE->getOperand(0));
1802
1803 case Instruction::IntToPtr: {
1804 const DataLayout &DL = getDataLayout();
1805
1806 // Handle casts to pointers by changing them into casts to the appropriate
1807 // integer type. This promotes constant folding and simplifies this code.
1808 Constant *Op = CE->getOperand(0);
1809 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1810 false/*ZExt*/);
1811 return lowerConstant(Op);
1812 }
1813
1814 case Instruction::PtrToInt: {
1815 const DataLayout &DL = getDataLayout();
1816
1817 // Support only foldable casts to/from pointers that can be eliminated by
1818 // changing the pointer to the appropriately sized integer type.
1819 Constant *Op = CE->getOperand(0);
1820 Type *Ty = CE->getType();
1821
1822 const MCExpr *OpExpr = lowerConstant(Op);
1823
1824 // We can emit the pointer value into this slot if the slot is an
1825 // integer slot equal to the size of the pointer.
1826 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1827 return OpExpr;
1828
1829 // Otherwise the pointer is smaller than the resultant integer, mask off
1830 // the high bits so we are sure to get a proper truncation if the input is
1831 // a constant expr.
1832 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1833 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
1834 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
1835 }
1836
1837 case Instruction::Sub: {
1838 GlobalValue *LHSGV;
1839 APInt LHSOffset;
1840 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
1841 getDataLayout())) {
1842 GlobalValue *RHSGV;
1843 APInt RHSOffset;
1844 if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
1845 getDataLayout())) {
1846 const MCExpr *RelocExpr = getObjFileLowering().lowerRelativeReference(
1847 LHSGV, RHSGV, *Mang, TM);
1848 if (!RelocExpr)
1849 RelocExpr = MCBinaryExpr::createSub(
1850 MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx),
1851 MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
1852 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
1853 if (Addend != 0)
1854 RelocExpr = MCBinaryExpr::createAdd(
1855 RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
1856 return RelocExpr;
1857 }
1858 }
1859 }
1860 // else fallthrough
1861
1862 // The MC library also has a right-shift operator, but it isn't consistently
1863 // signed or unsigned between different targets.
1864 case Instruction::Add:
1865 case Instruction::Mul:
1866 case Instruction::SDiv:
1867 case Instruction::SRem:
1868 case Instruction::Shl:
1869 case Instruction::And:
1870 case Instruction::Or:
1871 case Instruction::Xor: {
1872 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
1873 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
1874 switch (CE->getOpcode()) {
1875 default: llvm_unreachable("Unknown binary operator constant cast expr");
1876 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
1877 case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1878 case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
1879 case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
1880 case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
1881 case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
1882 case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
1883 case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx);
1884 case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
1885 }
1886 }
1887 }
1888 }
1889
1890 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
1891 AsmPrinter &AP,
1892 const Constant *BaseCV = nullptr,
1893 uint64_t Offset = 0);
1894
1895 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
1896
1897 /// isRepeatedByteSequence - Determine whether the given value is
1898 /// composed of a repeated sequence of identical bytes and return the
1899 /// byte value. If it is not a repeated sequence, return -1.
isRepeatedByteSequence(const ConstantDataSequential * V)1900 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1901 StringRef Data = V->getRawDataValues();
1902 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1903 char C = Data[0];
1904 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1905 if (Data[i] != C) return -1;
1906 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1907 }
1908
1909
1910 /// isRepeatedByteSequence - Determine whether the given value is
1911 /// composed of a repeated sequence of identical bytes and return the
1912 /// byte value. If it is not a repeated sequence, return -1.
isRepeatedByteSequence(const Value * V,const DataLayout & DL)1913 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
1914 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1915 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
1916 assert(Size % 8 == 0);
1917
1918 // Extend the element to take zero padding into account.
1919 APInt Value = CI->getValue().zextOrSelf(Size);
1920 if (!Value.isSplat(8))
1921 return -1;
1922
1923 return Value.zextOrTrunc(8).getZExtValue();
1924 }
1925 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1926 // Make sure all array elements are sequences of the same repeated
1927 // byte.
1928 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1929 Constant *Op0 = CA->getOperand(0);
1930 int Byte = isRepeatedByteSequence(Op0, DL);
1931 if (Byte == -1)
1932 return -1;
1933
1934 // All array elements must be equal.
1935 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
1936 if (CA->getOperand(i) != Op0)
1937 return -1;
1938 return Byte;
1939 }
1940
1941 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1942 return isRepeatedByteSequence(CDS);
1943
1944 return -1;
1945 }
1946
emitGlobalConstantDataSequential(const DataLayout & DL,const ConstantDataSequential * CDS,AsmPrinter & AP)1947 static void emitGlobalConstantDataSequential(const DataLayout &DL,
1948 const ConstantDataSequential *CDS,
1949 AsmPrinter &AP) {
1950
1951 // See if we can aggregate this into a .fill, if so, emit it as such.
1952 int Value = isRepeatedByteSequence(CDS, DL);
1953 if (Value != -1) {
1954 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
1955 // Don't emit a 1-byte object as a .fill.
1956 if (Bytes > 1)
1957 return AP.OutStreamer->emitFill(Bytes, Value);
1958 }
1959
1960 // If this can be emitted with .ascii/.asciz, emit it as such.
1961 if (CDS->isString())
1962 return AP.OutStreamer->EmitBytes(CDS->getAsString());
1963
1964 // Otherwise, emit the values in successive locations.
1965 unsigned ElementByteSize = CDS->getElementByteSize();
1966 if (isa<IntegerType>(CDS->getElementType())) {
1967 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1968 if (AP.isVerbose())
1969 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
1970 CDS->getElementAsInteger(i));
1971 AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i),
1972 ElementByteSize);
1973 }
1974 } else {
1975 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
1976 emitGlobalConstantFP(cast<ConstantFP>(CDS->getElementAsConstant(I)), AP);
1977 }
1978
1979 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1980 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1981 CDS->getNumElements();
1982 if (unsigned Padding = Size - EmittedSize)
1983 AP.OutStreamer->EmitZeros(Padding);
1984
1985 }
1986
emitGlobalConstantArray(const DataLayout & DL,const ConstantArray * CA,AsmPrinter & AP,const Constant * BaseCV,uint64_t Offset)1987 static void emitGlobalConstantArray(const DataLayout &DL,
1988 const ConstantArray *CA, AsmPrinter &AP,
1989 const Constant *BaseCV, uint64_t Offset) {
1990 // See if we can aggregate some values. Make sure it can be
1991 // represented as a series of bytes of the constant value.
1992 int Value = isRepeatedByteSequence(CA, DL);
1993
1994 if (Value != -1) {
1995 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
1996 AP.OutStreamer->emitFill(Bytes, Value);
1997 }
1998 else {
1999 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
2000 emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
2001 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
2002 }
2003 }
2004 }
2005
emitGlobalConstantVector(const DataLayout & DL,const ConstantVector * CV,AsmPrinter & AP)2006 static void emitGlobalConstantVector(const DataLayout &DL,
2007 const ConstantVector *CV, AsmPrinter &AP) {
2008 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
2009 emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
2010
2011 unsigned Size = DL.getTypeAllocSize(CV->getType());
2012 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
2013 CV->getType()->getNumElements();
2014 if (unsigned Padding = Size - EmittedSize)
2015 AP.OutStreamer->EmitZeros(Padding);
2016 }
2017
emitGlobalConstantStruct(const DataLayout & DL,const ConstantStruct * CS,AsmPrinter & AP,const Constant * BaseCV,uint64_t Offset)2018 static void emitGlobalConstantStruct(const DataLayout &DL,
2019 const ConstantStruct *CS, AsmPrinter &AP,
2020 const Constant *BaseCV, uint64_t Offset) {
2021 // Print the fields in successive locations. Pad to align if needed!
2022 unsigned Size = DL.getTypeAllocSize(CS->getType());
2023 const StructLayout *Layout = DL.getStructLayout(CS->getType());
2024 uint64_t SizeSoFar = 0;
2025 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
2026 const Constant *Field = CS->getOperand(i);
2027
2028 // Print the actual field value.
2029 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
2030
2031 // Check if padding is needed and insert one or more 0s.
2032 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
2033 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
2034 - Layout->getElementOffset(i)) - FieldSize;
2035 SizeSoFar += FieldSize + PadSize;
2036
2037 // Insert padding - this may include padding to increase the size of the
2038 // current field up to the ABI size (if the struct is not packed) as well
2039 // as padding to ensure that the next field starts at the right offset.
2040 AP.OutStreamer->EmitZeros(PadSize);
2041 }
2042 assert(SizeSoFar == Layout->getSizeInBytes() &&
2043 "Layout of constant struct may be incorrect!");
2044 }
2045
emitGlobalConstantFP(const ConstantFP * CFP,AsmPrinter & AP)2046 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
2047 APInt API = CFP->getValueAPF().bitcastToAPInt();
2048
2049 // First print a comment with what we think the original floating-point value
2050 // should have been.
2051 if (AP.isVerbose()) {
2052 SmallString<8> StrVal;
2053 CFP->getValueAPF().toString(StrVal);
2054
2055 if (CFP->getType())
2056 CFP->getType()->print(AP.OutStreamer->GetCommentOS());
2057 else
2058 AP.OutStreamer->GetCommentOS() << "Printing <null> Type";
2059 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
2060 }
2061
2062 // Now iterate through the APInt chunks, emitting them in endian-correct
2063 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2064 // floats).
2065 unsigned NumBytes = API.getBitWidth() / 8;
2066 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2067 const uint64_t *p = API.getRawData();
2068
2069 // PPC's long double has odd notions of endianness compared to how LLVM
2070 // handles it: p[0] goes first for *big* endian on PPC.
2071 if (AP.getDataLayout().isBigEndian() && !CFP->getType()->isPPC_FP128Ty()) {
2072 int Chunk = API.getNumWords() - 1;
2073
2074 if (TrailingBytes)
2075 AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes);
2076
2077 for (; Chunk >= 0; --Chunk)
2078 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2079 } else {
2080 unsigned Chunk;
2081 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2082 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2083
2084 if (TrailingBytes)
2085 AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes);
2086 }
2087
2088 // Emit the tail padding for the long double.
2089 const DataLayout &DL = AP.getDataLayout();
2090 AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
2091 DL.getTypeStoreSize(CFP->getType()));
2092 }
2093
emitGlobalConstantLargeInt(const ConstantInt * CI,AsmPrinter & AP)2094 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
2095 const DataLayout &DL = AP.getDataLayout();
2096 unsigned BitWidth = CI->getBitWidth();
2097
2098 // Copy the value as we may massage the layout for constants whose bit width
2099 // is not a multiple of 64-bits.
2100 APInt Realigned(CI->getValue());
2101 uint64_t ExtraBits = 0;
2102 unsigned ExtraBitsSize = BitWidth & 63;
2103
2104 if (ExtraBitsSize) {
2105 // The bit width of the data is not a multiple of 64-bits.
2106 // The extra bits are expected to be at the end of the chunk of the memory.
2107 // Little endian:
2108 // * Nothing to be done, just record the extra bits to emit.
2109 // Big endian:
2110 // * Record the extra bits to emit.
2111 // * Realign the raw data to emit the chunks of 64-bits.
2112 if (DL.isBigEndian()) {
2113 // Basically the structure of the raw data is a chunk of 64-bits cells:
2114 // 0 1 BitWidth / 64
2115 // [chunk1][chunk2] ... [chunkN].
2116 // The most significant chunk is chunkN and it should be emitted first.
2117 // However, due to the alignment issue chunkN contains useless bits.
2118 // Realign the chunks so that they contain only useless information:
2119 // ExtraBits 0 1 (BitWidth / 64) - 1
2120 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2121 ExtraBits = Realigned.getRawData()[0] &
2122 (((uint64_t)-1) >> (64 - ExtraBitsSize));
2123 Realigned = Realigned.lshr(ExtraBitsSize);
2124 } else
2125 ExtraBits = Realigned.getRawData()[BitWidth / 64];
2126 }
2127
2128 // We don't expect assemblers to support integer data directives
2129 // for more than 64 bits, so we emit the data in at most 64-bit
2130 // quantities at a time.
2131 const uint64_t *RawData = Realigned.getRawData();
2132 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2133 uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
2134 AP.OutStreamer->EmitIntValue(Val, 8);
2135 }
2136
2137 if (ExtraBitsSize) {
2138 // Emit the extra bits after the 64-bits chunks.
2139
2140 // Emit a directive that fills the expected size.
2141 uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType());
2142 Size -= (BitWidth / 64) * 8;
2143 assert(Size && Size * 8 >= ExtraBitsSize &&
2144 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2145 == ExtraBits && "Directive too small for extra bits.");
2146 AP.OutStreamer->EmitIntValue(ExtraBits, Size);
2147 }
2148 }
2149
2150 /// \brief Transform a not absolute MCExpr containing a reference to a GOT
2151 /// equivalent global, by a target specific GOT pc relative access to the
2152 /// final symbol.
handleIndirectSymViaGOTPCRel(AsmPrinter & AP,const MCExpr ** ME,const Constant * BaseCst,uint64_t Offset)2153 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2154 const Constant *BaseCst,
2155 uint64_t Offset) {
2156 // The global @foo below illustrates a global that uses a got equivalent.
2157 //
2158 // @bar = global i32 42
2159 // @gotequiv = private unnamed_addr constant i32* @bar
2160 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2161 // i64 ptrtoint (i32* @foo to i64))
2162 // to i32)
2163 //
2164 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2165 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2166 // form:
2167 //
2168 // foo = cstexpr, where
2169 // cstexpr := <gotequiv> - "." + <cst>
2170 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2171 //
2172 // After canonicalization by evaluateAsRelocatable `ME` turns into:
2173 //
2174 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2175 // gotpcrelcst := <offset from @foo base> + <cst>
2176 //
2177 MCValue MV;
2178 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2179 return;
2180 const MCSymbolRefExpr *SymA = MV.getSymA();
2181 if (!SymA)
2182 return;
2183
2184 // Check that GOT equivalent symbol is cached.
2185 const MCSymbol *GOTEquivSym = &SymA->getSymbol();
2186 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2187 return;
2188
2189 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
2190 if (!BaseGV)
2191 return;
2192
2193 // Check for a valid base symbol
2194 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2195 const MCSymbolRefExpr *SymB = MV.getSymB();
2196
2197 if (!SymB || BaseSym != &SymB->getSymbol())
2198 return;
2199
2200 // Make sure to match:
2201 //
2202 // gotpcrelcst := <offset from @foo base> + <cst>
2203 //
2204 // If gotpcrelcst is positive it means that we can safely fold the pc rel
2205 // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2206 // if the target knows how to encode it.
2207 //
2208 int64_t GOTPCRelCst = Offset + MV.getConstant();
2209 if (GOTPCRelCst < 0)
2210 return;
2211 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2212 return;
2213
2214 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2215 //
2216 // bar:
2217 // .long 42
2218 // gotequiv:
2219 // .quad bar
2220 // foo:
2221 // .long gotequiv - "." + <cst>
2222 //
2223 // is replaced by the target specific equivalent to:
2224 //
2225 // bar:
2226 // .long 42
2227 // foo:
2228 // .long bar@GOTPCREL+<gotpcrelcst>
2229 //
2230 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2231 const GlobalVariable *GV = Result.first;
2232 int NumUses = (int)Result.second;
2233 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2234 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2235 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
2236 FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
2237
2238 // Update GOT equivalent usage information
2239 --NumUses;
2240 if (NumUses >= 0)
2241 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2242 }
2243
emitGlobalConstantImpl(const DataLayout & DL,const Constant * CV,AsmPrinter & AP,const Constant * BaseCV,uint64_t Offset)2244 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
2245 AsmPrinter &AP, const Constant *BaseCV,
2246 uint64_t Offset) {
2247 uint64_t Size = DL.getTypeAllocSize(CV->getType());
2248
2249 // Globals with sub-elements such as combinations of arrays and structs
2250 // are handled recursively by emitGlobalConstantImpl. Keep track of the
2251 // constant symbol base and the current position with BaseCV and Offset.
2252 if (!BaseCV && CV->hasOneUse())
2253 BaseCV = dyn_cast<Constant>(CV->user_back());
2254
2255 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2256 return AP.OutStreamer->EmitZeros(Size);
2257
2258 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2259 switch (Size) {
2260 case 1:
2261 case 2:
2262 case 4:
2263 case 8:
2264 if (AP.isVerbose())
2265 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2266 CI->getZExtValue());
2267 AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size);
2268 return;
2269 default:
2270 emitGlobalConstantLargeInt(CI, AP);
2271 return;
2272 }
2273 }
2274
2275 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2276 return emitGlobalConstantFP(CFP, AP);
2277
2278 if (isa<ConstantPointerNull>(CV)) {
2279 AP.OutStreamer->EmitIntValue(0, Size);
2280 return;
2281 }
2282
2283 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2284 return emitGlobalConstantDataSequential(DL, CDS, AP);
2285
2286 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2287 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
2288
2289 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2290 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
2291
2292 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2293 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2294 // vectors).
2295 if (CE->getOpcode() == Instruction::BitCast)
2296 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
2297
2298 if (Size > 8) {
2299 // If the constant expression's size is greater than 64-bits, then we have
2300 // to emit the value in chunks. Try to constant fold the value and emit it
2301 // that way.
2302 Constant *New = ConstantFoldConstantExpression(CE, DL);
2303 if (New && New != CE)
2304 return emitGlobalConstantImpl(DL, New, AP);
2305 }
2306 }
2307
2308 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2309 return emitGlobalConstantVector(DL, V, AP);
2310
2311 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
2312 // thread the streamer with EmitValue.
2313 const MCExpr *ME = AP.lowerConstant(CV);
2314
2315 // Since lowerConstant already folded and got rid of all IR pointer and
2316 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2317 // directly.
2318 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
2319 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2320
2321 AP.OutStreamer->EmitValue(ME, Size);
2322 }
2323
2324 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
EmitGlobalConstant(const DataLayout & DL,const Constant * CV)2325 void AsmPrinter::EmitGlobalConstant(const DataLayout &DL, const Constant *CV) {
2326 uint64_t Size = DL.getTypeAllocSize(CV->getType());
2327 if (Size)
2328 emitGlobalConstantImpl(DL, CV, *this);
2329 else if (MAI->hasSubsectionsViaSymbols()) {
2330 // If the global has zero size, emit a single byte so that two labels don't
2331 // look like they are at the same location.
2332 OutStreamer->EmitIntValue(0, 1);
2333 }
2334 }
2335
EmitMachineConstantPoolValue(MachineConstantPoolValue * MCPV)2336 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2337 // Target doesn't support this yet!
2338 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2339 }
2340
printOffset(int64_t Offset,raw_ostream & OS) const2341 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2342 if (Offset > 0)
2343 OS << '+' << Offset;
2344 else if (Offset < 0)
2345 OS << Offset;
2346 }
2347
2348 //===----------------------------------------------------------------------===//
2349 // Symbol Lowering Routines.
2350 //===----------------------------------------------------------------------===//
2351
createTempSymbol(const Twine & Name) const2352 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
2353 return OutContext.createTempSymbol(Name, true);
2354 }
2355
GetBlockAddressSymbol(const BlockAddress * BA) const2356 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2357 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2358 }
2359
GetBlockAddressSymbol(const BasicBlock * BB) const2360 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2361 return MMI->getAddrLabelSymbol(BB);
2362 }
2363
2364 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
GetCPISymbol(unsigned CPID) const2365 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2366 const DataLayout &DL = getDataLayout();
2367 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
2368 "CPI" + Twine(getFunctionNumber()) + "_" +
2369 Twine(CPID));
2370 }
2371
2372 /// GetJTISymbol - Return the symbol for the specified jump table entry.
GetJTISymbol(unsigned JTID,bool isLinkerPrivate) const2373 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2374 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2375 }
2376
2377 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2378 /// FIXME: privatize to AsmPrinter.
GetJTSetSymbol(unsigned UID,unsigned MBBID) const2379 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2380 const DataLayout &DL = getDataLayout();
2381 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
2382 Twine(getFunctionNumber()) + "_" +
2383 Twine(UID) + "_set_" + Twine(MBBID));
2384 }
2385
getSymbolWithGlobalValueBase(const GlobalValue * GV,StringRef Suffix) const2386 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2387 StringRef Suffix) const {
2388 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
2389 TM);
2390 }
2391
2392 /// Return the MCSymbol for the specified ExternalSymbol.
GetExternalSymbolSymbol(StringRef Sym) const2393 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2394 SmallString<60> NameStr;
2395 Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
2396 return OutContext.getOrCreateSymbol(NameStr);
2397 }
2398
2399
2400
2401 /// PrintParentLoopComment - Print comments about parent loops of this one.
PrintParentLoopComment(raw_ostream & OS,const MachineLoop * Loop,unsigned FunctionNumber)2402 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2403 unsigned FunctionNumber) {
2404 if (!Loop) return;
2405 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2406 OS.indent(Loop->getLoopDepth()*2)
2407 << "Parent Loop BB" << FunctionNumber << "_"
2408 << Loop->getHeader()->getNumber()
2409 << " Depth=" << Loop->getLoopDepth() << '\n';
2410 }
2411
2412
2413 /// PrintChildLoopComment - Print comments about child loops within
2414 /// the loop for this basic block, with nesting.
PrintChildLoopComment(raw_ostream & OS,const MachineLoop * Loop,unsigned FunctionNumber)2415 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2416 unsigned FunctionNumber) {
2417 // Add child loop information
2418 for (const MachineLoop *CL : *Loop) {
2419 OS.indent(CL->getLoopDepth()*2)
2420 << "Child Loop BB" << FunctionNumber << "_"
2421 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2422 << '\n';
2423 PrintChildLoopComment(OS, CL, FunctionNumber);
2424 }
2425 }
2426
2427 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
emitBasicBlockLoopComments(const MachineBasicBlock & MBB,const MachineLoopInfo * LI,const AsmPrinter & AP)2428 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2429 const MachineLoopInfo *LI,
2430 const AsmPrinter &AP) {
2431 // Add loop depth information
2432 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2433 if (!Loop) return;
2434
2435 MachineBasicBlock *Header = Loop->getHeader();
2436 assert(Header && "No header for loop");
2437
2438 // If this block is not a loop header, just print out what is the loop header
2439 // and return.
2440 if (Header != &MBB) {
2441 AP.OutStreamer->AddComment(" in Loop: Header=BB" +
2442 Twine(AP.getFunctionNumber())+"_" +
2443 Twine(Loop->getHeader()->getNumber())+
2444 " Depth="+Twine(Loop->getLoopDepth()));
2445 return;
2446 }
2447
2448 // Otherwise, it is a loop header. Print out information about child and
2449 // parent loops.
2450 raw_ostream &OS = AP.OutStreamer->GetCommentOS();
2451
2452 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2453
2454 OS << "=>";
2455 OS.indent(Loop->getLoopDepth()*2-2);
2456
2457 OS << "This ";
2458 if (Loop->empty())
2459 OS << "Inner ";
2460 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2461
2462 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2463 }
2464
2465
2466 /// EmitBasicBlockStart - This method prints the label for the specified
2467 /// MachineBasicBlock, an alignment (if present) and a comment describing
2468 /// it if appropriate.
EmitBasicBlockStart(const MachineBasicBlock & MBB) const2469 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
2470 // End the previous funclet and start a new one.
2471 if (MBB.isEHFuncletEntry()) {
2472 for (const HandlerInfo &HI : Handlers) {
2473 HI.Handler->endFunclet();
2474 HI.Handler->beginFunclet(MBB);
2475 }
2476 }
2477
2478 // Emit an alignment directive for this block, if needed.
2479 if (unsigned Align = MBB.getAlignment())
2480 EmitAlignment(Align);
2481
2482 // If the block has its address taken, emit any labels that were used to
2483 // reference the block. It is possible that there is more than one label
2484 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2485 // the references were generated.
2486 if (MBB.hasAddressTaken()) {
2487 const BasicBlock *BB = MBB.getBasicBlock();
2488 if (isVerbose())
2489 OutStreamer->AddComment("Block address taken");
2490
2491 // MBBs can have their address taken as part of CodeGen without having
2492 // their corresponding BB's address taken in IR
2493 if (BB->hasAddressTaken())
2494 for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
2495 OutStreamer->EmitLabel(Sym);
2496 }
2497
2498 // Print some verbose block comments.
2499 if (isVerbose()) {
2500 if (const BasicBlock *BB = MBB.getBasicBlock()) {
2501 if (BB->hasName()) {
2502 BB->printAsOperand(OutStreamer->GetCommentOS(),
2503 /*PrintType=*/false, BB->getModule());
2504 OutStreamer->GetCommentOS() << '\n';
2505 }
2506 }
2507 emitBasicBlockLoopComments(MBB, LI, *this);
2508 }
2509
2510 // Print the main label for the block.
2511 if (MBB.pred_empty() ||
2512 (isBlockOnlyReachableByFallthrough(&MBB) && !MBB.isEHFuncletEntry())) {
2513 if (isVerbose()) {
2514 // NOTE: Want this comment at start of line, don't emit with AddComment.
2515 OutStreamer->emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
2516 }
2517 } else {
2518 OutStreamer->EmitLabel(MBB.getSymbol());
2519 }
2520 }
2521
EmitVisibility(MCSymbol * Sym,unsigned Visibility,bool IsDefinition) const2522 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2523 bool IsDefinition) const {
2524 MCSymbolAttr Attr = MCSA_Invalid;
2525
2526 switch (Visibility) {
2527 default: break;
2528 case GlobalValue::HiddenVisibility:
2529 if (IsDefinition)
2530 Attr = MAI->getHiddenVisibilityAttr();
2531 else
2532 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2533 break;
2534 case GlobalValue::ProtectedVisibility:
2535 Attr = MAI->getProtectedVisibilityAttr();
2536 break;
2537 }
2538
2539 if (Attr != MCSA_Invalid)
2540 OutStreamer->EmitSymbolAttribute(Sym, Attr);
2541 }
2542
2543 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2544 /// exactly one predecessor and the control transfer mechanism between
2545 /// the predecessor and this block is a fall-through.
2546 bool AsmPrinter::
isBlockOnlyReachableByFallthrough(const MachineBasicBlock * MBB) const2547 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2548 // If this is a landing pad, it isn't a fall through. If it has no preds,
2549 // then nothing falls through to it.
2550 if (MBB->isEHPad() || MBB->pred_empty())
2551 return false;
2552
2553 // If there isn't exactly one predecessor, it can't be a fall through.
2554 if (MBB->pred_size() > 1)
2555 return false;
2556
2557 // The predecessor has to be immediately before this block.
2558 MachineBasicBlock *Pred = *MBB->pred_begin();
2559 if (!Pred->isLayoutSuccessor(MBB))
2560 return false;
2561
2562 // If the block is completely empty, then it definitely does fall through.
2563 if (Pred->empty())
2564 return true;
2565
2566 // Check the terminators in the previous blocks
2567 for (const auto &MI : Pred->terminators()) {
2568 // If it is not a simple branch, we are in a table somewhere.
2569 if (!MI.isBranch() || MI.isIndirectBranch())
2570 return false;
2571
2572 // If we are the operands of one of the branches, this is not a fall
2573 // through. Note that targets with delay slots will usually bundle
2574 // terminators with the delay slot instruction.
2575 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
2576 if (OP->isJTI())
2577 return false;
2578 if (OP->isMBB() && OP->getMBB() == MBB)
2579 return false;
2580 }
2581 }
2582
2583 return true;
2584 }
2585
2586
2587
GetOrCreateGCPrinter(GCStrategy & S)2588 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
2589 if (!S.usesMetadata())
2590 return nullptr;
2591
2592 assert(!S.useStatepoints() && "statepoints do not currently support custom"
2593 " stackmap formats, please see the documentation for a description of"
2594 " the default format. If you really need a custom serialized format,"
2595 " please file a bug");
2596
2597 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2598 gcp_map_type::iterator GCPI = GCMap.find(&S);
2599 if (GCPI != GCMap.end())
2600 return GCPI->second.get();
2601
2602 const char *Name = S.getName().c_str();
2603
2604 for (GCMetadataPrinterRegistry::iterator
2605 I = GCMetadataPrinterRegistry::begin(),
2606 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2607 if (strcmp(Name, I->getName()) == 0) {
2608 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
2609 GMP->S = &S;
2610 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
2611 return IterBool.first->second.get();
2612 }
2613
2614 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2615 }
2616
2617 /// Pin vtable to this file.
~AsmPrinterHandler()2618 AsmPrinterHandler::~AsmPrinterHandler() {}
2619
markFunctionEnd()2620 void AsmPrinterHandler::markFunctionEnd() {}
2621