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