e4681c0a3dc37aaa65309cb936cc25739efce120
[oota-llvm.git] / include / llvm / MC / MCMachObjectWriter.h
1 //===-- llvm/MC/MCMachObjectWriter.h - Mach Object Writer -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef LLVM_MC_MCMACHOBJECTWRITER_H
11 #define LLVM_MC_MCMACHOBJECTWRITER_H
12
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCObjectWriter.h"
17 #include "llvm/MC/StringTableBuilder.h"
18 #include "llvm/Support/DataTypes.h"
19 #include "llvm/Support/MachO.h"
20 #include <vector>
21
22 namespace llvm {
23
24 class MCSectionData;
25 class MachObjectWriter;
26
27 class MCMachObjectTargetWriter {
28   const unsigned Is64Bit : 1;
29   const uint32_t CPUType;
30   const uint32_t CPUSubtype;
31   // FIXME: Remove this, we should just always use it once we no longer care
32   // about Darwin 'as' compatibility.
33   const unsigned UseAggressiveSymbolFolding : 1;
34   unsigned LocalDifference_RIT;
35
36 protected:
37   MCMachObjectTargetWriter(bool Is64Bit_, uint32_t CPUType_,
38                            uint32_t CPUSubtype_,
39                            bool UseAggressiveSymbolFolding_ = false);
40
41   void setLocalDifferenceRelocationType(unsigned Type) {
42     LocalDifference_RIT = Type;
43   }
44
45 public:
46   virtual ~MCMachObjectTargetWriter();
47
48   /// @name Lifetime Management
49   /// @{
50
51   virtual void reset() {};
52
53   /// @}
54
55   /// @name Accessors
56   /// @{
57
58   bool is64Bit() const { return Is64Bit; }
59   bool useAggressiveSymbolFolding() const { return UseAggressiveSymbolFolding; }
60   uint32_t getCPUType() const { return CPUType; }
61   uint32_t getCPUSubtype() const { return CPUSubtype; }
62   unsigned getLocalDifferenceRelocationType() const {
63     return LocalDifference_RIT;
64   }
65
66   /// @}
67
68   /// @name API
69   /// @{
70
71   virtual void RecordRelocation(MachObjectWriter *Writer, MCAssembler &Asm,
72                                 const MCAsmLayout &Layout,
73                                 const MCFragment *Fragment,
74                                 const MCFixup &Fixup, MCValue Target,
75                                 uint64_t &FixedValue) = 0;
76
77   /// @}
78 };
79
80 class MachObjectWriter : public MCObjectWriter {
81   /// MachSymbolData - Helper struct for containing some precomputed information
82   /// on symbols.
83   struct MachSymbolData {
84     MCSymbolData *SymbolData;
85     uint64_t StringIndex;
86     uint8_t SectionIndex;
87
88     // Support lexicographic sorting.
89     bool operator<(const MachSymbolData &RHS) const;
90   };
91
92   /// The target specific Mach-O writer instance.
93   std::unique_ptr<MCMachObjectTargetWriter> TargetObjectWriter;
94
95   /// @name Relocation Data
96   /// @{
97
98   struct RelAndSymbol {
99     const MCSymbolData *Sym;
100     MachO::any_relocation_info MRE;
101     RelAndSymbol(const MCSymbolData *Sym, const MachO::any_relocation_info &MRE)
102         : Sym(Sym), MRE(MRE) {}
103   };
104
105   llvm::DenseMap<const MCSectionData *, std::vector<RelAndSymbol>> Relocations;
106   llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
107
108   /// @}
109   /// @name Symbol Table Data
110   /// @{
111
112   StringTableBuilder StringTable;
113   std::vector<MachSymbolData> LocalSymbolData;
114   std::vector<MachSymbolData> ExternalSymbolData;
115   std::vector<MachSymbolData> UndefinedSymbolData;
116
117   /// @}
118
119   MachSymbolData *findSymbolData(const MCSymbol &Sym);
120
121 public:
122   MachObjectWriter(MCMachObjectTargetWriter *MOTW, raw_ostream &_OS,
123                    bool _IsLittleEndian)
124     : MCObjectWriter(_OS, _IsLittleEndian), TargetObjectWriter(MOTW) {
125   }
126
127   /// @name Lifetime management Methods
128   /// @{
129
130   void reset() override;
131
132   /// @}
133
134   /// @name Utility Methods
135   /// @{
136
137   bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
138
139   SectionAddrMap SectionAddress;
140
141   SectionAddrMap &getSectionAddressMap() { return SectionAddress; }
142
143   uint64_t getSectionAddress(const MCSectionData* SD) const {
144     return SectionAddress.lookup(SD);
145   }
146   uint64_t getSymbolAddress(const MCSymbolData* SD,
147                             const MCAsmLayout &Layout) const;
148
149   uint64_t getFragmentAddress(const MCFragment *Fragment,
150                               const MCAsmLayout &Layout) const;
151
152   uint64_t getPaddingSize(const MCSectionData *SD,
153                           const MCAsmLayout &Layout) const;
154
155   bool doesSymbolRequireExternRelocation(const MCSymbolData *SD);
156
157   /// @}
158
159   /// @name Target Writer Proxy Accessors
160   /// @{
161
162   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
163   bool isX86_64() const {
164     uint32_t CPUType = TargetObjectWriter->getCPUType();
165     return CPUType == MachO::CPU_TYPE_X86_64;
166   }
167
168   /// @}
169
170   void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
171                    bool SubsectionsViaSymbols);
172
173   /// WriteSegmentLoadCommand - Write a segment load command.
174   ///
175   /// \param NumSections The number of sections in this segment.
176   /// \param SectionDataSize The total size of the sections.
177   void WriteSegmentLoadCommand(unsigned NumSections,
178                                uint64_t VMSize,
179                                uint64_t SectionDataStartOffset,
180                                uint64_t SectionDataSize);
181
182   void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
183                     const MCSectionData &SD, uint64_t FileOffset,
184                     uint64_t RelocationsStart, unsigned NumRelocations);
185
186   void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
187                               uint32_t StringTableOffset,
188                               uint32_t StringTableSize);
189
190   void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
191                                 uint32_t NumLocalSymbols,
192                                 uint32_t FirstExternalSymbol,
193                                 uint32_t NumExternalSymbols,
194                                 uint32_t FirstUndefinedSymbol,
195                                 uint32_t NumUndefinedSymbols,
196                                 uint32_t IndirectSymbolOffset,
197                                 uint32_t NumIndirectSymbols);
198
199   void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout);
200
201   void WriteLinkeditLoadCommand(uint32_t Type, uint32_t DataOffset,
202                                 uint32_t DataSize);
203
204   void WriteLinkerOptionsLoadCommand(const std::vector<std::string> &Options);
205
206   // FIXME: We really need to improve the relocation validation. Basically, we
207   // want to implement a separate computation which evaluates the relocation
208   // entry as the linker would, and verifies that the resultant fixup value is
209   // exactly what the encoder wanted. This will catch several classes of
210   // problems:
211   //
212   //  - Relocation entry bugs, the two algorithms are unlikely to have the same
213   //    exact bug.
214   //
215   //  - Relaxation issues, where we forget to relax something.
216   //
217   //  - Input errors, where something cannot be correctly encoded. 'as' allows
218   //    these through in many cases.
219
220   // Add a relocation to be output in the object file. At the time this is
221   // called, the symbol indexes are not know, so if the relocation refers
222   // to a symbol it should be passed as \p RelSymbol so that it can be updated
223   // afterwards. If the relocation doesn't refer to a symbol, nullptr should be
224   // used.
225   void addRelocation(const MCSymbolData *RelSymbol, const MCSectionData *SD,
226                      MachO::any_relocation_info &MRE) {
227     RelAndSymbol P(RelSymbol, MRE);
228     Relocations[SD].push_back(P);
229   }
230
231   void RecordScatteredRelocation(const MCAssembler &Asm,
232                                  const MCAsmLayout &Layout,
233                                  const MCFragment *Fragment,
234                                  const MCFixup &Fixup, MCValue Target,
235                                  unsigned Log2Size,
236                                  uint64_t &FixedValue);
237
238   void RecordTLVPRelocation(const MCAssembler &Asm,
239                             const MCAsmLayout &Layout,
240                             const MCFragment *Fragment,
241                             const MCFixup &Fixup, MCValue Target,
242                             uint64_t &FixedValue);
243
244   void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
245                         const MCFragment *Fragment, const MCFixup &Fixup,
246                         MCValue Target, bool &IsPCRel,
247                         uint64_t &FixedValue) override;
248
249   void BindIndirectSymbols(MCAssembler &Asm);
250
251   /// ComputeSymbolTable - Compute the symbol table data
252   ///
253   void ComputeSymbolTable(MCAssembler &Asm,
254                           std::vector<MachSymbolData> &LocalSymbolData,
255                           std::vector<MachSymbolData> &ExternalSymbolData,
256                           std::vector<MachSymbolData> &UndefinedSymbolData);
257
258   void computeSectionAddresses(const MCAssembler &Asm,
259                                const MCAsmLayout &Layout);
260
261   void markAbsoluteVariableSymbols(MCAssembler &Asm,
262                                    const MCAsmLayout &Layout);
263   void ExecutePostLayoutBinding(MCAssembler &Asm,
264                                 const MCAsmLayout &Layout) override;
265
266   bool IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
267                                               const MCSymbolData &DataA,
268                                               const MCFragment &FB,
269                                               bool InSet,
270                                               bool IsPCRel) const override;
271
272   void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
273 };
274
275
276 /// \brief Construct a new Mach-O writer instance.
277 ///
278 /// This routine takes ownership of the target writer subclass.
279 ///
280 /// \param MOTW - The target specific Mach-O writer subclass.
281 /// \param OS - The stream to write to.
282 /// \returns The constructed object writer.
283 MCObjectWriter *createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
284                                        raw_ostream &OS, bool IsLittleEndian);
285
286 } // End llvm namespace
287
288 #endif