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