LLVM  15.0.0git
MachObjectWriter.cpp
Go to the documentation of this file.
1 //===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
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/ADT/DenseMap.h"
10 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAsmBackend.h"
14 #include "llvm/MC/MCAsmLayout.h"
15 #include "llvm/MC/MCAssembler.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCDirectives.h"
18 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCFragment.h"
23 #include "llvm/MC/MCObjectWriter.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCSectionMachO.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCSymbolMachO.h"
28 #include "llvm/MC/MCValue.h"
29 #include "llvm/Support/Alignment.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/LEB128.h"
36 #include <algorithm>
37 #include <cassert>
38 #include <cstdint>
39 #include <string>
40 #include <utility>
41 #include <vector>
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "mc"
46 
48  Relocations.clear();
49  IndirectSymBase.clear();
50  StringTable.clear();
51  LocalSymbolData.clear();
52  ExternalSymbolData.clear();
53  UndefinedSymbolData.clear();
55 }
56 
58  // Undefined symbols are always extern.
59  if (S.isUndefined())
60  return true;
61 
62  // References to weak definitions require external relocation entries; the
63  // definition may not always be the one in the same object file.
64  if (cast<MCSymbolMachO>(S).isWeakDefinition())
65  return true;
66 
67  // Otherwise, we can use an internal relocation.
68  return false;
69 }
70 
72 MachSymbolData::operator<(const MachSymbolData &RHS) const {
73  return Symbol->getName() < RHS.Symbol->getName();
74 }
75 
77  const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
78  (MCFixupKind) Kind);
79 
81 }
82 
84  const MCAsmLayout &Layout) const {
85  return getSectionAddress(Fragment->getParent()) +
86  Layout.getFragmentOffset(Fragment);
87 }
88 
90  const MCAsmLayout &Layout) const {
91  // If this is a variable, then recursively evaluate now.
92  if (S.isVariable()) {
93  if (const MCConstantExpr *C =
94  dyn_cast<const MCConstantExpr>(S.getVariableValue()))
95  return C->getValue();
96 
98  if (!S.getVariableValue()->evaluateAsRelocatable(Target, &Layout, nullptr))
99  report_fatal_error("unable to evaluate offset for variable '" +
100  S.getName() + "'");
101 
102  // Verify that any used symbols are defined.
103  if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
104  report_fatal_error("unable to evaluate offset to undefined symbol '" +
105  Target.getSymA()->getSymbol().getName() + "'");
106  if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
107  report_fatal_error("unable to evaluate offset to undefined symbol '" +
108  Target.getSymB()->getSymbol().getName() + "'");
109 
110  uint64_t Address = Target.getConstant();
111  if (Target.getSymA())
112  Address += getSymbolAddress(Target.getSymA()->getSymbol(), Layout);
113  if (Target.getSymB())
114  Address += getSymbolAddress(Target.getSymB()->getSymbol(), Layout);
115  return Address;
116  }
117 
118  return getSectionAddress(S.getFragment()->getParent()) +
119  Layout.getSymbolOffset(S);
120 }
121 
123  const MCAsmLayout &Layout) const {
124  uint64_t EndAddr = getSectionAddress(Sec) + Layout.getSectionAddressSize(Sec);
125  unsigned Next = Sec->getLayoutOrder() + 1;
126  if (Next >= Layout.getSectionOrder().size())
127  return 0;
128 
129  const MCSection &NextSec = *Layout.getSectionOrder()[Next];
130  if (NextSec.isVirtualSection())
131  return 0;
132  return offsetToAlignment(EndAddr, Align(NextSec.getAlignment()));
133 }
134 
136  unsigned NumLoadCommands,
137  unsigned LoadCommandsSize,
138  bool SubsectionsViaSymbols) {
139  uint32_t Flags = 0;
140 
141  if (SubsectionsViaSymbols)
143 
144  // struct mach_header (28 bytes) or
145  // struct mach_header_64 (32 bytes)
146 
147  uint64_t Start = W.OS.tell();
148  (void) Start;
149 
151 
152  W.write<uint32_t>(TargetObjectWriter->getCPUType());
153  W.write<uint32_t>(TargetObjectWriter->getCPUSubtype());
154 
155  W.write<uint32_t>(Type);
156  W.write<uint32_t>(NumLoadCommands);
157  W.write<uint32_t>(LoadCommandsSize);
158  W.write<uint32_t>(Flags);
159  if (is64Bit())
160  W.write<uint32_t>(0); // reserved
161 
162  assert(W.OS.tell() - Start == (is64Bit() ? sizeof(MachO::mach_header_64)
163  : sizeof(MachO::mach_header)));
164 }
165 
166 void MachObjectWriter::writeWithPadding(StringRef Str, uint64_t Size) {
167  assert(Size >= Str.size());
168  W.OS << Str;
169  W.OS.write_zeros(Size - Str.size());
170 }
171 
172 /// writeSegmentLoadCommand - Write a segment load command.
173 ///
174 /// \param NumSections The number of sections in this segment.
175 /// \param SectionDataSize The total size of the sections.
177  StringRef Name, unsigned NumSections, uint64_t VMAddr, uint64_t VMSize,
178  uint64_t SectionDataStartOffset, uint64_t SectionDataSize, uint32_t MaxProt,
179  uint32_t InitProt) {
180  // struct segment_command (56 bytes) or
181  // struct segment_command_64 (72 bytes)
182 
183  uint64_t Start = W.OS.tell();
184  (void) Start;
185 
186  unsigned SegmentLoadCommandSize =
188  sizeof(MachO::segment_command);
189  W.write<uint32_t>(is64Bit() ? MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT);
190  W.write<uint32_t>(SegmentLoadCommandSize +
191  NumSections * (is64Bit() ? sizeof(MachO::section_64) :
192  sizeof(MachO::section)));
193 
194  writeWithPadding(Name, 16);
195  if (is64Bit()) {
196  W.write<uint64_t>(VMAddr); // vmaddr
197  W.write<uint64_t>(VMSize); // vmsize
198  W.write<uint64_t>(SectionDataStartOffset); // file offset
199  W.write<uint64_t>(SectionDataSize); // file size
200  } else {
201  W.write<uint32_t>(VMAddr); // vmaddr
202  W.write<uint32_t>(VMSize); // vmsize
203  W.write<uint32_t>(SectionDataStartOffset); // file offset
204  W.write<uint32_t>(SectionDataSize); // file size
205  }
206  // maxprot
207  W.write<uint32_t>(MaxProt);
208  // initprot
209  W.write<uint32_t>(InitProt);
210  W.write<uint32_t>(NumSections);
211  W.write<uint32_t>(0); // flags
212 
213  assert(W.OS.tell() - Start == SegmentLoadCommandSize);
214 }
215 
217  const MCSection &Sec, uint64_t VMAddr,
218  uint64_t FileOffset, unsigned Flags,
219  uint64_t RelocationsStart,
220  unsigned NumRelocations) {
222  const MCSectionMachO &Section = cast<MCSectionMachO>(Sec);
223 
224  // The offset is unused for virtual sections.
225  if (Section.isVirtualSection()) {
226  assert(Layout.getSectionFileSize(&Sec) == 0 && "Invalid file size!");
227  FileOffset = 0;
228  }
229 
230  // struct section (68 bytes) or
231  // struct section_64 (80 bytes)
232 
233  uint64_t Start = W.OS.tell();
234  (void) Start;
235 
236  writeWithPadding(Section.getName(), 16);
237  writeWithPadding(Section.getSegmentName(), 16);
238  if (is64Bit()) {
239  W.write<uint64_t>(VMAddr); // address
240  W.write<uint64_t>(SectionSize); // size
241  } else {
242  W.write<uint32_t>(VMAddr); // address
243  W.write<uint32_t>(SectionSize); // size
244  }
245  W.write<uint32_t>(FileOffset);
246 
247  assert(isPowerOf2_32(Section.getAlignment()) && "Invalid alignment!");
248  W.write<uint32_t>(Log2_32(Section.getAlignment()));
249  W.write<uint32_t>(NumRelocations ? RelocationsStart : 0);
250  W.write<uint32_t>(NumRelocations);
251  W.write<uint32_t>(Flags);
252  W.write<uint32_t>(IndirectSymBase.lookup(&Sec)); // reserved1
253  W.write<uint32_t>(Section.getStubSize()); // reserved2
254  if (is64Bit())
255  W.write<uint32_t>(0); // reserved3
256 
257  assert(W.OS.tell() - Start ==
258  (is64Bit() ? sizeof(MachO::section_64) : sizeof(MachO::section)));
259 }
260 
262  uint32_t NumSymbols,
263  uint32_t StringTableOffset,
264  uint32_t StringTableSize) {
265  // struct symtab_command (24 bytes)
266 
267  uint64_t Start = W.OS.tell();
268  (void) Start;
269 
270  W.write<uint32_t>(MachO::LC_SYMTAB);
272  W.write<uint32_t>(SymbolOffset);
273  W.write<uint32_t>(NumSymbols);
274  W.write<uint32_t>(StringTableOffset);
275  W.write<uint32_t>(StringTableSize);
276 
277  assert(W.OS.tell() - Start == sizeof(MachO::symtab_command));
278 }
279 
281  uint32_t NumLocalSymbols,
282  uint32_t FirstExternalSymbol,
283  uint32_t NumExternalSymbols,
284  uint32_t FirstUndefinedSymbol,
285  uint32_t NumUndefinedSymbols,
286  uint32_t IndirectSymbolOffset,
287  uint32_t NumIndirectSymbols) {
288  // struct dysymtab_command (80 bytes)
289 
290  uint64_t Start = W.OS.tell();
291  (void) Start;
292 
293  W.write<uint32_t>(MachO::LC_DYSYMTAB);
295  W.write<uint32_t>(FirstLocalSymbol);
296  W.write<uint32_t>(NumLocalSymbols);
297  W.write<uint32_t>(FirstExternalSymbol);
298  W.write<uint32_t>(NumExternalSymbols);
299  W.write<uint32_t>(FirstUndefinedSymbol);
300  W.write<uint32_t>(NumUndefinedSymbols);
301  W.write<uint32_t>(0); // tocoff
302  W.write<uint32_t>(0); // ntoc
303  W.write<uint32_t>(0); // modtaboff
304  W.write<uint32_t>(0); // nmodtab
305  W.write<uint32_t>(0); // extrefsymoff
306  W.write<uint32_t>(0); // nextrefsyms
307  W.write<uint32_t>(IndirectSymbolOffset);
308  W.write<uint32_t>(NumIndirectSymbols);
309  W.write<uint32_t>(0); // extreloff
310  W.write<uint32_t>(0); // nextrel
311  W.write<uint32_t>(0); // locreloff
312  W.write<uint32_t>(0); // nlocrel
313 
314  assert(W.OS.tell() - Start == sizeof(MachO::dysymtab_command));
315 }
316 
317 MachObjectWriter::MachSymbolData *
318 MachObjectWriter::findSymbolData(const MCSymbol &Sym) {
319  for (auto *SymbolData :
320  {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
321  for (MachSymbolData &Entry : *SymbolData)
322  if (Entry.Symbol == &Sym)
323  return &Entry;
324 
325  return nullptr;
326 }
327 
329  const MCSymbol *S = &Sym;
330  while (S->isVariable()) {
331  const MCExpr *Value = S->getVariableValue();
332  const auto *Ref = dyn_cast<MCSymbolRefExpr>(Value);
333  if (!Ref)
334  return *S;
335  S = &Ref->getSymbol();
336  }
337  return *S;
338 }
339 
340 void MachObjectWriter::writeNlist(MachSymbolData &MSD,
341  const MCAsmLayout &Layout) {
342  const MCSymbol *Symbol = MSD.Symbol;
343  const MCSymbol &Data = *Symbol;
344  const MCSymbol *AliasedSymbol = &findAliasedSymbol(*Symbol);
345  uint8_t SectionIndex = MSD.SectionIndex;
346  uint8_t Type = 0;
347  uint64_t Address = 0;
348  bool IsAlias = Symbol != AliasedSymbol;
349 
350  const MCSymbol &OrigSymbol = *Symbol;
351  MachSymbolData *AliaseeInfo;
352  if (IsAlias) {
353  AliaseeInfo = findSymbolData(*AliasedSymbol);
354  if (AliaseeInfo)
355  SectionIndex = AliaseeInfo->SectionIndex;
356  Symbol = AliasedSymbol;
357  // FIXME: Should this update Data as well?
358  }
359 
360  // Set the N_TYPE bits. See <mach-o/nlist.h>.
361  //
362  // FIXME: Are the prebound or indirect fields possible here?
363  if (IsAlias && Symbol->isUndefined())
365  else if (Symbol->isUndefined())
367  else if (Symbol->isAbsolute())
368  Type = MachO::N_ABS;
369  else
371 
372  // FIXME: Set STAB bits.
373 
374  if (Data.isPrivateExtern())
375  Type |= MachO::N_PEXT;
376 
377  // Set external bit.
378  if (Data.isExternal() || (!IsAlias && Symbol->isUndefined()))
379  Type |= MachO::N_EXT;
380 
381  // Compute the symbol address.
382  if (IsAlias && Symbol->isUndefined())
383  Address = AliaseeInfo->StringIndex;
384  else if (Symbol->isDefined())
385  Address = getSymbolAddress(OrigSymbol, Layout);
386  else if (Symbol->isCommon()) {
387  // Common symbols are encoded with the size in the address
388  // field, and their alignment in the flags.
389  Address = Symbol->getCommonSize();
390  }
391 
392  // struct nlist (12 bytes)
393 
394  W.write<uint32_t>(MSD.StringIndex);
395  W.OS << char(Type);
396  W.OS << char(SectionIndex);
397 
398  // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
399  // value.
400  bool EncodeAsAltEntry =
401  IsAlias && cast<MCSymbolMachO>(OrigSymbol).isAltEntry();
402  W.write<uint16_t>(cast<MCSymbolMachO>(Symbol)->getEncodedFlags(EncodeAsAltEntry));
403  if (is64Bit())
404  W.write<uint64_t>(Address);
405  else
406  W.write<uint32_t>(Address);
407 }
408 
410  uint32_t DataOffset,
411  uint32_t DataSize) {
412  uint64_t Start = W.OS.tell();
413  (void) Start;
414 
415  W.write<uint32_t>(Type);
417  W.write<uint32_t>(DataOffset);
418  W.write<uint32_t>(DataSize);
419 
420  assert(W.OS.tell() - Start == sizeof(MachO::linkedit_data_command));
421 }
422 
424  const std::vector<std::string> &Options, bool is64Bit)
425 {
426  unsigned Size = sizeof(MachO::linker_option_command);
427  for (const std::string &Option : Options)
428  Size += Option.size() + 1;
429  return alignTo(Size, is64Bit ? 8 : 4);
430 }
431 
433  const std::vector<std::string> &Options)
434 {
436  uint64_t Start = W.OS.tell();
437  (void) Start;
438 
439  W.write<uint32_t>(MachO::LC_LINKER_OPTION);
440  W.write<uint32_t>(Size);
441  W.write<uint32_t>(Options.size());
442  uint64_t BytesWritten = sizeof(MachO::linker_option_command);
443  for (const std::string &Option : Options) {
444  // Write each string, including the null byte.
445  W.OS << Option << '\0';
446  BytesWritten += Option.size() + 1;
447  }
448 
449  // Pad to a multiple of the pointer size.
450  W.OS.write_zeros(
451  offsetToAlignment(BytesWritten, is64Bit() ? Align(8) : Align(4)));
452 
453  assert(W.OS.tell() - Start == Size);
454 }
455 
456 static bool isFixupTargetValid(const MCValue &Target) {
457  // Target is (LHS - RHS + cst).
458  // We don't support the form where LHS is null: -RHS + cst
459  if (!Target.getSymA() && Target.getSymB())
460  return false;
461  return true;
462 }
463 
465  const MCAsmLayout &Layout,
466  const MCFragment *Fragment,
467  const MCFixup &Fixup, MCValue Target,
468  uint64_t &FixedValue) {
469  if (!isFixupTargetValid(Target)) {
470  Asm.getContext().reportError(Fixup.getLoc(),
471  "unsupported relocation expression");
472  return;
473  }
474 
475  TargetObjectWriter->recordRelocation(this, Asm, Layout, Fragment, Fixup,
476  Target, FixedValue);
477 }
478 
480  // This is the point where 'as' creates actual symbols for indirect symbols
481  // (in the following two passes). It would be easier for us to do this sooner
482  // when we see the attribute, but that makes getting the order in the symbol
483  // table much more complicated than it is worth.
484  //
485  // FIXME: Revisit this when the dust settles.
486 
487  // Report errors for use of .indirect_symbol not in a symbol pointer section
488  // or stub section.
489  for (IndirectSymbolData &ISD : llvm::make_range(Asm.indirect_symbol_begin(),
490  Asm.indirect_symbol_end())) {
491  const MCSectionMachO &Section = cast<MCSectionMachO>(*ISD.Section);
492 
493  if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
494  Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
496  Section.getType() != MachO::S_SYMBOL_STUBS) {
497  MCSymbol &Symbol = *ISD.Symbol;
498  report_fatal_error("indirect symbol '" + Symbol.getName() +
499  "' not in a symbol pointer or stub section");
500  }
501  }
502 
503  // Bind non-lazy symbol pointers first.
504  unsigned IndirectIndex = 0;
505  for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
506  ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
507  const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
508 
509  if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
511  continue;
512 
513  // Initialize the section indirect symbol base, if necessary.
514  IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
515 
516  Asm.registerSymbol(*it->Symbol);
517  }
518 
519  // Then lazy symbol pointers and symbol stubs.
520  IndirectIndex = 0;
521  for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
522  ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
523  const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
524 
525  if (Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
526  Section.getType() != MachO::S_SYMBOL_STUBS)
527  continue;
528 
529  // Initialize the section indirect symbol base, if necessary.
530  IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
531 
532  // Set the symbol type to undefined lazy, but only on construction.
533  //
534  // FIXME: Do not hardcode.
535  bool Created;
536  Asm.registerSymbol(*it->Symbol, &Created);
537  if (Created)
538  cast<MCSymbolMachO>(it->Symbol)->setReferenceTypeUndefinedLazy(true);
539  }
540 }
541 
542 /// computeSymbolTable - Compute the symbol table data
544  MCAssembler &Asm, std::vector<MachSymbolData> &LocalSymbolData,
545  std::vector<MachSymbolData> &ExternalSymbolData,
546  std::vector<MachSymbolData> &UndefinedSymbolData) {
547  // Build section lookup table.
548  DenseMap<const MCSection*, uint8_t> SectionIndexMap;
549  unsigned Index = 1;
550  for (MCAssembler::iterator it = Asm.begin(),
551  ie = Asm.end(); it != ie; ++it, ++Index)
552  SectionIndexMap[&*it] = Index;
553  assert(Index <= 256 && "Too many sections!");
554 
555  // Build the string table.
556  for (const MCSymbol &Symbol : Asm.symbols()) {
557  if (!Asm.isSymbolLinkerVisible(Symbol))
558  continue;
559 
560  StringTable.add(Symbol.getName());
561  }
562  StringTable.finalize();
563 
564  // Build the symbol arrays but only for non-local symbols.
565  //
566  // The particular order that we collect and then sort the symbols is chosen to
567  // match 'as'. Even though it doesn't matter for correctness, this is
568  // important for letting us diff .o files.
569  for (const MCSymbol &Symbol : Asm.symbols()) {
570  // Ignore non-linker visible symbols.
571  if (!Asm.isSymbolLinkerVisible(Symbol))
572  continue;
573 
574  if (!Symbol.isExternal() && !Symbol.isUndefined())
575  continue;
576 
577  MachSymbolData MSD;
578  MSD.Symbol = &Symbol;
579  MSD.StringIndex = StringTable.getOffset(Symbol.getName());
580 
581  if (Symbol.isUndefined()) {
582  MSD.SectionIndex = 0;
583  UndefinedSymbolData.push_back(MSD);
584  } else if (Symbol.isAbsolute()) {
585  MSD.SectionIndex = 0;
586  ExternalSymbolData.push_back(MSD);
587  } else {
588  MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
589  assert(MSD.SectionIndex && "Invalid section index!");
590  ExternalSymbolData.push_back(MSD);
591  }
592  }
593 
594  // Now add the data for local symbols.
595  for (const MCSymbol &Symbol : Asm.symbols()) {
596  // Ignore non-linker visible symbols.
597  if (!Asm.isSymbolLinkerVisible(Symbol))
598  continue;
599 
600  if (Symbol.isExternal() || Symbol.isUndefined())
601  continue;
602 
603  MachSymbolData MSD;
604  MSD.Symbol = &Symbol;
605  MSD.StringIndex = StringTable.getOffset(Symbol.getName());
606 
607  if (Symbol.isAbsolute()) {
608  MSD.SectionIndex = 0;
609  LocalSymbolData.push_back(MSD);
610  } else {
611  MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
612  assert(MSD.SectionIndex && "Invalid section index!");
613  LocalSymbolData.push_back(MSD);
614  }
615  }
616 
617  // External and undefined symbols are required to be in lexicographic order.
618  llvm::sort(ExternalSymbolData);
619  llvm::sort(UndefinedSymbolData);
620 
621  // Set the symbol indices.
622  Index = 0;
623  for (auto *SymbolData :
624  {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
625  for (MachSymbolData &Entry : *SymbolData)
626  Entry.Symbol->setIndex(Index++);
627 
628  for (const MCSection &Section : Asm) {
629  for (RelAndSymbol &Rel : Relocations[&Section]) {
630  if (!Rel.Sym)
631  continue;
632 
633  // Set the Index and the IsExtern bit.
634  unsigned Index = Rel.Sym->getIndex();
635  assert(isInt<24>(Index));
636  if (W.Endian == support::little)
637  Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (~0U << 24)) | Index | (1 << 27);
638  else
639  Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) | Index << 8 | (1 << 4);
640  }
641  }
642 }
643 
645  const MCAsmLayout &Layout) {
646  uint64_t StartAddress = 0;
647  for (const MCSection *Sec : Layout.getSectionOrder()) {
648  StartAddress = alignTo(StartAddress, Sec->getAlignment());
649  SectionAddress[Sec] = StartAddress;
650  StartAddress += Layout.getSectionAddressSize(Sec);
651 
652  // Explicitly pad the section to match the alignment requirements of the
653  // following one. This is for 'gas' compatibility, it shouldn't
654  /// strictly be necessary.
655  StartAddress += getPaddingSize(Sec, Layout);
656  }
657 }
658 
660  const MCAsmLayout &Layout) {
661  computeSectionAddresses(Asm, Layout);
662 
663  // Create symbol data for any indirect symbols.
665 }
666 
668  const MCAssembler &Asm, const MCSymbol &A, const MCSymbol &B,
669  bool InSet) const {
670  // FIXME: We don't handle things like
671  // foo = .
672  // creating atoms.
673  if (A.isVariable() || B.isVariable())
674  return false;
676  InSet);
677 }
678 
680  const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
681  bool InSet, bool IsPCRel) const {
682  if (InSet)
683  return true;
684 
685  // The effective address is
686  // addr(atom(A)) + offset(A)
687  // - addr(atom(B)) - offset(B)
688  // and the offsets are not relocatable, so the fixup is fully resolved when
689  // addr(atom(A)) - addr(atom(B)) == 0.
690  const MCSymbol &SA = findAliasedSymbol(SymA);
691  const MCSection &SecA = SA.getSection();
692  const MCSection &SecB = *FB.getParent();
693 
694  if (IsPCRel) {
695  // The simple (Darwin, except on x86_64) way of dealing with this was to
696  // assume that any reference to a temporary symbol *must* be a temporary
697  // symbol in the same atom, unless the sections differ. Therefore, any PCrel
698  // relocation to a temporary symbol (in the same section) is fully
699  // resolved. This also works in conjunction with absolutized .set, which
700  // requires the compiler to use .set to absolutize the differences between
701  // symbols which the compiler knows to be assembly time constants, so we
702  // don't need to worry about considering symbol differences fully resolved.
703  //
704  // If the file isn't using sub-sections-via-symbols, we can make the
705  // same assumptions about any symbol that we normally make about
706  // assembler locals.
707 
708  bool hasReliableSymbolDifference = isX86_64();
709  if (!hasReliableSymbolDifference) {
710  if (!SA.isInSection() || &SecA != &SecB ||
711  (!SA.isTemporary() && FB.getAtom() != SA.getFragment()->getAtom() &&
712  Asm.getSubsectionsViaSymbols()))
713  return false;
714  return true;
715  }
716  // For Darwin x86_64, there is one special case when the reference IsPCRel.
717  // If the fragment with the reference does not have a base symbol but meets
718  // the simple way of dealing with this, in that it is a temporary symbol in
719  // the same atom then it is assumed to be fully resolved. This is needed so
720  // a relocation entry is not created and so the static linker does not
721  // mess up the reference later.
722  else if(!FB.getAtom() &&
723  SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
724  return true;
725  }
726  }
727 
728  // If they are not in the same section, we can't compute the diff.
729  if (&SecA != &SecB)
730  return false;
731 
732  const MCFragment *FA = SA.getFragment();
733 
734  // Bail if the symbol has no fragment.
735  if (!FA)
736  return false;
737 
738  // If the atoms are the same, they are guaranteed to have the same address.
739  if (FA->getAtom() == FB.getAtom())
740  return true;
741 
742  // Otherwise, we can't prove this is fully resolved.
743  return false;
744 }
745 
747  switch (Type) {
748  case MCVM_OSXVersionMin: return MachO::LC_VERSION_MIN_MACOSX;
749  case MCVM_IOSVersionMin: return MachO::LC_VERSION_MIN_IPHONEOS;
750  case MCVM_TvOSVersionMin: return MachO::LC_VERSION_MIN_TVOS;
751  case MCVM_WatchOSVersionMin: return MachO::LC_VERSION_MIN_WATCHOS;
752  }
753  llvm_unreachable("Invalid mc version min type");
754 }
755 
756 // Encode addrsig data as symbol indexes in variable length encoding.
758  MCSection *AddrSigSection =
759  Asm.getContext().getObjectFileInfo()->getAddrSigSection();
760  MCSection::FragmentListType &fragmentList = AddrSigSection->getFragmentList();
761  if (!fragmentList.size())
762  return;
763 
764  assert(fragmentList.size() == 1);
765  MCFragment *pFragment = &*fragmentList.begin();
766  MCDataFragment *pDataFragment = dyn_cast_or_null<MCDataFragment>(pFragment);
767  assert(pDataFragment);
768 
769  raw_svector_ostream OS(pDataFragment->getContents());
770  for (const MCSymbol *sym : this->getAddrsigSyms())
771  encodeULEB128(sym->getIndex(), OS);
772 }
773 
775  const MCAsmLayout &Layout) {
776  uint64_t StartOffset = W.OS.tell();
777 
778  // Compute symbol table information and bind symbol indices.
779  computeSymbolTable(Asm, LocalSymbolData, ExternalSymbolData,
780  UndefinedSymbolData);
782 
783  if (!Asm.CGProfile.empty()) {
784  MCSection *CGProfileSection = Asm.getContext().getMachOSection(
785  "__LLVM", "__cg_profile", 0, SectionKind::getMetadata());
786  MCDataFragment *Frag = dyn_cast_or_null<MCDataFragment>(
787  &*CGProfileSection->getFragmentList().begin());
788  assert(Frag && "call graph profile section not reserved");
789  Frag->getContents().clear();
790  raw_svector_ostream OS(Frag->getContents());
791  for (const MCAssembler::CGProfileEntry &CGPE : Asm.CGProfile) {
792  uint32_t FromIndex = CGPE.From->getSymbol().getIndex();
793  uint32_t ToIndex = CGPE.To->getSymbol().getIndex();
794  support::endian::write(OS, FromIndex, W.Endian);
795  support::endian::write(OS, ToIndex, W.Endian);
797  }
798  }
799 
800  unsigned NumSections = Asm.size();
801  const MCAssembler::VersionInfoType &VersionInfo =
802  Layout.getAssembler().getVersionInfo();
803 
804  // The section data starts after the header, the segment load command (and
805  // section headers) and the symbol table.
806  unsigned NumLoadCommands = 1;
807  uint64_t LoadCommandsSize = is64Bit() ?
808  sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
809  sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
810 
811  // Add the deployment target version info load command size, if used.
812  if (VersionInfo.Major != 0) {
813  ++NumLoadCommands;
814  if (VersionInfo.EmitBuildVersion)
815  LoadCommandsSize += sizeof(MachO::build_version_command);
816  else
817  LoadCommandsSize += sizeof(MachO::version_min_command);
818  }
819 
820  const MCAssembler::VersionInfoType &TargetVariantVersionInfo =
822 
823  // Add the target variant version info load command size, if used.
824  if (TargetVariantVersionInfo.Major != 0) {
825  ++NumLoadCommands;
826  assert(TargetVariantVersionInfo.EmitBuildVersion &&
827  "target variant should use build version");
828  LoadCommandsSize += sizeof(MachO::build_version_command);
829  }
830 
831  // Add the data-in-code load command size, if used.
832  unsigned NumDataRegions = Asm.getDataRegions().size();
833  if (NumDataRegions) {
834  ++NumLoadCommands;
835  LoadCommandsSize += sizeof(MachO::linkedit_data_command);
836  }
837 
838  // Add the loh load command size, if used.
839  uint64_t LOHRawSize = Asm.getLOHContainer().getEmitSize(*this, Layout);
840  uint64_t LOHSize = alignTo(LOHRawSize, is64Bit() ? 8 : 4);
841  if (LOHSize) {
842  ++NumLoadCommands;
843  LoadCommandsSize += sizeof(MachO::linkedit_data_command);
844  }
845 
846  // Add the symbol table load command sizes, if used.
847  unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
848  UndefinedSymbolData.size();
849  if (NumSymbols) {
850  NumLoadCommands += 2;
851  LoadCommandsSize += (sizeof(MachO::symtab_command) +
852  sizeof(MachO::dysymtab_command));
853  }
854 
855  // Add the linker option load commands sizes.
856  for (const auto &Option : Asm.getLinkerOptions()) {
857  ++NumLoadCommands;
858  LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(Option, is64Bit());
859  }
860 
861  // Compute the total size of the section data, as well as its file size and vm
862  // size.
863  uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) :
864  sizeof(MachO::mach_header)) + LoadCommandsSize;
865  uint64_t SectionDataSize = 0;
866  uint64_t SectionDataFileSize = 0;
867  uint64_t VMSize = 0;
868  for (const MCSection &Sec : Asm) {
869  uint64_t Address = getSectionAddress(&Sec);
870  uint64_t Size = Layout.getSectionAddressSize(&Sec);
871  uint64_t FileSize = Layout.getSectionFileSize(&Sec);
872  FileSize += getPaddingSize(&Sec, Layout);
873 
874  VMSize = std::max(VMSize, Address + Size);
875 
876  if (Sec.isVirtualSection())
877  continue;
878 
879  SectionDataSize = std::max(SectionDataSize, Address + Size);
880  SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
881  }
882 
883  // The section data is padded to pointer size bytes.
884  //
885  // FIXME: Is this machine dependent?
886  unsigned SectionDataPadding =
887  offsetToAlignment(SectionDataFileSize, is64Bit() ? Align(8) : Align(4));
888  SectionDataFileSize += SectionDataPadding;
889 
890  // Write the prolog, starting with the header and load command...
891  writeHeader(MachO::MH_OBJECT, NumLoadCommands, LoadCommandsSize,
892  Asm.getSubsectionsViaSymbols());
893  uint32_t Prot =
895  writeSegmentLoadCommand("", NumSections, 0, VMSize, SectionDataStart,
896  SectionDataSize, Prot, Prot);
897 
898  // ... and then the section headers.
899  uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
900  for (const MCSection &Section : Asm) {
901  const auto &Sec = cast<MCSectionMachO>(Section);
902  std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
903  unsigned NumRelocs = Relocs.size();
904  uint64_t SectionStart = SectionDataStart + getSectionAddress(&Sec);
905  unsigned Flags = Sec.getTypeAndAttributes();
906  if (Sec.hasInstructions())
908  writeSection(Layout, Sec, getSectionAddress(&Sec), SectionStart, Flags,
909  RelocTableEnd, NumRelocs);
910  RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
911  }
912 
913  // Write out the deployment target information, if it's available.
914  auto EmitDeploymentTargetVersion =
915  [&](const MCAssembler::VersionInfoType &VersionInfo) {
916  auto EncodeVersion = [](VersionTuple V) -> uint32_t {
917  assert(!V.empty() && "empty version");
918  unsigned Update = V.getSubminor().value_or(0);
919  unsigned Minor = V.getMinor().value_or(0);
920  assert(Update < 256 && "unencodable update target version");
921  assert(Minor < 256 && "unencodable minor target version");
922  assert(V.getMajor() < 65536 && "unencodable major target version");
923  return Update | (Minor << 8) | (V.getMajor() << 16);
924  };
925  uint32_t EncodedVersion = EncodeVersion(VersionTuple(
926  VersionInfo.Major, VersionInfo.Minor, VersionInfo.Update));
927  uint32_t SDKVersion = !VersionInfo.SDKVersion.empty()
928  ? EncodeVersion(VersionInfo.SDKVersion)
929  : 0;
930  if (VersionInfo.EmitBuildVersion) {
931  // FIXME: Currently empty tools. Add clang version in the future.
932  W.write<uint32_t>(MachO::LC_BUILD_VERSION);
934  W.write<uint32_t>(VersionInfo.TypeOrPlatform.Platform);
935  W.write<uint32_t>(EncodedVersion);
936  W.write<uint32_t>(SDKVersion);
937  W.write<uint32_t>(0); // Empty tools list.
938  } else {
939  MachO::LoadCommandType LCType =
940  getLCFromMCVM(VersionInfo.TypeOrPlatform.Type);
941  W.write<uint32_t>(LCType);
943  W.write<uint32_t>(EncodedVersion);
944  W.write<uint32_t>(SDKVersion);
945  }
946  };
947  if (VersionInfo.Major != 0)
948  EmitDeploymentTargetVersion(VersionInfo);
949  if (TargetVariantVersionInfo.Major != 0)
950  EmitDeploymentTargetVersion(TargetVariantVersionInfo);
951 
952  // Write the data-in-code load command, if used.
953  uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
954  if (NumDataRegions) {
955  uint64_t DataRegionsOffset = RelocTableEnd;
956  uint64_t DataRegionsSize = NumDataRegions * 8;
957  writeLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
958  DataRegionsSize);
959  }
960 
961  // Write the loh load command, if used.
962  uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
963  if (LOHSize)
964  writeLinkeditLoadCommand(MachO::LC_LINKER_OPTIMIZATION_HINT,
965  DataInCodeTableEnd, LOHSize);
966 
967  // Write the symbol table load command, if used.
968  if (NumSymbols) {
969  unsigned FirstLocalSymbol = 0;
970  unsigned NumLocalSymbols = LocalSymbolData.size();
971  unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
972  unsigned NumExternalSymbols = ExternalSymbolData.size();
973  unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
974  unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
975  unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
976  unsigned NumSymTabSymbols =
977  NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
978  uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
979  uint64_t IndirectSymbolOffset = 0;
980 
981  // If used, the indirect symbols are written after the section data.
982  if (NumIndirectSymbols)
983  IndirectSymbolOffset = LOHTableEnd;
984 
985  // The symbol table is written after the indirect symbol data.
986  uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
987 
988  // The string table is written after symbol table.
989  uint64_t StringTableOffset =
990  SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
991  sizeof(MachO::nlist_64) :
992  sizeof(MachO::nlist));
993  writeSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
994  StringTableOffset, StringTable.getSize());
995 
996  writeDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
997  FirstExternalSymbol, NumExternalSymbols,
998  FirstUndefinedSymbol, NumUndefinedSymbols,
999  IndirectSymbolOffset, NumIndirectSymbols);
1000  }
1001 
1002  // Write the linker options load commands.
1003  for (const auto &Option : Asm.getLinkerOptions())
1005 
1006  // Write the actual section data.
1007  for (const MCSection &Sec : Asm) {
1008  Asm.writeSectionData(W.OS, &Sec, Layout);
1009 
1010  uint64_t Pad = getPaddingSize(&Sec, Layout);
1011  W.OS.write_zeros(Pad);
1012  }
1013 
1014  // Write the extra padding.
1015  W.OS.write_zeros(SectionDataPadding);
1016 
1017  // Write the relocation entries.
1018  for (const MCSection &Sec : Asm) {
1019  // Write the section relocation entries, in reverse order to match 'as'
1020  // (approximately, the exact algorithm is more complicated than this).
1021  std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
1022  for (const RelAndSymbol &Rel : llvm::reverse(Relocs)) {
1023  W.write<uint32_t>(Rel.MRE.r_word0);
1024  W.write<uint32_t>(Rel.MRE.r_word1);
1025  }
1026  }
1027 
1028  // Write out the data-in-code region payload, if there is one.
1030  it = Asm.data_region_begin(), ie = Asm.data_region_end();
1031  it != ie; ++it) {
1032  const DataRegionData *Data = &(*it);
1033  uint64_t Start = getSymbolAddress(*Data->Start, Layout);
1034  uint64_t End;
1035  if (Data->End)
1036  End = getSymbolAddress(*Data->End, Layout);
1037  else
1038  report_fatal_error("Data region not terminated");
1039 
1040  LLVM_DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
1041  << " start: " << Start << "(" << Data->Start->getName()
1042  << ")"
1043  << " end: " << End << "(" << Data->End->getName() << ")"
1044  << " size: " << End - Start << "\n");
1045  W.write<uint32_t>(Start);
1046  W.write<uint16_t>(End - Start);
1047  W.write<uint16_t>(Data->Kind);
1048  }
1049 
1050  // Write out the loh commands, if there is one.
1051  if (LOHSize) {
1052 #ifndef NDEBUG
1053  unsigned Start = W.OS.tell();
1054 #endif
1055  Asm.getLOHContainer().emit(*this, Layout);
1056  // Pad to a multiple of the pointer size.
1057  W.OS.write_zeros(
1058  offsetToAlignment(LOHRawSize, is64Bit() ? Align(8) : Align(4)));
1059  assert(W.OS.tell() - Start == LOHSize);
1060  }
1061 
1062  // Write the symbol table data, if used.
1063  if (NumSymbols) {
1064  // Write the indirect symbol entries.
1066  it = Asm.indirect_symbol_begin(),
1067  ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1068  // Indirect symbols in the non-lazy symbol pointer section have some
1069  // special handling.
1070  const MCSectionMachO &Section =
1071  static_cast<const MCSectionMachO &>(*it->Section);
1072  if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) {
1073  // If this symbol is defined and internal, mark it as such.
1074  if (it->Symbol->isDefined() && !it->Symbol->isExternal()) {
1076  if (it->Symbol->isAbsolute())
1077  Flags |= MachO::INDIRECT_SYMBOL_ABS;
1078  W.write<uint32_t>(Flags);
1079  continue;
1080  }
1081  }
1082 
1083  W.write<uint32_t>(it->Symbol->getIndex());
1084  }
1085 
1086  // FIXME: Check that offsets match computed ones.
1087 
1088  // Write the symbol table entries.
1089  for (auto *SymbolData :
1090  {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
1091  for (MachSymbolData &Entry : *SymbolData)
1092  writeNlist(Entry, Layout);
1093 
1094  // Write the string table.
1095  StringTable.write(W.OS);
1096  }
1097 
1098  return W.OS.tell() - StartOffset;
1099 }
1100 
1101 std::unique_ptr<MCObjectWriter>
1102 llvm::createMachObjectWriter(std::unique_ptr<MCMachObjectTargetWriter> MOTW,
1103  raw_pwrite_stream &OS, bool IsLittleEndian) {
1104  return std::make_unique<MachObjectWriter>(std::move(MOTW), OS,
1105  IsLittleEndian);
1106 }
llvm::Check::Size
@ Size
Definition: FileCheck.h:77
llvm::MachObjectWriter::writeNlist
void writeNlist(MachSymbolData &MSD, const MCAsmLayout &Layout)
Definition: MachObjectWriter.cpp:340
llvm::alignTo
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:156
llvm::raw_ostream::tell
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:136
llvm::MachO::section
Definition: MachO.h:565
llvm::MCVersionMinType
MCVersionMinType
Definition: MCDirectives.h:67
MathExtras.h
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:17
llvm::MachO::any_relocation_info
Definition: MachO.h:977
llvm::MCSymbol
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
it
into xmm2 addss xmm2 xmm1 xmm3 addss xmm3 movaps xmm0 unpcklps xmm0 ret seems silly when it could just be one addps Expand libm rounding functions main should enable SSE DAZ mode and other fast SSE modes Think about doing i64 math in SSE regs on x86 This testcase should have no SSE instructions in it
Definition: README-SSE.txt:81
llvm::make_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Definition: iterator_range.h:53
llvm::SectionKind::getMetadata
static SectionKind getMetadata()
Definition: SectionKind.h:188
llvm::MachObjectWriter::writeLinkeditLoadCommand
void writeLinkeditLoadCommand(uint32_t Type, uint32_t DataOffset, uint32_t DataSize)
Definition: MachObjectWriter.cpp:409
llvm::MCVM_WatchOSVersionMin
@ MCVM_WatchOSVersionMin
.watchos_version_min
Definition: MCDirectives.h:71
llvm::MCSymbol::isTemporary
bool isTemporary() const
isTemporary - Check if this is an assembler temporary symbol.
Definition: MCSymbol.h:215
llvm::raw_ostream::write_zeros
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
Definition: raw_ostream.cpp:501
llvm::DenseMapBase< DenseMap< KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >, KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >::lookup
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:199
llvm::MachO::nlist
Definition: MachO.h:989
is64Bit
static bool is64Bit(const char *name)
Definition: X86Disassembler.cpp:1018
MCDirectives.h
llvm::Target
Target - Wrapper for Target specific information.
Definition: TargetRegistry.h:145
llvm::MCSection::getLayoutOrder
unsigned getLayoutOrder() const
Definition: MCSection.h:146
ErrorHandling.h
llvm::MCObjectWriter::getAddrsigSyms
std::vector< const MCSymbol * > & getAddrsigSyms()
Definition: MCObjectWriter.h:106
MCFragment.h
llvm::MCVM_IOSVersionMin
@ MCVM_IOSVersionMin
.ios_version_min
Definition: MCDirectives.h:68
MCAssembler.h
MCObjectFileInfo.h
llvm::MachO::symtab_command
Definition: MachO.h:695
llvm::MachO::VM_PROT_WRITE
@ VM_PROT_WRITE
Definition: MachO.h:489
llvm::MCSymbol::getFragment
MCFragment * getFragment(bool SetUsed=true) const
Definition: MCSymbol.h:392
llvm::MachO::build_version_command
Definition: MachO.h:857
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
DenseMap.h
llvm::reverse
auto reverse(ContainerTy &&C, std::enable_if_t< has_rbegin< ContainerTy >::value > *=nullptr)
Definition: STLExtras.h:380
llvm::MachObjectWriter::doesSymbolRequireExternRelocation
bool doesSymbolRequireExternRelocation(const MCSymbol &S)
Definition: MachObjectWriter.cpp:57
llvm::MCVM_OSXVersionMin
@ MCVM_OSXVersionMin
.macosx_version_min
Definition: MCDirectives.h:69
llvm::MCFragment::getParent
MCSection * getParent() const
Definition: MCFragment.h:95
llvm::AMDGPU::Exp::Target
Target
Definition: SIDefines.h:858
MCFixupKindInfo.h
llvm::MachO::LoadCommandType
LoadCommandType
Definition: MachO.h:97
llvm::MCAssembler::CGProfileEntry::From
const MCSymbolRefExpr * From
Definition: MCAssembler.h:466
llvm::max
Expected< ExpressionValue > max(const ExpressionValue &Lhs, const ExpressionValue &Rhs)
Definition: FileCheck.cpp:337
llvm::MachO::N_UNDF
@ N_UNDF
Definition: MachO.h:311
RHS
Value * RHS
Definition: X86PartialReduction.cpp:76
llvm::StringTableBuilder::finalize
void finalize()
Analyze the strings and build the final table.
Definition: StringTableBuilder.cpp:128
llvm::isPowerOf2_32
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:491
llvm::MachO::S_SYMBOL_STUBS
@ S_SYMBOL_STUBS
S_SYMBOL_STUBS - Section with symbol stubs, byte size of stub in the Reserved2 field.
Definition: MachO.h:142
llvm::StringTableBuilder::getOffset
size_t getOffset(CachedHashStringRef S) const
Get the offest of a string in the string table.
Definition: StringTableBuilder.cpp:194
llvm::MachObjectWriter::writeObject
uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override
Write the object file and returns the number of bytes written.
Definition: MachObjectWriter.cpp:774
llvm::Data
@ Data
Definition: SIMachineScheduler.h:55
llvm::iplist< MCFragment >
LLVM_DEBUG
#define LLVM_DEBUG(X)
Definition: Debug.h:101
llvm::MachO::MH_MAGIC
@ MH_MAGIC
Definition: MachO.h:30
llvm::MCSection::getFragmentList
MCSection::FragmentListType & getFragmentList()
Definition: MCSection.h:166
llvm::MachO::S_ATTR_SOME_INSTRUCTIONS
@ S_ATTR_SOME_INSTRUCTIONS
S_ATTR_SOME_INSTRUCTIONS - Section contains some machine instructions.
Definition: MachO.h:208
llvm::MachObjectWriter::computeSectionAddresses
void computeSectionAddresses(const MCAssembler &Asm, const MCAsmLayout &Layout)
Definition: MachObjectWriter.cpp:644
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
llvm::ARMBuildAttrs::Section
@ Section
Legacy Tags.
Definition: ARMBuildAttributes.h:82
llvm::MCFragment
Definition: MCFragment.h:30
llvm::MCSymbol::getSection
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition: MCSymbol.h:262
MCAsmBackend.h
llvm::ModRefInfo::Ref
@ Ref
The access may reference the value stored in memory.
llvm::support::little
@ little
Definition: Endian.h:27
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
Twine.h
llvm::MCAssembler::CGProfileEntry::Count
uint64_t Count
Definition: MCAssembler.h:468
MCContext.h
MCSectionMachO.h
MCSymbol.h
llvm::support::endian::Writer::OS
raw_ostream & OS
Definition: EndianStream.h:53
llvm::dwarf::Index
Index
Definition: Dwarf.h:472
llvm::DataRegionData
Definition: MCAssembler.h:65
llvm::Log2_32
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:623
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
llvm::MachO::linkedit_data_command
Definition: MachO.h:800
llvm::StringTableBuilder::getSize
size_t getSize() const
Definition: StringTableBuilder.h:82
llvm::MachO::INDIRECT_SYMBOL_ABS
@ INDIRECT_SYMBOL_ABS
Definition: MachO.h:217
llvm::report_fatal_error
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:143
Options
const char LLVMTargetMachineRef LLVMPassBuilderOptionsRef Options
Definition: PassBuilderBindings.cpp:48
llvm::MCSymbolRefExpr::getSymbol
const MCSymbol & getSymbol() const
Definition: MCExpr.h:399
llvm::MachObjectWriter::writeAddrsigSection
void writeAddrsigSection(MCAssembler &Asm)
Definition: MachObjectWriter.cpp:757
llvm::VersionTuple
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:31
MCMachObjectWriter.h
llvm::MachObjectWriter::isFixupKindPCRel
bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind)
Definition: MachObjectWriter.cpp:76
Align
uint64_t Align
Definition: ELFObjHandler.cpp:81
llvm::MachO::S_LAZY_SYMBOL_POINTERS
@ S_LAZY_SYMBOL_POINTERS
S_LAZY_SYMBOL_POINTERS - Section with lazy symbol pointers.
Definition: MachO.h:139
llvm::MCFixupKindInfo::Flags
unsigned Flags
Flags describing additional information on this fixup kind.
Definition: MCFixupKindInfo.h:45
llvm::MCVM_TvOSVersionMin
@ MCVM_TvOSVersionMin
.tvos_version_min
Definition: MCDirectives.h:70
llvm::lltok::Kind
Kind
Definition: LLToken.h:18
llvm::MachO::HeaderFileType
HeaderFileType
Definition: MachO.h:40
llvm::MCSymbol::getIndex
uint32_t getIndex() const
Get the (implementation defined) index.
Definition: MCSymbol.h:309
llvm::support::endian::write
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular endianness.
Definition: Endian.h:97
llvm::MachO::S_NON_LAZY_SYMBOL_POINTERS
@ S_NON_LAZY_SYMBOL_POINTERS
S_NON_LAZY_SYMBOL_POINTERS - Section with non-lazy symbol pointers.
Definition: MachO.h:137
llvm::MCAssembler::const_indirect_symbol_iterator
std::vector< IndirectSymbolData >::const_iterator const_indirect_symbol_iterator
Definition: MCAssembler.h:91
llvm::MCConstantExpr
Definition: MCExpr.h:144
llvm::createMachObjectWriter
std::unique_ptr< MCObjectWriter > createMachObjectWriter(std::unique_ptr< MCMachObjectTargetWriter > MOTW, raw_pwrite_stream &OS, bool IsLittleEndian)
Construct a new Mach-O writer instance.
Definition: MachObjectWriter.cpp:1102
llvm::MachObjectWriter::executePostLayoutBinding
void executePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout) override
Perform any late binding of symbols (for example, to assign symbol indices for use when generating re...
Definition: MachObjectWriter.cpp:659
llvm::MCAsmLayout::getSectionOrder
llvm::SmallVectorImpl< MCSection * > & getSectionOrder()
Definition: MCAsmLayout.h:69
llvm::MachO::mach_header_64
Definition: MachO.h:521
llvm::MachObjectWriter::getPaddingSize
uint64_t getPaddingSize(const MCSection *SD, const MCAsmLayout &Layout) const
Definition: MachObjectWriter.cpp:122
llvm::StringTableBuilder::clear
void clear()
Definition: StringTableBuilder.cpp:189
llvm::MCAsmLayout::getSectionFileSize
uint64_t getSectionFileSize(const MCSection *Sec) const
Get the data size of the given section, as emitted to the object file.
Definition: MCFragment.cpp:204
llvm::MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl
bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm, const MCSymbol &A, const MCSymbol &B, bool InSet) const override
Definition: MachObjectWriter.cpp:667
llvm::MachO::VM_PROT_EXECUTE
@ VM_PROT_EXECUTE
Definition: MachO.h:489
llvm::MCAssembler
Definition: MCAssembler.h:73
llvm::MachObjectWriter::is64Bit
bool is64Bit() const
Definition: MCMachObjectWriter.h:171
Index
uint32_t Index
Definition: ELFObjHandler.cpp:82
uint64_t
llvm::MachO::MH_MAGIC_64
@ MH_MAGIC_64
Definition: MachO.h:32
llvm::MachObjectWriter::getFragmentAddress
uint64_t getFragmentAddress(const MCFragment *Fragment, const MCAsmLayout &Layout) const
Definition: MachObjectWriter.cpp:83
llvm::raw_pwrite_stream
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:418
llvm::MachObjectWriter::writeLinkerOptionsLoadCommand
void writeLinkerOptionsLoadCommand(const std::vector< std::string > &Options)
Definition: MachObjectWriter.cpp:432
llvm::MachO::N_INDR
@ N_INDR
Definition: MachO.h:315
LEB128.h
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::MCFixupKindInfo::FKF_IsPCRel
@ FKF_IsPCRel
Is this fixup kind PCrelative? This is used by the assembler backend to evaluate fixup values in a ta...
Definition: MCFixupKindInfo.h:19
llvm::DenseMap
Definition: DenseMap.h:716
llvm::COFF::SectionSize
@ SectionSize
Definition: COFF.h:60
llvm::MachO::MH_OBJECT
@ MH_OBJECT
Definition: MachO.h:43
llvm::MachObjectWriter::writeHeader
void writeHeader(MachO::HeaderFileType Type, unsigned NumLoadCommands, unsigned LoadCommandsSize, bool SubsectionsViaSymbols)
Definition: MachObjectWriter.cpp:135
TemplateParamKind::Type
@ Type
llvm::MachO::linker_option_command
Definition: MachO.h:882
llvm::Target::getName
const char * getName() const
getName - Get the target name.
Definition: TargetRegistry.h:367
llvm::MachObjectWriter::writeDysymtabLoadCommand
void writeDysymtabLoadCommand(uint32_t FirstLocalSymbol, uint32_t NumLocalSymbols, uint32_t FirstExternalSymbol, uint32_t NumExternalSymbols, uint32_t FirstUndefinedSymbol, uint32_t NumUndefinedSymbols, uint32_t IndirectSymbolOffset, uint32_t NumIndirectSymbols)
Definition: MachObjectWriter.cpp:280
isFixupTargetValid
static bool isFixupTargetValid(const MCValue &Target)
Definition: MachObjectWriter.cpp:456
llvm::MachObjectWriter::writeSymtabLoadCommand
void writeSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols, uint32_t StringTableOffset, uint32_t StringTableSize)
Definition: MachObjectWriter.cpp:261
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::MCFixupKindInfo
Target independent information on a fixup kind.
Definition: MCFixupKindInfo.h:15
llvm::MCAssembler::CGProfileEntry::To
const MCSymbolRefExpr * To
Definition: MCAssembler.h:467
llvm::MachO::segment_command
Definition: MachO.h:537
MCSymbolMachO.h
iterator_range.h
PreferPredicateTy::Option
Option
Definition: LoopVectorize.cpp:210
llvm::MCAssembler::const_data_region_iterator
std::vector< DataRegionData >::const_iterator const_data_region_iterator
Definition: MCAssembler.h:95
ComputeLinkerOptionsLoadCommandSize
static unsigned ComputeLinkerOptionsLoadCommandSize(const std::vector< std::string > &Options, bool is64Bit)
Definition: MachObjectWriter.cpp:423
llvm::StringTableBuilder::write
void write(raw_ostream &OS) const
Definition: StringTableBuilder.cpp:60
MCSection.h
llvm::IndirectSymbolData
Definition: MCAssembler.h:58
llvm::MCSection::getAlignment
unsigned getAlignment() const
Definition: MCSection.h:140
Fixup
PowerPC TLS Dynamic Call Fixup
Definition: PPCTLSDynamicCall.cpp:233
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:58
llvm::MCSection::isVirtualSection
virtual bool isVirtualSection() const =0
Check whether this section is "virtual", that is has no actual object file contents.
llvm::MachO::N_PEXT
@ N_PEXT
Definition: MachO.h:303
llvm::MachO::N_SECT
@ N_SECT
Definition: MachO.h:313
llvm::support::endian::Writer::write
void write(ArrayRef< value_type > Val)
Definition: EndianStream.h:56
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:143
A
* A
Definition: README_ALTIVEC.txt:89
uint32_t
llvm::MachO::segment_command_64
Definition: MachO.h:551
llvm::MCSection
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:39
llvm::MachO::VM_PROT_READ
@ VM_PROT_READ
Definition: MachO.h:489
S
add sub stmia L5 ldr r0 bl L_printf $stub Instead of a and a wouldn t it be better to do three moves *Return an aggregate type is even return S
Definition: README.txt:210
llvm::MachObjectWriter::getSymbolAddress
uint64_t getSymbolAddress(const MCSymbol &S, const MCAsmLayout &Layout) const
Definition: MachObjectWriter.cpp:89
llvm::support::endian::Writer::Endian
endianness Endian
Definition: EndianStream.h:54
llvm::MachO::N_ABS
@ N_ABS
Definition: MachO.h:312
llvm::Value::getName
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:305
llvm::MachO::MH_SUBSECTIONS_VIA_SYMBOLS
@ MH_SUBSECTIONS_VIA_SYMBOLS
Definition: MachO.h:72
llvm::MCAsmLayout::getFragmentOffset
uint64_t getFragmentOffset(const MCFragment *F) const
Get the offset of the given fragment inside its containing section.
Definition: MCFragment.cpp:96
MCAsmLayout.h
llvm::MachO::dysymtab_command
Definition: MachO.h:704
MCObjectWriter.h
llvm::MachO::section_64
Definition: MachO.h:579
Alignment.h
llvm::GraphProgram::Name
Name
Definition: GraphWriter.h:50
llvm::MCObjectWriter::reset
virtual void reset()
lifetime management
Definition: MCObjectWriter.h:47
uint16_t
llvm::MCAsmLayout
Encapsulates the layout of an assembly file at a particular point in time.
Definition: MCAsmLayout.h:28
operator<
bool operator<(const DeltaInfo &LHS, int64_t Delta)
Definition: LineTable.cpp:30
llvm::MachO::S_THREAD_LOCAL_VARIABLE_POINTERS
@ S_THREAD_LOCAL_VARIABLE_POINTERS
S_THREAD_LOCAL_VARIABLE_POINTERS - Section with pointers to thread local structures.
Definition: MachO.h:173
llvm::MCSectionMachO
This represents a section on a Mach-O system (used by Mac OS X).
Definition: MCSectionMachO.h:24
Casting.h
llvm::MCAssembler::VersionInfoType
struct { bool EmitBuildVersion VersionInfoType
MachO specific deployment target version info.
Definition: MCAssembler.h:102
llvm::StringTableBuilder::add
size_t add(CachedHashStringRef S)
Add a string to the builder.
Definition: StringTableBuilder.cpp:201
llvm::sort
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1562
llvm::MCAsmLayout::getSymbolOffset
bool getSymbolOffset(const MCSymbol &S, uint64_t &Val) const
Get the offset of the given symbol, as computed in the current layout.
Definition: MCFragment.cpp:152
llvm::MachO::mach_header
Definition: MachO.h:511
llvm::SmallVectorImpl::clear
void clear()
Definition: SmallVector.h:591
llvm::MachObjectWriter::reset
void reset() override
lifetime management
Definition: MachObjectWriter.cpp:47
MCValue.h
llvm::MachObjectWriter::W
support::endian::Writer W
Definition: MCMachObjectWriter.h:136
llvm::MachO::INDIRECT_SYMBOL_LOCAL
@ INDIRECT_SYMBOL_LOCAL
Definition: MachO.h:216
llvm::ARMBuildAttrs::Symbol
@ Symbol
Definition: ARMBuildAttributes.h:83
llvm::MCFixupKind
MCFixupKind
Extensible enumeration to represent the type of a fixup.
Definition: MCFixup.h:21
llvm::MCAssembler::getVersionInfo
const VersionInfoType & getVersionInfo() const
MachO deployment target version information.
Definition: MCAssembler.h:280
llvm::MachO::nlist_64
Definition: MachO.h:997
llvm::MachObjectWriter::findAliasedSymbol
const MCSymbol & findAliasedSymbol(const MCSymbol &Sym) const
Definition: MachObjectWriter.cpp:328
llvm::MachO::N_EXT
@ N_EXT
Definition: MachO.h:305
llvm::MachObjectWriter::getSectionAddress
uint64_t getSectionAddress(const MCSection *Sec) const
Definition: MCMachObjectWriter.h:154
llvm::MCSymbol::isInSection
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute).
Definition: MCSymbol.h:247
llvm::MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl
virtual bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm, const MCSymbol &A, const MCSymbol &B, bool InSet) const
Definition: MCObjectWriter.cpp:40
llvm::MCAssembler::getDarwinTargetVariantVersionInfo
const VersionInfoType & getDarwinTargetVariantVersionInfo() const
Definition: MCAssembler.h:302
llvm::MachObjectWriter::computeSymbolTable
void computeSymbolTable(MCAssembler &Asm, std::vector< MachSymbolData > &LocalSymbolData, std::vector< MachSymbolData > &ExternalSymbolData, std::vector< MachSymbolData > &UndefinedSymbolData)
Compute the symbol table data.
Definition: MachObjectWriter.cpp:543
llvm::raw_svector_ostream
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:662
llvm::MachObjectWriter::recordRelocation
void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target, uint64_t &FixedValue) override
Record a relocation entry.
Definition: MachObjectWriter.cpp:464
llvm::encodeULEB128
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition: LEB128.h:80
llvm::HexStyle::Asm
@ Asm
0ffh
Definition: MCInstPrinter.h:34
llvm::MCAsmLayout::getAssembler
MCAssembler & getAssembler() const
Get the assembler object this is a layout for.
Definition: MCAsmLayout.h:50
llvm::MCValue
This represents an "assembler immediate".
Definition: MCValue.h:36
MachO.h
llvm::pointee_iterator
An iterator type that allows iterating over the pointees via some other iterator.
Definition: iterator.h:320
llvm::MCAsmLayout::getSectionAddressSize
uint64_t getSectionAddressSize(const MCSection *Sec) const
Get the address space size of the given section, as it effects layout.
Definition: MCFragment.cpp:198
raw_ostream.h
llvm::MCAssembler::indirect_symbol_iterator
std::vector< IndirectSymbolData >::iterator indirect_symbol_iterator
Definition: MCAssembler.h:92
llvm::MachObjectWriter::isX86_64
bool isX86_64() const
Definition: MCMachObjectWriter.h:172
llvm::MCDataFragment
Fragment for data and encoded instructions.
Definition: MCFragment.h:241
MCExpr.h
llvm::MCFixup
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:71
getLCFromMCVM
static MachO::LoadCommandType getLCFromMCVM(MCVersionMinType Type)
Definition: MachObjectWriter.cpp:746
llvm::MachObjectWriter::writeSegmentLoadCommand
void writeSegmentLoadCommand(StringRef Name, unsigned NumSections, uint64_t VMAddr, uint64_t VMSize, uint64_t SectionDataStartOffset, uint64_t SectionDataSize, uint32_t MaxProt, uint32_t InitProt)
Write a segment load command.
Definition: MachObjectWriter.cpp:176
llvm::offsetToAlignment
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition: Alignment.h:198
llvm::MachO::version_min_command
Definition: MachO.h:836
llvm::MachObjectWriter::writeSection
void writeSection(const MCAsmLayout &Layout, const MCSection &Sec, uint64_t VMAddr, uint64_t FileOffset, unsigned Flags, uint64_t RelocationsStart, unsigned NumRelocations)
Definition: MachObjectWriter.cpp:216
llvm::Value
LLVM Value Representation.
Definition: Value.h:74
llvm::MCExpr
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
Debug.h
llvm::MCFragment::getAtom
const MCSymbol * getAtom() const
Definition: MCFragment.h:98
llvm::MCAssembler::CGProfileEntry
Definition: MCAssembler.h:465
llvm::MCEncodedFragmentWithContents::getContents
SmallVectorImpl< char > & getContents()
Definition: MCFragment.h:196
llvm::MachObjectWriter::bindIndirectSymbols
void bindIndirectSymbols(MCAssembler &Asm)
Definition: MachObjectWriter.cpp:479