xref: /openbsd/gnu/llvm/llvm/lib/MC/MCStreamer.cpp (revision d415bd75)
1 //===- lib/MC/MCStreamer.cpp - Streaming Machine Code Output --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/MC/MCStreamer.h"
10 #include "llvm/ADT/SmallString.h"
11 #include "llvm/ADT/StringRef.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/BinaryFormat/COFF.h"
14 #include "llvm/BinaryFormat/MachO.h"
15 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
16 #include "llvm/MC/MCAsmBackend.h"
17 #include "llvm/MC/MCAsmInfo.h"
18 #include "llvm/MC/MCCodeView.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDwarf.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCObjectFileInfo.h"
25 #include "llvm/MC/MCPseudoProbe.h"
26 #include "llvm/MC/MCRegister.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCSection.h"
29 #include "llvm/MC/MCSectionCOFF.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCWin64EH.h"
32 #include "llvm/MC/MCWinEH.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/LEB128.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <cassert>
39 #include <cstdint>
40 #include <cstdlib>
41 #include <optional>
42 #include <utility>
43 
44 using namespace llvm;
45 
MCTargetStreamer(MCStreamer & S)46 MCTargetStreamer::MCTargetStreamer(MCStreamer &S) : Streamer(S) {
47   S.setTargetStreamer(this);
48 }
49 
50 // Pin the vtables to this file.
51 MCTargetStreamer::~MCTargetStreamer() = default;
52 
emitLabel(MCSymbol * Symbol)53 void MCTargetStreamer::emitLabel(MCSymbol *Symbol) {}
54 
finish()55 void MCTargetStreamer::finish() {}
56 
emitConstantPools()57 void MCTargetStreamer::emitConstantPools() {}
58 
changeSection(const MCSection * CurSection,MCSection * Section,const MCExpr * Subsection,raw_ostream & OS)59 void MCTargetStreamer::changeSection(const MCSection *CurSection,
60                                      MCSection *Section,
61                                      const MCExpr *Subsection,
62                                      raw_ostream &OS) {
63   Section->printSwitchToSection(*Streamer.getContext().getAsmInfo(),
64                                 Streamer.getContext().getTargetTriple(), OS,
65                                 Subsection);
66 }
67 
emitDwarfFileDirective(StringRef Directive)68 void MCTargetStreamer::emitDwarfFileDirective(StringRef Directive) {
69   Streamer.emitRawText(Directive);
70 }
71 
emitValue(const MCExpr * Value)72 void MCTargetStreamer::emitValue(const MCExpr *Value) {
73   SmallString<128> Str;
74   raw_svector_ostream OS(Str);
75 
76   Value->print(OS, Streamer.getContext().getAsmInfo());
77   Streamer.emitRawText(OS.str());
78 }
79 
emitRawBytes(StringRef Data)80 void MCTargetStreamer::emitRawBytes(StringRef Data) {
81   const MCAsmInfo *MAI = Streamer.getContext().getAsmInfo();
82   const char *Directive = MAI->getData8bitsDirective();
83   for (const unsigned char C : Data.bytes()) {
84     SmallString<128> Str;
85     raw_svector_ostream OS(Str);
86 
87     OS << Directive << (unsigned)C;
88     Streamer.emitRawText(OS.str());
89   }
90 }
91 
emitAssignment(MCSymbol * Symbol,const MCExpr * Value)92 void MCTargetStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {}
93 
MCStreamer(MCContext & Ctx)94 MCStreamer::MCStreamer(MCContext &Ctx)
95     : Context(Ctx), CurrentWinFrameInfo(nullptr),
96       CurrentProcWinFrameInfoStartIndex(0), UseAssemblerInfoForParsing(false) {
97   SectionStack.push_back(std::pair<MCSectionSubPair, MCSectionSubPair>());
98 }
99 
100 MCStreamer::~MCStreamer() = default;
101 
reset()102 void MCStreamer::reset() {
103   DwarfFrameInfos.clear();
104   CurrentWinFrameInfo = nullptr;
105   WinFrameInfos.clear();
106   SymbolOrdering.clear();
107   SectionStack.clear();
108   SectionStack.push_back(std::pair<MCSectionSubPair, MCSectionSubPair>());
109 }
110 
getCommentOS()111 raw_ostream &MCStreamer::getCommentOS() {
112   // By default, discard comments.
113   return nulls();
114 }
115 
getNumFrameInfos()116 unsigned MCStreamer::getNumFrameInfos() { return DwarfFrameInfos.size(); }
getDwarfFrameInfos() const117 ArrayRef<MCDwarfFrameInfo> MCStreamer::getDwarfFrameInfos() const {
118   return DwarfFrameInfos;
119 }
120 
emitRawComment(const Twine & T,bool TabPrefix)121 void MCStreamer::emitRawComment(const Twine &T, bool TabPrefix) {}
122 
addExplicitComment(const Twine & T)123 void MCStreamer::addExplicitComment(const Twine &T) {}
emitExplicitComments()124 void MCStreamer::emitExplicitComments() {}
125 
generateCompactUnwindEncodings(MCAsmBackend * MAB)126 void MCStreamer::generateCompactUnwindEncodings(MCAsmBackend *MAB) {
127   for (auto &FI : DwarfFrameInfos)
128     FI.CompactUnwindEncoding =
129         (MAB ? MAB->generateCompactUnwindEncoding(FI.Instructions) : 0);
130 }
131 
132 /// EmitIntValue - Special case of EmitValue that avoids the client having to
133 /// pass in a MCExpr for constant integers.
emitIntValue(uint64_t Value,unsigned Size)134 void MCStreamer::emitIntValue(uint64_t Value, unsigned Size) {
135   assert(1 <= Size && Size <= 8 && "Invalid size");
136   assert((isUIntN(8 * Size, Value) || isIntN(8 * Size, Value)) &&
137          "Invalid size");
138   const bool IsLittleEndian = Context.getAsmInfo()->isLittleEndian();
139   uint64_t Swapped = support::endian::byte_swap(
140       Value, IsLittleEndian ? support::little : support::big);
141   unsigned Index = IsLittleEndian ? 0 : 8 - Size;
142   emitBytes(StringRef(reinterpret_cast<char *>(&Swapped) + Index, Size));
143 }
emitIntValue(APInt Value)144 void MCStreamer::emitIntValue(APInt Value) {
145   if (Value.getNumWords() == 1) {
146     emitIntValue(Value.getLimitedValue(), Value.getBitWidth() / 8);
147     return;
148   }
149 
150   const bool IsLittleEndianTarget = Context.getAsmInfo()->isLittleEndian();
151   const bool ShouldSwap = sys::IsLittleEndianHost != IsLittleEndianTarget;
152   const APInt Swapped = ShouldSwap ? Value.byteSwap() : Value;
153   const unsigned Size = Value.getBitWidth() / 8;
154   SmallString<10> Tmp;
155   Tmp.resize(Size);
156   StoreIntToMemory(Swapped, reinterpret_cast<uint8_t *>(Tmp.data()), Size);
157   emitBytes(Tmp.str());
158 }
159 
160 /// EmitULEB128IntValue - Special case of EmitULEB128Value that avoids the
161 /// client having to pass in a MCExpr for constant integers.
emitULEB128IntValue(uint64_t Value,unsigned PadTo)162 unsigned MCStreamer::emitULEB128IntValue(uint64_t Value, unsigned PadTo) {
163   SmallString<128> Tmp;
164   raw_svector_ostream OSE(Tmp);
165   encodeULEB128(Value, OSE, PadTo);
166   emitBytes(OSE.str());
167   return Tmp.size();
168 }
169 
170 /// EmitSLEB128IntValue - Special case of EmitSLEB128Value that avoids the
171 /// client having to pass in a MCExpr for constant integers.
emitSLEB128IntValue(int64_t Value)172 unsigned MCStreamer::emitSLEB128IntValue(int64_t Value) {
173   SmallString<128> Tmp;
174   raw_svector_ostream OSE(Tmp);
175   encodeSLEB128(Value, OSE);
176   emitBytes(OSE.str());
177   return Tmp.size();
178 }
179 
emitValue(const MCExpr * Value,unsigned Size,SMLoc Loc)180 void MCStreamer::emitValue(const MCExpr *Value, unsigned Size, SMLoc Loc) {
181   emitValueImpl(Value, Size, Loc);
182 }
183 
emitSymbolValue(const MCSymbol * Sym,unsigned Size,bool IsSectionRelative)184 void MCStreamer::emitSymbolValue(const MCSymbol *Sym, unsigned Size,
185                                  bool IsSectionRelative) {
186   assert((!IsSectionRelative || Size == 4) &&
187          "SectionRelative value requires 4-bytes");
188 
189   if (!IsSectionRelative)
190     emitValueImpl(MCSymbolRefExpr::create(Sym, getContext()), Size);
191   else
192     emitCOFFSecRel32(Sym, /*Offset=*/0);
193 }
194 
emitDTPRel64Value(const MCExpr * Value)195 void MCStreamer::emitDTPRel64Value(const MCExpr *Value) {
196   report_fatal_error("unsupported directive in streamer");
197 }
198 
emitDTPRel32Value(const MCExpr * Value)199 void MCStreamer::emitDTPRel32Value(const MCExpr *Value) {
200   report_fatal_error("unsupported directive in streamer");
201 }
202 
emitTPRel64Value(const MCExpr * Value)203 void MCStreamer::emitTPRel64Value(const MCExpr *Value) {
204   report_fatal_error("unsupported directive in streamer");
205 }
206 
emitTPRel32Value(const MCExpr * Value)207 void MCStreamer::emitTPRel32Value(const MCExpr *Value) {
208   report_fatal_error("unsupported directive in streamer");
209 }
210 
emitGPRel64Value(const MCExpr * Value)211 void MCStreamer::emitGPRel64Value(const MCExpr *Value) {
212   report_fatal_error("unsupported directive in streamer");
213 }
214 
emitGPRel32Value(const MCExpr * Value)215 void MCStreamer::emitGPRel32Value(const MCExpr *Value) {
216   report_fatal_error("unsupported directive in streamer");
217 }
218 
219 /// Emit NumBytes bytes worth of the value specified by FillValue.
220 /// This implements directives such as '.space'.
emitFill(uint64_t NumBytes,uint8_t FillValue)221 void MCStreamer::emitFill(uint64_t NumBytes, uint8_t FillValue) {
222   emitFill(*MCConstantExpr::create(NumBytes, getContext()), FillValue);
223 }
224 
emitNops(int64_t NumBytes,int64_t ControlledNopLen,llvm::SMLoc,const MCSubtargetInfo & STI)225 void llvm::MCStreamer::emitNops(int64_t NumBytes, int64_t ControlledNopLen,
226                                 llvm::SMLoc, const MCSubtargetInfo& STI) {}
227 
228 /// The implementation in this class just redirects to emitFill.
emitZeros(uint64_t NumBytes)229 void MCStreamer::emitZeros(uint64_t NumBytes) { emitFill(NumBytes, 0); }
230 
tryEmitDwarfFileDirective(unsigned FileNo,StringRef Directory,StringRef Filename,std::optional<MD5::MD5Result> Checksum,std::optional<StringRef> Source,unsigned CUID)231 Expected<unsigned> MCStreamer::tryEmitDwarfFileDirective(
232     unsigned FileNo, StringRef Directory, StringRef Filename,
233     std::optional<MD5::MD5Result> Checksum, std::optional<StringRef> Source,
234     unsigned CUID) {
235   return getContext().getDwarfFile(Directory, Filename, FileNo, Checksum,
236                                    Source, CUID);
237 }
238 
emitDwarfFile0Directive(StringRef Directory,StringRef Filename,std::optional<MD5::MD5Result> Checksum,std::optional<StringRef> Source,unsigned CUID)239 void MCStreamer::emitDwarfFile0Directive(StringRef Directory,
240                                          StringRef Filename,
241                                          std::optional<MD5::MD5Result> Checksum,
242                                          std::optional<StringRef> Source,
243                                          unsigned CUID) {
244   getContext().setMCLineTableRootFile(CUID, Directory, Filename, Checksum,
245                                       Source);
246 }
247 
emitCFIBKeyFrame()248 void MCStreamer::emitCFIBKeyFrame() {
249   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
250   if (!CurFrame)
251     return;
252   CurFrame->IsBKeyFrame = true;
253 }
254 
emitCFIMTETaggedFrame()255 void MCStreamer::emitCFIMTETaggedFrame() {
256   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
257   if (!CurFrame)
258     return;
259   CurFrame->IsMTETaggedFrame = true;
260 }
261 
emitDwarfLocDirective(unsigned FileNo,unsigned Line,unsigned Column,unsigned Flags,unsigned Isa,unsigned Discriminator,StringRef FileName)262 void MCStreamer::emitDwarfLocDirective(unsigned FileNo, unsigned Line,
263                                        unsigned Column, unsigned Flags,
264                                        unsigned Isa, unsigned Discriminator,
265                                        StringRef FileName) {
266   getContext().setCurrentDwarfLoc(FileNo, Line, Column, Flags, Isa,
267                                   Discriminator);
268 }
269 
getDwarfLineTableSymbol(unsigned CUID)270 MCSymbol *MCStreamer::getDwarfLineTableSymbol(unsigned CUID) {
271   MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
272   if (!Table.getLabel()) {
273     StringRef Prefix = Context.getAsmInfo()->getPrivateGlobalPrefix();
274     Table.setLabel(
275         Context.getOrCreateSymbol(Prefix + "line_table_start" + Twine(CUID)));
276   }
277   return Table.getLabel();
278 }
279 
hasUnfinishedDwarfFrameInfo()280 bool MCStreamer::hasUnfinishedDwarfFrameInfo() {
281   return !DwarfFrameInfos.empty() && !DwarfFrameInfos.back().End;
282 }
283 
getCurrentDwarfFrameInfo()284 MCDwarfFrameInfo *MCStreamer::getCurrentDwarfFrameInfo() {
285   if (!hasUnfinishedDwarfFrameInfo()) {
286     getContext().reportError(getStartTokLoc(),
287                              "this directive must appear between "
288                              ".cfi_startproc and .cfi_endproc directives");
289     return nullptr;
290   }
291   return &DwarfFrameInfos.back();
292 }
293 
emitCVFileDirective(unsigned FileNo,StringRef Filename,ArrayRef<uint8_t> Checksum,unsigned ChecksumKind)294 bool MCStreamer::emitCVFileDirective(unsigned FileNo, StringRef Filename,
295                                      ArrayRef<uint8_t> Checksum,
296                                      unsigned ChecksumKind) {
297   return getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum,
298                                              ChecksumKind);
299 }
300 
emitCVFuncIdDirective(unsigned FunctionId)301 bool MCStreamer::emitCVFuncIdDirective(unsigned FunctionId) {
302   return getContext().getCVContext().recordFunctionId(FunctionId);
303 }
304 
emitCVInlineSiteIdDirective(unsigned FunctionId,unsigned IAFunc,unsigned IAFile,unsigned IALine,unsigned IACol,SMLoc Loc)305 bool MCStreamer::emitCVInlineSiteIdDirective(unsigned FunctionId,
306                                              unsigned IAFunc, unsigned IAFile,
307                                              unsigned IALine, unsigned IACol,
308                                              SMLoc Loc) {
309   if (getContext().getCVContext().getCVFunctionInfo(IAFunc) == nullptr) {
310     getContext().reportError(Loc, "parent function id not introduced by "
311                                   ".cv_func_id or .cv_inline_site_id");
312     return true;
313   }
314 
315   return getContext().getCVContext().recordInlinedCallSiteId(
316       FunctionId, IAFunc, IAFile, IALine, IACol);
317 }
318 
emitCVLocDirective(unsigned FunctionId,unsigned FileNo,unsigned Line,unsigned Column,bool PrologueEnd,bool IsStmt,StringRef FileName,SMLoc Loc)319 void MCStreamer::emitCVLocDirective(unsigned FunctionId, unsigned FileNo,
320                                     unsigned Line, unsigned Column,
321                                     bool PrologueEnd, bool IsStmt,
322                                     StringRef FileName, SMLoc Loc) {}
323 
checkCVLocSection(unsigned FuncId,unsigned FileNo,SMLoc Loc)324 bool MCStreamer::checkCVLocSection(unsigned FuncId, unsigned FileNo,
325                                    SMLoc Loc) {
326   CodeViewContext &CVC = getContext().getCVContext();
327   MCCVFunctionInfo *FI = CVC.getCVFunctionInfo(FuncId);
328   if (!FI) {
329     getContext().reportError(
330         Loc, "function id not introduced by .cv_func_id or .cv_inline_site_id");
331     return false;
332   }
333 
334   // Track the section
335   if (FI->Section == nullptr)
336     FI->Section = getCurrentSectionOnly();
337   else if (FI->Section != getCurrentSectionOnly()) {
338     getContext().reportError(
339         Loc,
340         "all .cv_loc directives for a function must be in the same section");
341     return false;
342   }
343   return true;
344 }
345 
emitCVLinetableDirective(unsigned FunctionId,const MCSymbol * Begin,const MCSymbol * End)346 void MCStreamer::emitCVLinetableDirective(unsigned FunctionId,
347                                           const MCSymbol *Begin,
348                                           const MCSymbol *End) {}
349 
emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,unsigned SourceFileId,unsigned SourceLineNum,const MCSymbol * FnStartSym,const MCSymbol * FnEndSym)350 void MCStreamer::emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
351                                                 unsigned SourceFileId,
352                                                 unsigned SourceLineNum,
353                                                 const MCSymbol *FnStartSym,
354                                                 const MCSymbol *FnEndSym) {}
355 
356 /// Only call this on endian-specific types like ulittle16_t and little32_t, or
357 /// structs composed of them.
358 template <typename T>
copyBytesForDefRange(SmallString<20> & BytePrefix,codeview::SymbolKind SymKind,const T & DefRangeHeader)359 static void copyBytesForDefRange(SmallString<20> &BytePrefix,
360                                  codeview::SymbolKind SymKind,
361                                  const T &DefRangeHeader) {
362   BytePrefix.resize(2 + sizeof(T));
363   codeview::ulittle16_t SymKindLE = codeview::ulittle16_t(SymKind);
364   memcpy(&BytePrefix[0], &SymKindLE, 2);
365   memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T));
366 }
367 
emitCVDefRangeDirective(ArrayRef<std::pair<const MCSymbol *,const MCSymbol * >> Ranges,StringRef FixedSizePortion)368 void MCStreamer::emitCVDefRangeDirective(
369     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
370     StringRef FixedSizePortion) {}
371 
emitCVDefRangeDirective(ArrayRef<std::pair<const MCSymbol *,const MCSymbol * >> Ranges,codeview::DefRangeRegisterRelHeader DRHdr)372 void MCStreamer::emitCVDefRangeDirective(
373     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
374     codeview::DefRangeRegisterRelHeader DRHdr) {
375   SmallString<20> BytePrefix;
376   copyBytesForDefRange(BytePrefix, codeview::S_DEFRANGE_REGISTER_REL, DRHdr);
377   emitCVDefRangeDirective(Ranges, BytePrefix);
378 }
379 
emitCVDefRangeDirective(ArrayRef<std::pair<const MCSymbol *,const MCSymbol * >> Ranges,codeview::DefRangeSubfieldRegisterHeader DRHdr)380 void MCStreamer::emitCVDefRangeDirective(
381     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
382     codeview::DefRangeSubfieldRegisterHeader DRHdr) {
383   SmallString<20> BytePrefix;
384   copyBytesForDefRange(BytePrefix, codeview::S_DEFRANGE_SUBFIELD_REGISTER,
385                        DRHdr);
386   emitCVDefRangeDirective(Ranges, BytePrefix);
387 }
388 
emitCVDefRangeDirective(ArrayRef<std::pair<const MCSymbol *,const MCSymbol * >> Ranges,codeview::DefRangeRegisterHeader DRHdr)389 void MCStreamer::emitCVDefRangeDirective(
390     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
391     codeview::DefRangeRegisterHeader DRHdr) {
392   SmallString<20> BytePrefix;
393   copyBytesForDefRange(BytePrefix, codeview::S_DEFRANGE_REGISTER, DRHdr);
394   emitCVDefRangeDirective(Ranges, BytePrefix);
395 }
396 
emitCVDefRangeDirective(ArrayRef<std::pair<const MCSymbol *,const MCSymbol * >> Ranges,codeview::DefRangeFramePointerRelHeader DRHdr)397 void MCStreamer::emitCVDefRangeDirective(
398     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
399     codeview::DefRangeFramePointerRelHeader DRHdr) {
400   SmallString<20> BytePrefix;
401   copyBytesForDefRange(BytePrefix, codeview::S_DEFRANGE_FRAMEPOINTER_REL,
402                        DRHdr);
403   emitCVDefRangeDirective(Ranges, BytePrefix);
404 }
405 
emitEHSymAttributes(const MCSymbol * Symbol,MCSymbol * EHSymbol)406 void MCStreamer::emitEHSymAttributes(const MCSymbol *Symbol,
407                                      MCSymbol *EHSymbol) {
408 }
409 
initSections(bool NoExecStack,const MCSubtargetInfo & STI)410 void MCStreamer::initSections(bool NoExecStack, const MCSubtargetInfo &STI) {
411   switchSection(getContext().getObjectFileInfo()->getTextSection());
412 }
413 
assignFragment(MCSymbol * Symbol,MCFragment * Fragment)414 void MCStreamer::assignFragment(MCSymbol *Symbol, MCFragment *Fragment) {
415   assert(Fragment);
416   Symbol->setFragment(Fragment);
417 
418   // As we emit symbols into a section, track the order so that they can
419   // be sorted upon later. Zero is reserved to mean 'unemitted'.
420   SymbolOrdering[Symbol] = 1 + SymbolOrdering.size();
421 }
422 
emitLabel(MCSymbol * Symbol,SMLoc Loc)423 void MCStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
424   Symbol->redefineIfPossible();
425 
426   if (!Symbol->isUndefined() || Symbol->isVariable())
427     return getContext().reportError(Loc, "symbol '" + Twine(Symbol->getName()) +
428                                              "' is already defined");
429 
430   assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
431   assert(getCurrentSectionOnly() && "Cannot emit before setting section!");
432   assert(!Symbol->getFragment() && "Unexpected fragment on symbol data!");
433   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
434 
435   Symbol->setFragment(&getCurrentSectionOnly()->getDummyFragment());
436 
437   MCTargetStreamer *TS = getTargetStreamer();
438   if (TS)
439     TS->emitLabel(Symbol);
440 }
441 
emitConditionalAssignment(MCSymbol * Symbol,const MCExpr * Value)442 void MCStreamer::emitConditionalAssignment(MCSymbol *Symbol,
443                                            const MCExpr *Value) {}
444 
emitCFISections(bool EH,bool Debug)445 void MCStreamer::emitCFISections(bool EH, bool Debug) {}
446 
emitCFIStartProc(bool IsSimple,SMLoc Loc)447 void MCStreamer::emitCFIStartProc(bool IsSimple, SMLoc Loc) {
448   if (hasUnfinishedDwarfFrameInfo())
449     return getContext().reportError(
450         Loc, "starting new .cfi frame before finishing the previous one");
451 
452   MCDwarfFrameInfo Frame;
453   Frame.IsSimple = IsSimple;
454   emitCFIStartProcImpl(Frame);
455 
456   const MCAsmInfo* MAI = Context.getAsmInfo();
457   if (MAI) {
458     for (const MCCFIInstruction& Inst : MAI->getInitialFrameState()) {
459       if (Inst.getOperation() == MCCFIInstruction::OpDefCfa ||
460           Inst.getOperation() == MCCFIInstruction::OpDefCfaRegister ||
461           Inst.getOperation() == MCCFIInstruction::OpLLVMDefAspaceCfa) {
462         Frame.CurrentCfaRegister = Inst.getRegister();
463       }
464     }
465   }
466 
467   DwarfFrameInfos.push_back(Frame);
468 }
469 
emitCFIStartProcImpl(MCDwarfFrameInfo & Frame)470 void MCStreamer::emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
471 }
472 
emitCFIEndProc()473 void MCStreamer::emitCFIEndProc() {
474   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
475   if (!CurFrame)
476     return;
477   emitCFIEndProcImpl(*CurFrame);
478 }
479 
emitCFIEndProcImpl(MCDwarfFrameInfo & Frame)480 void MCStreamer::emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
481   // Put a dummy non-null value in Frame.End to mark that this frame has been
482   // closed.
483   Frame.End = (MCSymbol *)1;
484 }
485 
emitCFILabel()486 MCSymbol *MCStreamer::emitCFILabel() {
487   // Return a dummy non-null value so that label fields appear filled in when
488   // generating textual assembly.
489   return (MCSymbol *)1;
490 }
491 
emitCFIDefCfa(int64_t Register,int64_t Offset)492 void MCStreamer::emitCFIDefCfa(int64_t Register, int64_t Offset) {
493   MCSymbol *Label = emitCFILabel();
494   MCCFIInstruction Instruction =
495       MCCFIInstruction::cfiDefCfa(Label, Register, Offset);
496   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
497   if (!CurFrame)
498     return;
499   CurFrame->Instructions.push_back(Instruction);
500   CurFrame->CurrentCfaRegister = static_cast<unsigned>(Register);
501 }
502 
emitCFIDefCfaOffset(int64_t Offset)503 void MCStreamer::emitCFIDefCfaOffset(int64_t Offset) {
504   MCSymbol *Label = emitCFILabel();
505   MCCFIInstruction Instruction =
506       MCCFIInstruction::cfiDefCfaOffset(Label, Offset);
507   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
508   if (!CurFrame)
509     return;
510   CurFrame->Instructions.push_back(Instruction);
511 }
512 
emitCFIAdjustCfaOffset(int64_t Adjustment)513 void MCStreamer::emitCFIAdjustCfaOffset(int64_t Adjustment) {
514   MCSymbol *Label = emitCFILabel();
515   MCCFIInstruction Instruction =
516     MCCFIInstruction::createAdjustCfaOffset(Label, Adjustment);
517   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
518   if (!CurFrame)
519     return;
520   CurFrame->Instructions.push_back(Instruction);
521 }
522 
emitCFIDefCfaRegister(int64_t Register)523 void MCStreamer::emitCFIDefCfaRegister(int64_t Register) {
524   MCSymbol *Label = emitCFILabel();
525   MCCFIInstruction Instruction =
526     MCCFIInstruction::createDefCfaRegister(Label, Register);
527   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
528   if (!CurFrame)
529     return;
530   CurFrame->Instructions.push_back(Instruction);
531   CurFrame->CurrentCfaRegister = static_cast<unsigned>(Register);
532 }
533 
emitCFILLVMDefAspaceCfa(int64_t Register,int64_t Offset,int64_t AddressSpace)534 void MCStreamer::emitCFILLVMDefAspaceCfa(int64_t Register, int64_t Offset,
535                                          int64_t AddressSpace) {
536   MCSymbol *Label = emitCFILabel();
537   MCCFIInstruction Instruction = MCCFIInstruction::createLLVMDefAspaceCfa(
538       Label, Register, Offset, AddressSpace);
539   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
540   if (!CurFrame)
541     return;
542   CurFrame->Instructions.push_back(Instruction);
543   CurFrame->CurrentCfaRegister = static_cast<unsigned>(Register);
544 }
545 
emitCFIOffset(int64_t Register,int64_t Offset)546 void MCStreamer::emitCFIOffset(int64_t Register, int64_t Offset) {
547   MCSymbol *Label = emitCFILabel();
548   MCCFIInstruction Instruction =
549     MCCFIInstruction::createOffset(Label, Register, Offset);
550   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
551   if (!CurFrame)
552     return;
553   CurFrame->Instructions.push_back(Instruction);
554 }
555 
emitCFIRelOffset(int64_t Register,int64_t Offset)556 void MCStreamer::emitCFIRelOffset(int64_t Register, int64_t Offset) {
557   MCSymbol *Label = emitCFILabel();
558   MCCFIInstruction Instruction =
559     MCCFIInstruction::createRelOffset(Label, Register, Offset);
560   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
561   if (!CurFrame)
562     return;
563   CurFrame->Instructions.push_back(Instruction);
564 }
565 
emitCFIPersonality(const MCSymbol * Sym,unsigned Encoding)566 void MCStreamer::emitCFIPersonality(const MCSymbol *Sym,
567                                     unsigned Encoding) {
568   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
569   if (!CurFrame)
570     return;
571   CurFrame->Personality = Sym;
572   CurFrame->PersonalityEncoding = Encoding;
573 }
574 
emitCFILsda(const MCSymbol * Sym,unsigned Encoding)575 void MCStreamer::emitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
576   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
577   if (!CurFrame)
578     return;
579   CurFrame->Lsda = Sym;
580   CurFrame->LsdaEncoding = Encoding;
581 }
582 
emitCFIRememberState()583 void MCStreamer::emitCFIRememberState() {
584   MCSymbol *Label = emitCFILabel();
585   MCCFIInstruction Instruction = MCCFIInstruction::createRememberState(Label);
586   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
587   if (!CurFrame)
588     return;
589   CurFrame->Instructions.push_back(Instruction);
590 }
591 
emitCFIRestoreState()592 void MCStreamer::emitCFIRestoreState() {
593   // FIXME: Error if there is no matching cfi_remember_state.
594   MCSymbol *Label = emitCFILabel();
595   MCCFIInstruction Instruction = MCCFIInstruction::createRestoreState(Label);
596   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
597   if (!CurFrame)
598     return;
599   CurFrame->Instructions.push_back(Instruction);
600 }
601 
emitCFISameValue(int64_t Register)602 void MCStreamer::emitCFISameValue(int64_t Register) {
603   MCSymbol *Label = emitCFILabel();
604   MCCFIInstruction Instruction =
605     MCCFIInstruction::createSameValue(Label, Register);
606   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
607   if (!CurFrame)
608     return;
609   CurFrame->Instructions.push_back(Instruction);
610 }
611 
emitCFIRestore(int64_t Register)612 void MCStreamer::emitCFIRestore(int64_t Register) {
613   MCSymbol *Label = emitCFILabel();
614   MCCFIInstruction Instruction =
615     MCCFIInstruction::createRestore(Label, Register);
616   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
617   if (!CurFrame)
618     return;
619   CurFrame->Instructions.push_back(Instruction);
620 }
621 
emitCFIEscape(StringRef Values)622 void MCStreamer::emitCFIEscape(StringRef Values) {
623   MCSymbol *Label = emitCFILabel();
624   MCCFIInstruction Instruction = MCCFIInstruction::createEscape(Label, Values);
625   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
626   if (!CurFrame)
627     return;
628   CurFrame->Instructions.push_back(Instruction);
629 }
630 
emitCFIGnuArgsSize(int64_t Size)631 void MCStreamer::emitCFIGnuArgsSize(int64_t Size) {
632   MCSymbol *Label = emitCFILabel();
633   MCCFIInstruction Instruction =
634     MCCFIInstruction::createGnuArgsSize(Label, Size);
635   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
636   if (!CurFrame)
637     return;
638   CurFrame->Instructions.push_back(Instruction);
639 }
640 
emitCFISignalFrame()641 void MCStreamer::emitCFISignalFrame() {
642   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
643   if (!CurFrame)
644     return;
645   CurFrame->IsSignalFrame = true;
646 }
647 
emitCFIUndefined(int64_t Register)648 void MCStreamer::emitCFIUndefined(int64_t Register) {
649   MCSymbol *Label = emitCFILabel();
650   MCCFIInstruction Instruction =
651     MCCFIInstruction::createUndefined(Label, Register);
652   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
653   if (!CurFrame)
654     return;
655   CurFrame->Instructions.push_back(Instruction);
656 }
657 
emitCFIRegister(int64_t Register1,int64_t Register2)658 void MCStreamer::emitCFIRegister(int64_t Register1, int64_t Register2) {
659   MCSymbol *Label = emitCFILabel();
660   MCCFIInstruction Instruction =
661     MCCFIInstruction::createRegister(Label, Register1, Register2);
662   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
663   if (!CurFrame)
664     return;
665   CurFrame->Instructions.push_back(Instruction);
666 }
667 
emitCFIWindowSave()668 void MCStreamer::emitCFIWindowSave() {
669   MCSymbol *Label = emitCFILabel();
670   MCCFIInstruction Instruction =
671     MCCFIInstruction::createWindowSave(Label);
672   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
673   if (!CurFrame)
674     return;
675   CurFrame->Instructions.push_back(Instruction);
676 }
677 
emitCFINegateRAState()678 void MCStreamer::emitCFINegateRAState() {
679   MCSymbol *Label = emitCFILabel();
680   MCCFIInstruction Instruction = MCCFIInstruction::createNegateRAState(Label);
681   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
682   if (!CurFrame)
683     return;
684   CurFrame->Instructions.push_back(Instruction);
685 }
686 
emitCFIReturnColumn(int64_t Register)687 void MCStreamer::emitCFIReturnColumn(int64_t Register) {
688   MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
689   if (!CurFrame)
690     return;
691   CurFrame->RAReg = Register;
692 }
693 
EnsureValidWinFrameInfo(SMLoc Loc)694 WinEH::FrameInfo *MCStreamer::EnsureValidWinFrameInfo(SMLoc Loc) {
695   const MCAsmInfo *MAI = Context.getAsmInfo();
696   if (!MAI->usesWindowsCFI()) {
697     getContext().reportError(
698         Loc, ".seh_* directives are not supported on this target");
699     return nullptr;
700   }
701   if (!CurrentWinFrameInfo || CurrentWinFrameInfo->End) {
702     getContext().reportError(
703         Loc, ".seh_ directive must appear within an active frame");
704     return nullptr;
705   }
706   return CurrentWinFrameInfo;
707 }
708 
emitWinCFIStartProc(const MCSymbol * Symbol,SMLoc Loc)709 void MCStreamer::emitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) {
710   const MCAsmInfo *MAI = Context.getAsmInfo();
711   if (!MAI->usesWindowsCFI())
712     return getContext().reportError(
713         Loc, ".seh_* directives are not supported on this target");
714   if (CurrentWinFrameInfo && !CurrentWinFrameInfo->End)
715     getContext().reportError(
716         Loc, "Starting a function before ending the previous one!");
717 
718   MCSymbol *StartProc = emitCFILabel();
719 
720   CurrentProcWinFrameInfoStartIndex = WinFrameInfos.size();
721   WinFrameInfos.emplace_back(
722       std::make_unique<WinEH::FrameInfo>(Symbol, StartProc));
723   CurrentWinFrameInfo = WinFrameInfos.back().get();
724   CurrentWinFrameInfo->TextSection = getCurrentSectionOnly();
725 }
726 
emitWinCFIEndProc(SMLoc Loc)727 void MCStreamer::emitWinCFIEndProc(SMLoc Loc) {
728   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
729   if (!CurFrame)
730     return;
731   if (CurFrame->ChainedParent)
732     getContext().reportError(Loc, "Not all chained regions terminated!");
733 
734   MCSymbol *Label = emitCFILabel();
735   CurFrame->End = Label;
736   if (!CurFrame->FuncletOrFuncEnd)
737     CurFrame->FuncletOrFuncEnd = CurFrame->End;
738 
739   for (size_t I = CurrentProcWinFrameInfoStartIndex, E = WinFrameInfos.size();
740        I != E; ++I)
741     emitWindowsUnwindTables(WinFrameInfos[I].get());
742   switchSection(CurFrame->TextSection);
743 }
744 
emitWinCFIFuncletOrFuncEnd(SMLoc Loc)745 void MCStreamer::emitWinCFIFuncletOrFuncEnd(SMLoc Loc) {
746   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
747   if (!CurFrame)
748     return;
749   if (CurFrame->ChainedParent)
750     getContext().reportError(Loc, "Not all chained regions terminated!");
751 
752   MCSymbol *Label = emitCFILabel();
753   CurFrame->FuncletOrFuncEnd = Label;
754 }
755 
emitWinCFIStartChained(SMLoc Loc)756 void MCStreamer::emitWinCFIStartChained(SMLoc Loc) {
757   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
758   if (!CurFrame)
759     return;
760 
761   MCSymbol *StartProc = emitCFILabel();
762 
763   WinFrameInfos.emplace_back(std::make_unique<WinEH::FrameInfo>(
764       CurFrame->Function, StartProc, CurFrame));
765   CurrentWinFrameInfo = WinFrameInfos.back().get();
766   CurrentWinFrameInfo->TextSection = getCurrentSectionOnly();
767 }
768 
emitWinCFIEndChained(SMLoc Loc)769 void MCStreamer::emitWinCFIEndChained(SMLoc Loc) {
770   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
771   if (!CurFrame)
772     return;
773   if (!CurFrame->ChainedParent)
774     return getContext().reportError(
775         Loc, "End of a chained region outside a chained region!");
776 
777   MCSymbol *Label = emitCFILabel();
778 
779   CurFrame->End = Label;
780   CurrentWinFrameInfo = const_cast<WinEH::FrameInfo *>(CurFrame->ChainedParent);
781 }
782 
emitWinEHHandler(const MCSymbol * Sym,bool Unwind,bool Except,SMLoc Loc)783 void MCStreamer::emitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
784                                   SMLoc Loc) {
785   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
786   if (!CurFrame)
787     return;
788   if (CurFrame->ChainedParent)
789     return getContext().reportError(
790         Loc, "Chained unwind areas can't have handlers!");
791   CurFrame->ExceptionHandler = Sym;
792   if (!Except && !Unwind)
793     getContext().reportError(Loc, "Don't know what kind of handler this is!");
794   if (Unwind)
795     CurFrame->HandlesUnwind = true;
796   if (Except)
797     CurFrame->HandlesExceptions = true;
798 }
799 
emitWinEHHandlerData(SMLoc Loc)800 void MCStreamer::emitWinEHHandlerData(SMLoc Loc) {
801   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
802   if (!CurFrame)
803     return;
804   if (CurFrame->ChainedParent)
805     getContext().reportError(Loc, "Chained unwind areas can't have handlers!");
806 }
807 
emitCGProfileEntry(const MCSymbolRefExpr * From,const MCSymbolRefExpr * To,uint64_t Count)808 void MCStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
809                                     const MCSymbolRefExpr *To, uint64_t Count) {
810 }
811 
getWinCFISection(MCContext & Context,unsigned * NextWinCFIID,MCSection * MainCFISec,const MCSection * TextSec)812 static MCSection *getWinCFISection(MCContext &Context, unsigned *NextWinCFIID,
813                                    MCSection *MainCFISec,
814                                    const MCSection *TextSec) {
815   // If this is the main .text section, use the main unwind info section.
816   if (TextSec == Context.getObjectFileInfo()->getTextSection())
817     return MainCFISec;
818 
819   const auto *TextSecCOFF = cast<MCSectionCOFF>(TextSec);
820   auto *MainCFISecCOFF = cast<MCSectionCOFF>(MainCFISec);
821   unsigned UniqueID = TextSecCOFF->getOrAssignWinCFISectionID(NextWinCFIID);
822 
823   // If this section is COMDAT, this unwind section should be COMDAT associative
824   // with its group.
825   const MCSymbol *KeySym = nullptr;
826   if (TextSecCOFF->getCharacteristics() & COFF::IMAGE_SCN_LNK_COMDAT) {
827     KeySym = TextSecCOFF->getCOMDATSymbol();
828 
829     // In a GNU environment, we can't use associative comdats. Instead, do what
830     // GCC does, which is to make plain comdat selectany section named like
831     // ".[px]data$_Z3foov".
832     if (!Context.getAsmInfo()->hasCOFFAssociativeComdats()) {
833       std::string SectionName = (MainCFISecCOFF->getName() + "$" +
834                                  TextSecCOFF->getName().split('$').second)
835                                     .str();
836       return Context.getCOFFSection(
837           SectionName,
838           MainCFISecCOFF->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT,
839           MainCFISecCOFF->getKind(), "", COFF::IMAGE_COMDAT_SELECT_ANY);
840     }
841   }
842 
843   return Context.getAssociativeCOFFSection(MainCFISecCOFF, KeySym, UniqueID);
844 }
845 
getAssociatedPDataSection(const MCSection * TextSec)846 MCSection *MCStreamer::getAssociatedPDataSection(const MCSection *TextSec) {
847   return getWinCFISection(getContext(), &NextWinCFIID,
848                           getContext().getObjectFileInfo()->getPDataSection(),
849                           TextSec);
850 }
851 
getAssociatedXDataSection(const MCSection * TextSec)852 MCSection *MCStreamer::getAssociatedXDataSection(const MCSection *TextSec) {
853   return getWinCFISection(getContext(), &NextWinCFIID,
854                           getContext().getObjectFileInfo()->getXDataSection(),
855                           TextSec);
856 }
857 
emitSyntaxDirective()858 void MCStreamer::emitSyntaxDirective() {}
859 
encodeSEHRegNum(MCContext & Ctx,MCRegister Reg)860 static unsigned encodeSEHRegNum(MCContext &Ctx, MCRegister Reg) {
861   return Ctx.getRegisterInfo()->getSEHRegNum(Reg);
862 }
863 
emitWinCFIPushReg(MCRegister Register,SMLoc Loc)864 void MCStreamer::emitWinCFIPushReg(MCRegister Register, SMLoc Loc) {
865   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
866   if (!CurFrame)
867     return;
868 
869   MCSymbol *Label = emitCFILabel();
870 
871   WinEH::Instruction Inst = Win64EH::Instruction::PushNonVol(
872       Label, encodeSEHRegNum(Context, Register));
873   CurFrame->Instructions.push_back(Inst);
874 }
875 
emitWinCFISetFrame(MCRegister Register,unsigned Offset,SMLoc Loc)876 void MCStreamer::emitWinCFISetFrame(MCRegister Register, unsigned Offset,
877                                     SMLoc Loc) {
878   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
879   if (!CurFrame)
880     return;
881   if (CurFrame->LastFrameInst >= 0)
882     return getContext().reportError(
883         Loc, "frame register and offset can be set at most once");
884   if (Offset & 0x0F)
885     return getContext().reportError(Loc, "offset is not a multiple of 16");
886   if (Offset > 240)
887     return getContext().reportError(
888         Loc, "frame offset must be less than or equal to 240");
889 
890   MCSymbol *Label = emitCFILabel();
891 
892   WinEH::Instruction Inst = Win64EH::Instruction::SetFPReg(
893       Label, encodeSEHRegNum(getContext(), Register), Offset);
894   CurFrame->LastFrameInst = CurFrame->Instructions.size();
895   CurFrame->Instructions.push_back(Inst);
896 }
897 
emitWinCFIAllocStack(unsigned Size,SMLoc Loc)898 void MCStreamer::emitWinCFIAllocStack(unsigned Size, SMLoc Loc) {
899   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
900   if (!CurFrame)
901     return;
902   if (Size == 0)
903     return getContext().reportError(Loc,
904                                     "stack allocation size must be non-zero");
905   if (Size & 7)
906     return getContext().reportError(
907         Loc, "stack allocation size is not a multiple of 8");
908 
909   MCSymbol *Label = emitCFILabel();
910 
911   WinEH::Instruction Inst = Win64EH::Instruction::Alloc(Label, Size);
912   CurFrame->Instructions.push_back(Inst);
913 }
914 
emitWinCFISaveReg(MCRegister Register,unsigned Offset,SMLoc Loc)915 void MCStreamer::emitWinCFISaveReg(MCRegister Register, unsigned Offset,
916                                    SMLoc Loc) {
917   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
918   if (!CurFrame)
919     return;
920 
921   if (Offset & 7)
922     return getContext().reportError(
923         Loc, "register save offset is not 8 byte aligned");
924 
925   MCSymbol *Label = emitCFILabel();
926 
927   WinEH::Instruction Inst = Win64EH::Instruction::SaveNonVol(
928       Label, encodeSEHRegNum(Context, Register), Offset);
929   CurFrame->Instructions.push_back(Inst);
930 }
931 
emitWinCFISaveXMM(MCRegister Register,unsigned Offset,SMLoc Loc)932 void MCStreamer::emitWinCFISaveXMM(MCRegister Register, unsigned Offset,
933                                    SMLoc Loc) {
934   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
935   if (!CurFrame)
936     return;
937   if (Offset & 0x0F)
938     return getContext().reportError(Loc, "offset is not a multiple of 16");
939 
940   MCSymbol *Label = emitCFILabel();
941 
942   WinEH::Instruction Inst = Win64EH::Instruction::SaveXMM(
943       Label, encodeSEHRegNum(Context, Register), Offset);
944   CurFrame->Instructions.push_back(Inst);
945 }
946 
emitWinCFIPushFrame(bool Code,SMLoc Loc)947 void MCStreamer::emitWinCFIPushFrame(bool Code, SMLoc Loc) {
948   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
949   if (!CurFrame)
950     return;
951   if (!CurFrame->Instructions.empty())
952     return getContext().reportError(
953         Loc, "If present, PushMachFrame must be the first UOP");
954 
955   MCSymbol *Label = emitCFILabel();
956 
957   WinEH::Instruction Inst = Win64EH::Instruction::PushMachFrame(Label, Code);
958   CurFrame->Instructions.push_back(Inst);
959 }
960 
emitWinCFIEndProlog(SMLoc Loc)961 void MCStreamer::emitWinCFIEndProlog(SMLoc Loc) {
962   WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
963   if (!CurFrame)
964     return;
965 
966   MCSymbol *Label = emitCFILabel();
967 
968   CurFrame->PrologEnd = Label;
969 }
970 
emitCOFFSafeSEH(MCSymbol const * Symbol)971 void MCStreamer::emitCOFFSafeSEH(MCSymbol const *Symbol) {}
972 
emitCOFFSymbolIndex(MCSymbol const * Symbol)973 void MCStreamer::emitCOFFSymbolIndex(MCSymbol const *Symbol) {}
974 
emitCOFFSectionIndex(MCSymbol const * Symbol)975 void MCStreamer::emitCOFFSectionIndex(MCSymbol const *Symbol) {}
976 
emitCOFFSecRel32(MCSymbol const * Symbol,uint64_t Offset)977 void MCStreamer::emitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {}
978 
emitCOFFImgRel32(MCSymbol const * Symbol,int64_t Offset)979 void MCStreamer::emitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) {}
980 
981 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
982 /// the specified string in the output .s file.  This capability is
983 /// indicated by the hasRawTextSupport() predicate.
emitRawTextImpl(StringRef String)984 void MCStreamer::emitRawTextImpl(StringRef String) {
985   // This is not llvm_unreachable for the sake of out of tree backend
986   // developers who may not have assembly streamers and should serve as a
987   // reminder to not accidentally call EmitRawText in the absence of such.
988   report_fatal_error("EmitRawText called on an MCStreamer that doesn't support "
989                      "it (target backend is likely missing an AsmStreamer "
990                      "implementation)");
991 }
992 
emitRawText(const Twine & T)993 void MCStreamer::emitRawText(const Twine &T) {
994   SmallString<128> Str;
995   emitRawTextImpl(T.toStringRef(Str));
996 }
997 
emitWindowsUnwindTables()998 void MCStreamer::emitWindowsUnwindTables() {}
999 
emitWindowsUnwindTables(WinEH::FrameInfo * Frame)1000 void MCStreamer::emitWindowsUnwindTables(WinEH::FrameInfo *Frame) {}
1001 
finish(SMLoc EndLoc)1002 void MCStreamer::finish(SMLoc EndLoc) {
1003   if ((!DwarfFrameInfos.empty() && !DwarfFrameInfos.back().End) ||
1004       (!WinFrameInfos.empty() && !WinFrameInfos.back()->End)) {
1005     getContext().reportError(EndLoc, "Unfinished frame!");
1006     return;
1007   }
1008 
1009   MCTargetStreamer *TS = getTargetStreamer();
1010   if (TS)
1011     TS->finish();
1012 
1013   finishImpl();
1014 }
1015 
maybeEmitDwarf64Mark()1016 void MCStreamer::maybeEmitDwarf64Mark() {
1017   if (Context.getDwarfFormat() != dwarf::DWARF64)
1018     return;
1019   AddComment("DWARF64 Mark");
1020   emitInt32(dwarf::DW_LENGTH_DWARF64);
1021 }
1022 
emitDwarfUnitLength(uint64_t Length,const Twine & Comment)1023 void MCStreamer::emitDwarfUnitLength(uint64_t Length, const Twine &Comment) {
1024   assert(Context.getDwarfFormat() == dwarf::DWARF64 ||
1025          Length <= dwarf::DW_LENGTH_lo_reserved);
1026   maybeEmitDwarf64Mark();
1027   AddComment(Comment);
1028   emitIntValue(Length, dwarf::getDwarfOffsetByteSize(Context.getDwarfFormat()));
1029 }
1030 
emitDwarfUnitLength(const Twine & Prefix,const Twine & Comment)1031 MCSymbol *MCStreamer::emitDwarfUnitLength(const Twine &Prefix,
1032                                           const Twine &Comment) {
1033   maybeEmitDwarf64Mark();
1034   AddComment(Comment);
1035   MCSymbol *Lo = Context.createTempSymbol(Prefix + "_start");
1036   MCSymbol *Hi = Context.createTempSymbol(Prefix + "_end");
1037 
1038   emitAbsoluteSymbolDiff(
1039       Hi, Lo, dwarf::getDwarfOffsetByteSize(Context.getDwarfFormat()));
1040   // emit the begin symbol after we generate the length field.
1041   emitLabel(Lo);
1042   // Return the Hi symbol to the caller.
1043   return Hi;
1044 }
1045 
emitDwarfLineStartLabel(MCSymbol * StartSym)1046 void MCStreamer::emitDwarfLineStartLabel(MCSymbol *StartSym) {
1047   // Set the value of the symbol, as we are at the start of the line table.
1048   emitLabel(StartSym);
1049 }
1050 
emitAssignment(MCSymbol * Symbol,const MCExpr * Value)1051 void MCStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
1052   visitUsedExpr(*Value);
1053   Symbol->setVariableValue(Value);
1054 
1055   MCTargetStreamer *TS = getTargetStreamer();
1056   if (TS)
1057     TS->emitAssignment(Symbol, Value);
1058 }
1059 
prettyPrintAsm(MCInstPrinter & InstPrinter,uint64_t Address,const MCInst & Inst,const MCSubtargetInfo & STI,raw_ostream & OS)1060 void MCTargetStreamer::prettyPrintAsm(MCInstPrinter &InstPrinter,
1061                                       uint64_t Address, const MCInst &Inst,
1062                                       const MCSubtargetInfo &STI,
1063                                       raw_ostream &OS) {
1064   InstPrinter.printInst(&Inst, Address, "", STI, OS);
1065 }
1066 
visitUsedSymbol(const MCSymbol & Sym)1067 void MCStreamer::visitUsedSymbol(const MCSymbol &Sym) {
1068 }
1069 
visitUsedExpr(const MCExpr & Expr)1070 void MCStreamer::visitUsedExpr(const MCExpr &Expr) {
1071   switch (Expr.getKind()) {
1072   case MCExpr::Target:
1073     cast<MCTargetExpr>(Expr).visitUsedExpr(*this);
1074     break;
1075 
1076   case MCExpr::Constant:
1077     break;
1078 
1079   case MCExpr::Binary: {
1080     const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
1081     visitUsedExpr(*BE.getLHS());
1082     visitUsedExpr(*BE.getRHS());
1083     break;
1084   }
1085 
1086   case MCExpr::SymbolRef:
1087     visitUsedSymbol(cast<MCSymbolRefExpr>(Expr).getSymbol());
1088     break;
1089 
1090   case MCExpr::Unary:
1091     visitUsedExpr(*cast<MCUnaryExpr>(Expr).getSubExpr());
1092     break;
1093   }
1094 }
1095 
emitInstruction(const MCInst & Inst,const MCSubtargetInfo &)1096 void MCStreamer::emitInstruction(const MCInst &Inst, const MCSubtargetInfo &) {
1097   // Scan for values.
1098   for (unsigned i = Inst.getNumOperands(); i--;)
1099     if (Inst.getOperand(i).isExpr())
1100       visitUsedExpr(*Inst.getOperand(i).getExpr());
1101 }
1102 
emitPseudoProbe(uint64_t Guid,uint64_t Index,uint64_t Type,uint64_t Attr,const MCPseudoProbeInlineStack & InlineStack,MCSymbol * FnSym)1103 void MCStreamer::emitPseudoProbe(uint64_t Guid, uint64_t Index, uint64_t Type,
1104                                  uint64_t Attr,
1105                                  const MCPseudoProbeInlineStack &InlineStack,
1106                                  MCSymbol *FnSym) {
1107   auto &Context = getContext();
1108 
1109   // Create a symbol at in the current section for use in the probe.
1110   MCSymbol *ProbeSym = Context.createTempSymbol();
1111 
1112   // Set the value of the symbol to use for the MCPseudoProbe.
1113   emitLabel(ProbeSym);
1114 
1115   // Create a (local) probe entry with the symbol.
1116   MCPseudoProbe Probe(ProbeSym, Guid, Index, Type, Attr);
1117 
1118   // Add the probe entry to this section's entries.
1119   Context.getMCPseudoProbeTable().getProbeSections().addPseudoProbe(
1120       FnSym, Probe, InlineStack);
1121 }
1122 
emitAbsoluteSymbolDiff(const MCSymbol * Hi,const MCSymbol * Lo,unsigned Size)1123 void MCStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo,
1124                                         unsigned Size) {
1125   // Get the Hi-Lo expression.
1126   const MCExpr *Diff =
1127       MCBinaryExpr::createSub(MCSymbolRefExpr::create(Hi, Context),
1128                               MCSymbolRefExpr::create(Lo, Context), Context);
1129 
1130   const MCAsmInfo *MAI = Context.getAsmInfo();
1131   if (!MAI->doesSetDirectiveSuppressReloc()) {
1132     emitValue(Diff, Size);
1133     return;
1134   }
1135 
1136   // Otherwise, emit with .set (aka assignment).
1137   MCSymbol *SetLabel = Context.createTempSymbol("set");
1138   emitAssignment(SetLabel, Diff);
1139   emitSymbolValue(SetLabel, Size);
1140 }
1141 
emitAbsoluteSymbolDiffAsULEB128(const MCSymbol * Hi,const MCSymbol * Lo)1142 void MCStreamer::emitAbsoluteSymbolDiffAsULEB128(const MCSymbol *Hi,
1143                                                  const MCSymbol *Lo) {
1144   // Get the Hi-Lo expression.
1145   const MCExpr *Diff =
1146       MCBinaryExpr::createSub(MCSymbolRefExpr::create(Hi, Context),
1147                               MCSymbolRefExpr::create(Lo, Context), Context);
1148 
1149   emitULEB128Value(Diff);
1150 }
1151 
emitAssemblerFlag(MCAssemblerFlag Flag)1152 void MCStreamer::emitAssemblerFlag(MCAssemblerFlag Flag) {}
emitThumbFunc(MCSymbol * Func)1153 void MCStreamer::emitThumbFunc(MCSymbol *Func) {}
emitSymbolDesc(MCSymbol * Symbol,unsigned DescValue)1154 void MCStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
beginCOFFSymbolDef(const MCSymbol * Symbol)1155 void MCStreamer::beginCOFFSymbolDef(const MCSymbol *Symbol) {
1156   llvm_unreachable("this directive only supported on COFF targets");
1157 }
endCOFFSymbolDef()1158 void MCStreamer::endCOFFSymbolDef() {
1159   llvm_unreachable("this directive only supported on COFF targets");
1160 }
emitFileDirective(StringRef Filename)1161 void MCStreamer::emitFileDirective(StringRef Filename) {}
emitFileDirective(StringRef Filename,StringRef CompilerVerion,StringRef TimeStamp,StringRef Description)1162 void MCStreamer::emitFileDirective(StringRef Filename, StringRef CompilerVerion,
1163                                    StringRef TimeStamp, StringRef Description) {
1164 }
emitCOFFSymbolStorageClass(int StorageClass)1165 void MCStreamer::emitCOFFSymbolStorageClass(int StorageClass) {
1166   llvm_unreachable("this directive only supported on COFF targets");
1167 }
emitCOFFSymbolType(int Type)1168 void MCStreamer::emitCOFFSymbolType(int Type) {
1169   llvm_unreachable("this directive only supported on COFF targets");
1170 }
emitXCOFFLocalCommonSymbol(MCSymbol * LabelSym,uint64_t Size,MCSymbol * CsectSym,Align Alignment)1171 void MCStreamer::emitXCOFFLocalCommonSymbol(MCSymbol *LabelSym, uint64_t Size,
1172                                             MCSymbol *CsectSym,
1173                                             Align Alignment) {
1174   llvm_unreachable("this directive only supported on XCOFF targets");
1175 }
1176 
emitXCOFFSymbolLinkageWithVisibility(MCSymbol * Symbol,MCSymbolAttr Linkage,MCSymbolAttr Visibility)1177 void MCStreamer::emitXCOFFSymbolLinkageWithVisibility(MCSymbol *Symbol,
1178                                                       MCSymbolAttr Linkage,
1179                                                       MCSymbolAttr Visibility) {
1180   llvm_unreachable("emitXCOFFSymbolLinkageWithVisibility is only supported on "
1181                    "XCOFF targets");
1182 }
1183 
emitXCOFFRenameDirective(const MCSymbol * Name,StringRef Rename)1184 void MCStreamer::emitXCOFFRenameDirective(const MCSymbol *Name,
1185                                           StringRef Rename) {
1186   llvm_unreachable("emitXCOFFRenameDirective is only supported on "
1187                    "XCOFF targets");
1188 }
1189 
emitXCOFFRefDirective(StringRef Name)1190 void MCStreamer::emitXCOFFRefDirective(StringRef Name) {
1191   llvm_unreachable("emitXCOFFRefDirective is only supported on XCOFF targets");
1192 }
1193 
emitXCOFFExceptDirective(const MCSymbol * Symbol,const MCSymbol * Trap,unsigned Lang,unsigned Reason,unsigned FunctionSize,bool hasDebug)1194 void MCStreamer::emitXCOFFExceptDirective(const MCSymbol *Symbol,
1195                                           const MCSymbol *Trap,
1196                                           unsigned Lang, unsigned Reason,
1197                                           unsigned FunctionSize,
1198                                           bool hasDebug) {
1199   report_fatal_error("emitXCOFFExceptDirective is only supported on "
1200                      "XCOFF targets");
1201 }
1202 
emitELFSize(MCSymbol * Symbol,const MCExpr * Value)1203 void MCStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
emitELFSymverDirective(const MCSymbol * OriginalSym,StringRef Name,bool KeepOriginalSym)1204 void MCStreamer::emitELFSymverDirective(const MCSymbol *OriginalSym,
1205                                         StringRef Name, bool KeepOriginalSym) {}
emitLocalCommonSymbol(MCSymbol * Symbol,uint64_t Size,Align ByteAlignment)1206 void MCStreamer::emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
1207                                        Align ByteAlignment) {}
emitTBSSSymbol(MCSection * Section,MCSymbol * Symbol,uint64_t Size,Align ByteAlignment)1208 void MCStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
1209                                 uint64_t Size, Align ByteAlignment) {}
changeSection(MCSection *,const MCExpr *)1210 void MCStreamer::changeSection(MCSection *, const MCExpr *) {}
emitWeakReference(MCSymbol * Alias,const MCSymbol * Symbol)1211 void MCStreamer::emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
emitBytes(StringRef Data)1212 void MCStreamer::emitBytes(StringRef Data) {}
emitBinaryData(StringRef Data)1213 void MCStreamer::emitBinaryData(StringRef Data) { emitBytes(Data); }
emitValueImpl(const MCExpr * Value,unsigned Size,SMLoc Loc)1214 void MCStreamer::emitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc) {
1215   visitUsedExpr(*Value);
1216 }
emitULEB128Value(const MCExpr * Value)1217 void MCStreamer::emitULEB128Value(const MCExpr *Value) {}
emitSLEB128Value(const MCExpr * Value)1218 void MCStreamer::emitSLEB128Value(const MCExpr *Value) {}
emitFill(const MCExpr & NumBytes,uint64_t Value,SMLoc Loc)1219 void MCStreamer::emitFill(const MCExpr &NumBytes, uint64_t Value, SMLoc Loc) {}
emitFill(const MCExpr & NumValues,int64_t Size,int64_t Expr,SMLoc Loc)1220 void MCStreamer::emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
1221                           SMLoc Loc) {}
emitValueToAlignment(Align Alignment,int64_t Value,unsigned ValueSize,unsigned MaxBytesToEmit)1222 void MCStreamer::emitValueToAlignment(Align Alignment, int64_t Value,
1223                                       unsigned ValueSize,
1224                                       unsigned MaxBytesToEmit) {}
emitCodeAlignment(Align Alignment,const MCSubtargetInfo * STI,unsigned MaxBytesToEmit)1225 void MCStreamer::emitCodeAlignment(Align Alignment, const MCSubtargetInfo *STI,
1226                                    unsigned MaxBytesToEmit) {}
emitValueToOffset(const MCExpr * Offset,unsigned char Value,SMLoc Loc)1227 void MCStreamer::emitValueToOffset(const MCExpr *Offset, unsigned char Value,
1228                                    SMLoc Loc) {}
emitBundleAlignMode(Align Alignment)1229 void MCStreamer::emitBundleAlignMode(Align Alignment) {}
emitBundleLock(bool AlignToEnd)1230 void MCStreamer::emitBundleLock(bool AlignToEnd) {}
finishImpl()1231 void MCStreamer::finishImpl() {}
emitBundleUnlock()1232 void MCStreamer::emitBundleUnlock() {}
1233 
switchSection(MCSection * Section,const MCExpr * Subsection)1234 void MCStreamer::switchSection(MCSection *Section, const MCExpr *Subsection) {
1235   assert(Section && "Cannot switch to a null section!");
1236   MCSectionSubPair curSection = SectionStack.back().first;
1237   SectionStack.back().second = curSection;
1238   if (MCSectionSubPair(Section, Subsection) != curSection) {
1239     changeSection(Section, Subsection);
1240     SectionStack.back().first = MCSectionSubPair(Section, Subsection);
1241     assert(!Section->hasEnded() && "Section already ended");
1242     MCSymbol *Sym = Section->getBeginSymbol();
1243     if (Sym && !Sym->isInSection())
1244       emitLabel(Sym);
1245   }
1246 }
1247 
endSection(MCSection * Section)1248 MCSymbol *MCStreamer::endSection(MCSection *Section) {
1249   // TODO: keep track of the last subsection so that this symbol appears in the
1250   // correct place.
1251   MCSymbol *Sym = Section->getEndSymbol(Context);
1252   if (Sym->isInSection())
1253     return Sym;
1254 
1255   switchSection(Section);
1256   emitLabel(Sym);
1257   return Sym;
1258 }
1259 
1260 static VersionTuple
targetVersionOrMinimumSupportedOSVersion(const Triple & Target,VersionTuple TargetVersion)1261 targetVersionOrMinimumSupportedOSVersion(const Triple &Target,
1262                                          VersionTuple TargetVersion) {
1263   VersionTuple Min = Target.getMinimumSupportedOSVersion();
1264   return !Min.empty() && Min > TargetVersion ? Min : TargetVersion;
1265 }
1266 
1267 static MCVersionMinType
getMachoVersionMinLoadCommandType(const Triple & Target)1268 getMachoVersionMinLoadCommandType(const Triple &Target) {
1269   assert(Target.isOSDarwin() && "expected a darwin OS");
1270   switch (Target.getOS()) {
1271   case Triple::MacOSX:
1272   case Triple::Darwin:
1273     return MCVM_OSXVersionMin;
1274   case Triple::IOS:
1275     assert(!Target.isMacCatalystEnvironment() &&
1276            "mac Catalyst should use LC_BUILD_VERSION");
1277     return MCVM_IOSVersionMin;
1278   case Triple::TvOS:
1279     return MCVM_TvOSVersionMin;
1280   case Triple::WatchOS:
1281     return MCVM_WatchOSVersionMin;
1282   default:
1283     break;
1284   }
1285   llvm_unreachable("unexpected OS type");
1286 }
1287 
getMachoBuildVersionSupportedOS(const Triple & Target)1288 static VersionTuple getMachoBuildVersionSupportedOS(const Triple &Target) {
1289   assert(Target.isOSDarwin() && "expected a darwin OS");
1290   switch (Target.getOS()) {
1291   case Triple::MacOSX:
1292   case Triple::Darwin:
1293     return VersionTuple(10, 14);
1294   case Triple::IOS:
1295     // Mac Catalyst always uses the build version load command.
1296     if (Target.isMacCatalystEnvironment())
1297       return VersionTuple();
1298     [[fallthrough]];
1299   case Triple::TvOS:
1300     return VersionTuple(12);
1301   case Triple::WatchOS:
1302     return VersionTuple(5);
1303   case Triple::DriverKit:
1304     // DriverKit always uses the build version load command.
1305     return VersionTuple();
1306   default:
1307     break;
1308   }
1309   llvm_unreachable("unexpected OS type");
1310 }
1311 
1312 static MachO::PlatformType
getMachoBuildVersionPlatformType(const Triple & Target)1313 getMachoBuildVersionPlatformType(const Triple &Target) {
1314   assert(Target.isOSDarwin() && "expected a darwin OS");
1315   switch (Target.getOS()) {
1316   case Triple::MacOSX:
1317   case Triple::Darwin:
1318     return MachO::PLATFORM_MACOS;
1319   case Triple::IOS:
1320     if (Target.isMacCatalystEnvironment())
1321       return MachO::PLATFORM_MACCATALYST;
1322     return Target.isSimulatorEnvironment() ? MachO::PLATFORM_IOSSIMULATOR
1323                                            : MachO::PLATFORM_IOS;
1324   case Triple::TvOS:
1325     return Target.isSimulatorEnvironment() ? MachO::PLATFORM_TVOSSIMULATOR
1326                                            : MachO::PLATFORM_TVOS;
1327   case Triple::WatchOS:
1328     return Target.isSimulatorEnvironment() ? MachO::PLATFORM_WATCHOSSIMULATOR
1329                                            : MachO::PLATFORM_WATCHOS;
1330   case Triple::DriverKit:
1331     return MachO::PLATFORM_DRIVERKIT;
1332   default:
1333     break;
1334   }
1335   llvm_unreachable("unexpected OS type");
1336 }
1337 
emitVersionForTarget(const Triple & Target,const VersionTuple & SDKVersion,const Triple * DarwinTargetVariantTriple,const VersionTuple & DarwinTargetVariantSDKVersion)1338 void MCStreamer::emitVersionForTarget(
1339     const Triple &Target, const VersionTuple &SDKVersion,
1340     const Triple *DarwinTargetVariantTriple,
1341     const VersionTuple &DarwinTargetVariantSDKVersion) {
1342   if (!Target.isOSBinFormatMachO() || !Target.isOSDarwin())
1343     return;
1344   // Do we even know the version?
1345   if (Target.getOSMajorVersion() == 0)
1346     return;
1347 
1348   VersionTuple Version;
1349   switch (Target.getOS()) {
1350   case Triple::MacOSX:
1351   case Triple::Darwin:
1352     Target.getMacOSXVersion(Version);
1353     break;
1354   case Triple::IOS:
1355   case Triple::TvOS:
1356     Version = Target.getiOSVersion();
1357     break;
1358   case Triple::WatchOS:
1359     Version = Target.getWatchOSVersion();
1360     break;
1361   case Triple::DriverKit:
1362     Version = Target.getDriverKitVersion();
1363     break;
1364   default:
1365     llvm_unreachable("unexpected OS type");
1366   }
1367   assert(Version.getMajor() != 0 && "A non-zero major version is expected");
1368   auto LinkedTargetVersion =
1369       targetVersionOrMinimumSupportedOSVersion(Target, Version);
1370   auto BuildVersionOSVersion = getMachoBuildVersionSupportedOS(Target);
1371   bool ShouldEmitBuildVersion = false;
1372   if (BuildVersionOSVersion.empty() ||
1373       LinkedTargetVersion >= BuildVersionOSVersion) {
1374     if (Target.isMacCatalystEnvironment() && DarwinTargetVariantTriple &&
1375         DarwinTargetVariantTriple->isMacOSX()) {
1376       emitVersionForTarget(*DarwinTargetVariantTriple,
1377                            DarwinTargetVariantSDKVersion,
1378                            /*DarwinTargetVariantTriple=*/nullptr,
1379                            /*DarwinTargetVariantSDKVersion=*/VersionTuple());
1380       emitDarwinTargetVariantBuildVersion(
1381           getMachoBuildVersionPlatformType(Target),
1382           LinkedTargetVersion.getMajor(),
1383           LinkedTargetVersion.getMinor().value_or(0),
1384           LinkedTargetVersion.getSubminor().value_or(0), SDKVersion);
1385       return;
1386     }
1387     emitBuildVersion(getMachoBuildVersionPlatformType(Target),
1388                      LinkedTargetVersion.getMajor(),
1389                      LinkedTargetVersion.getMinor().value_or(0),
1390                      LinkedTargetVersion.getSubminor().value_or(0), SDKVersion);
1391     ShouldEmitBuildVersion = true;
1392   }
1393 
1394   if (const Triple *TVT = DarwinTargetVariantTriple) {
1395     if (Target.isMacOSX() && TVT->isMacCatalystEnvironment()) {
1396       auto TVLinkedTargetVersion =
1397           targetVersionOrMinimumSupportedOSVersion(*TVT, TVT->getiOSVersion());
1398       emitDarwinTargetVariantBuildVersion(
1399           getMachoBuildVersionPlatformType(*TVT),
1400           TVLinkedTargetVersion.getMajor(),
1401           TVLinkedTargetVersion.getMinor().value_or(0),
1402           TVLinkedTargetVersion.getSubminor().value_or(0),
1403           DarwinTargetVariantSDKVersion);
1404     }
1405   }
1406 
1407   if (ShouldEmitBuildVersion)
1408     return;
1409 
1410   emitVersionMin(getMachoVersionMinLoadCommandType(Target),
1411                  LinkedTargetVersion.getMajor(),
1412                  LinkedTargetVersion.getMinor().value_or(0),
1413                  LinkedTargetVersion.getSubminor().value_or(0), SDKVersion);
1414 }
1415