Move alignment from MCSectionData to MCSection.
[oota-llvm.git] / lib / Target / ARM / MCTargetDesc / ARMMachObjectWriter.cpp
1 //===-- ARMMachObjectWriter.cpp - ARM Mach Object Writer ------------------===//
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 #include "MCTargetDesc/ARMMCTargetDesc.h"
11 #include "MCTargetDesc/ARMBaseInfo.h"
12 #include "MCTargetDesc/ARMFixupKinds.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAsmLayout.h"
15 #include "llvm/MC/MCAssembler.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCFixup.h"
19 #include "llvm/MC/MCFixupKindInfo.h"
20 #include "llvm/MC/MCMachOSymbolFlags.h"
21 #include "llvm/MC/MCMachObjectWriter.h"
22 #include "llvm/MC/MCValue.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/MachO.h"
25 using namespace llvm;
26
27 namespace {
28 class ARMMachObjectWriter : public MCMachObjectTargetWriter {
29   void RecordARMScatteredRelocation(MachObjectWriter *Writer,
30                                     const MCAssembler &Asm,
31                                     const MCAsmLayout &Layout,
32                                     const MCFragment *Fragment,
33                                     const MCFixup &Fixup,
34                                     MCValue Target,
35                                     unsigned Type,
36                                     unsigned Log2Size,
37                                     uint64_t &FixedValue);
38   void RecordARMScatteredHalfRelocation(MachObjectWriter *Writer,
39                                         const MCAssembler &Asm,
40                                         const MCAsmLayout &Layout,
41                                         const MCFragment *Fragment,
42                                         const MCFixup &Fixup, MCValue Target,
43                                         uint64_t &FixedValue);
44
45   bool requiresExternRelocation(MachObjectWriter *Writer,
46                                 const MCAssembler &Asm,
47                                 const MCFragment &Fragment, unsigned RelocType,
48                                 const MCSymbol &S, uint64_t FixedValue);
49
50 public:
51   ARMMachObjectWriter(bool Is64Bit, uint32_t CPUType,
52                       uint32_t CPUSubtype)
53     : MCMachObjectTargetWriter(Is64Bit, CPUType, CPUSubtype,
54                                /*UseAggressiveSymbolFolding=*/true) {}
55
56   void RecordRelocation(MachObjectWriter *Writer, MCAssembler &Asm,
57                         const MCAsmLayout &Layout, const MCFragment *Fragment,
58                         const MCFixup &Fixup, MCValue Target,
59                         uint64_t &FixedValue) override;
60 };
61 }
62
63 static bool getARMFixupKindMachOInfo(unsigned Kind, unsigned &RelocType,
64                               unsigned &Log2Size) {
65   RelocType = unsigned(MachO::ARM_RELOC_VANILLA);
66   Log2Size = ~0U;
67
68   switch (Kind) {
69   default:
70     return false;
71
72   case FK_Data_1:
73     Log2Size = llvm::Log2_32(1);
74     return true;
75   case FK_Data_2:
76     Log2Size = llvm::Log2_32(2);
77     return true;
78   case FK_Data_4:
79     Log2Size = llvm::Log2_32(4);
80     return true;
81   case FK_Data_8:
82     Log2Size = llvm::Log2_32(8);
83     return true;
84
85     // These fixups are expected to always be resolvable at assembly time and
86     // have no relocations supported.
87   case ARM::fixup_arm_ldst_pcrel_12:
88   case ARM::fixup_arm_pcrel_10:
89   case ARM::fixup_arm_adr_pcrel_12:
90   case ARM::fixup_arm_thumb_br:
91     return false;
92
93     // Handle 24-bit branch kinds.
94   case ARM::fixup_arm_condbranch:
95   case ARM::fixup_arm_uncondbranch:
96   case ARM::fixup_arm_uncondbl:
97   case ARM::fixup_arm_condbl:
98   case ARM::fixup_arm_blx:
99     RelocType = unsigned(MachO::ARM_RELOC_BR24);
100     // Report as 'long', even though that is not quite accurate.
101     Log2Size = llvm::Log2_32(4);
102     return true;
103
104   case ARM::fixup_t2_uncondbranch:
105   case ARM::fixup_arm_thumb_bl:
106   case ARM::fixup_arm_thumb_blx:
107     RelocType = unsigned(MachO::ARM_THUMB_RELOC_BR22);
108     Log2Size = llvm::Log2_32(4);
109     return true;
110
111   // For movw/movt r_type relocations they always have a pair following them and
112   // the r_length bits are used differently.  The encoding of the r_length is as
113   // follows:
114   //   low bit of r_length:
115   //      0 - :lower16: for movw instructions
116   //      1 - :upper16: for movt instructions
117   //   high bit of r_length:
118   //      0 - arm instructions
119   //      1 - thumb instructions
120   case ARM::fixup_arm_movt_hi16:
121     RelocType = unsigned(MachO::ARM_RELOC_HALF);
122     Log2Size = 1;
123     return true;
124   case ARM::fixup_t2_movt_hi16:
125     RelocType = unsigned(MachO::ARM_RELOC_HALF);
126     Log2Size = 3;
127     return true;
128
129   case ARM::fixup_arm_movw_lo16:
130     RelocType = unsigned(MachO::ARM_RELOC_HALF);
131     Log2Size = 0;
132     return true;
133   case ARM::fixup_t2_movw_lo16:
134     RelocType = unsigned(MachO::ARM_RELOC_HALF);
135     Log2Size = 2;
136     return true;
137   }
138 }
139
140 void ARMMachObjectWriter::
141 RecordARMScatteredHalfRelocation(MachObjectWriter *Writer,
142                                  const MCAssembler &Asm,
143                                  const MCAsmLayout &Layout,
144                                  const MCFragment *Fragment,
145                                  const MCFixup &Fixup,
146                                  MCValue Target,
147                                  uint64_t &FixedValue) {
148   uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
149   unsigned IsPCRel = Writer->isFixupKindPCRel(Asm, Fixup.getKind());
150   unsigned Type = MachO::ARM_RELOC_HALF;
151
152   // See <reloc.h>.
153   const MCSymbol *A = &Target.getSymA()->getSymbol();
154   const MCSymbolData *A_SD = &Asm.getSymbolData(*A);
155
156   if (!A_SD->getFragment())
157     Asm.getContext().reportFatalError(Fixup.getLoc(),
158                        "symbol '" + A->getName() +
159                        "' can not be undefined in a subtraction expression");
160
161   uint32_t Value = Writer->getSymbolAddress(*A, Layout);
162   uint32_t Value2 = 0;
163   uint64_t SecAddr =
164     Writer->getSectionAddress(A_SD->getFragment()->getParent());
165   FixedValue += SecAddr;
166
167   if (const MCSymbolRefExpr *B = Target.getSymB()) {
168     const MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
169
170     if (!B_SD->getFragment())
171       Asm.getContext().reportFatalError(Fixup.getLoc(),
172                          "symbol '" + B->getSymbol().getName() +
173                          "' can not be undefined in a subtraction expression");
174
175     // Select the appropriate difference relocation type.
176     Type = MachO::ARM_RELOC_HALF_SECTDIFF;
177     Value2 = Writer->getSymbolAddress(B->getSymbol(), Layout);
178     FixedValue -= Writer->getSectionAddress(B_SD->getFragment()->getParent());
179   }
180
181   // Relocations are written out in reverse order, so the PAIR comes first.
182   // ARM_RELOC_HALF and ARM_RELOC_HALF_SECTDIFF abuse the r_length field:
183   //
184   // For these two r_type relocations they always have a pair following them and
185   // the r_length bits are used differently.  The encoding of the r_length is as
186   // follows:
187   //   low bit of r_length:
188   //      0 - :lower16: for movw instructions
189   //      1 - :upper16: for movt instructions
190   //   high bit of r_length:
191   //      0 - arm instructions
192   //      1 - thumb instructions
193   // the other half of the relocated expression is in the following pair
194   // relocation entry in the low 16 bits of r_address field.
195   unsigned ThumbBit = 0;
196   unsigned MovtBit = 0;
197   switch ((unsigned)Fixup.getKind()) {
198   default: break;
199   case ARM::fixup_arm_movt_hi16:
200     MovtBit = 1;
201     // The thumb bit shouldn't be set in the 'other-half' bit of the
202     // relocation, but it will be set in FixedValue if the base symbol
203     // is a thumb function. Clear it out here.
204     if (Asm.isThumbFunc(A))
205       FixedValue &= 0xfffffffe;
206     break;
207   case ARM::fixup_t2_movt_hi16:
208     if (Asm.isThumbFunc(A))
209       FixedValue &= 0xfffffffe;
210     MovtBit = 1;
211     // Fallthrough
212   case ARM::fixup_t2_movw_lo16:
213     ThumbBit = 1;
214     break;
215   }
216
217   if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
218     uint32_t OtherHalf = MovtBit
219       ? (FixedValue & 0xffff) : ((FixedValue & 0xffff0000) >> 16);
220
221     MachO::any_relocation_info MRE;
222     MRE.r_word0 = ((OtherHalf             <<  0) |
223                    (MachO::ARM_RELOC_PAIR << 24) |
224                    (MovtBit               << 28) |
225                    (ThumbBit              << 29) |
226                    (IsPCRel               << 30) |
227                    MachO::R_SCATTERED);
228     MRE.r_word1 = Value2;
229     Writer->addRelocation(nullptr, Fragment->getParent(), MRE);
230   }
231
232   MachO::any_relocation_info MRE;
233   MRE.r_word0 = ((FixupOffset <<  0) |
234                  (Type        << 24) |
235                  (MovtBit     << 28) |
236                  (ThumbBit    << 29) |
237                  (IsPCRel     << 30) |
238                  MachO::R_SCATTERED);
239   MRE.r_word1 = Value;
240   Writer->addRelocation(nullptr, Fragment->getParent(), MRE);
241 }
242
243 void ARMMachObjectWriter::RecordARMScatteredRelocation(MachObjectWriter *Writer,
244                                                     const MCAssembler &Asm,
245                                                     const MCAsmLayout &Layout,
246                                                     const MCFragment *Fragment,
247                                                     const MCFixup &Fixup,
248                                                     MCValue Target,
249                                                     unsigned Type,
250                                                     unsigned Log2Size,
251                                                     uint64_t &FixedValue) {
252   uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
253   unsigned IsPCRel = Writer->isFixupKindPCRel(Asm, Fixup.getKind());
254
255   // See <reloc.h>.
256   const MCSymbol *A = &Target.getSymA()->getSymbol();
257   const MCSymbolData *A_SD = &Asm.getSymbolData(*A);
258
259   if (!A_SD->getFragment())
260     Asm.getContext().reportFatalError(Fixup.getLoc(),
261                        "symbol '" + A->getName() +
262                        "' can not be undefined in a subtraction expression");
263
264   uint32_t Value = Writer->getSymbolAddress(*A, Layout);
265   uint64_t SecAddr = Writer->getSectionAddress(A_SD->getFragment()->getParent());
266   FixedValue += SecAddr;
267   uint32_t Value2 = 0;
268
269   if (const MCSymbolRefExpr *B = Target.getSymB()) {
270     assert(Type == MachO::ARM_RELOC_VANILLA && "invalid reloc for 2 symbols");
271     const MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
272
273     if (!B_SD->getFragment())
274       Asm.getContext().reportFatalError(Fixup.getLoc(),
275                          "symbol '" + B->getSymbol().getName() +
276                          "' can not be undefined in a subtraction expression");
277
278     // Select the appropriate difference relocation type.
279     Type = MachO::ARM_RELOC_SECTDIFF;
280     Value2 = Writer->getSymbolAddress(B->getSymbol(), Layout);
281     FixedValue -= Writer->getSectionAddress(B_SD->getFragment()->getParent());
282   }
283
284   // Relocations are written out in reverse order, so the PAIR comes first.
285   if (Type == MachO::ARM_RELOC_SECTDIFF ||
286       Type == MachO::ARM_RELOC_LOCAL_SECTDIFF) {
287     MachO::any_relocation_info MRE;
288     MRE.r_word0 = ((0                     <<  0) |
289                    (MachO::ARM_RELOC_PAIR << 24) |
290                    (Log2Size              << 28) |
291                    (IsPCRel               << 30) |
292                    MachO::R_SCATTERED);
293     MRE.r_word1 = Value2;
294     Writer->addRelocation(nullptr, Fragment->getParent(), MRE);
295   }
296
297   MachO::any_relocation_info MRE;
298   MRE.r_word0 = ((FixupOffset <<  0) |
299                  (Type        << 24) |
300                  (Log2Size    << 28) |
301                  (IsPCRel     << 30) |
302                  MachO::R_SCATTERED);
303   MRE.r_word1 = Value;
304   Writer->addRelocation(nullptr, Fragment->getParent(), MRE);
305 }
306
307 bool ARMMachObjectWriter::requiresExternRelocation(MachObjectWriter *Writer,
308                                                    const MCAssembler &Asm,
309                                                    const MCFragment &Fragment,
310                                                    unsigned RelocType,
311                                                    const MCSymbol &S,
312                                                    uint64_t FixedValue) {
313   // Most cases can be identified purely from the symbol.
314   if (Writer->doesSymbolRequireExternRelocation(S))
315     return true;
316   int64_t Value = (int64_t)FixedValue;  // The displacement is signed.
317   int64_t Range;
318   switch (RelocType) {
319   default:
320     return false;
321   case MachO::ARM_RELOC_BR24:
322     // PC pre-adjustment of 8 for these instructions.
323     Value -= 8;
324     // ARM BL/BLX has a 25-bit offset.
325     Range = 0x1ffffff;
326     break;
327   case MachO::ARM_THUMB_RELOC_BR22:
328     // PC pre-adjustment of 4 for these instructions.
329     Value -= 4;
330     // Thumb BL/BLX has a 24-bit offset.
331     Range = 0xffffff;
332   }
333   // BL/BLX also use external relocations when an internal relocation
334   // would result in the target being out of range. This gives the linker
335   // enough information to generate a branch island.
336   const MCSectionData &SymSD = Asm.getSectionData(S.getSection());
337   Value += Writer->getSectionAddress(&SymSD);
338   Value -= Writer->getSectionAddress(Fragment.getParent());
339   // If the resultant value would be out of range for an internal relocation,
340   // use an external instead.
341   if (Value > Range || Value < -(Range + 1))
342     return true;
343   return false;
344 }
345
346 void ARMMachObjectWriter::RecordRelocation(MachObjectWriter *Writer,
347                                            MCAssembler &Asm,
348                                            const MCAsmLayout &Layout,
349                                            const MCFragment *Fragment,
350                                            const MCFixup &Fixup, MCValue Target,
351                                            uint64_t &FixedValue) {
352   unsigned IsPCRel = Writer->isFixupKindPCRel(Asm, Fixup.getKind());
353   unsigned Log2Size;
354   unsigned RelocType = MachO::ARM_RELOC_VANILLA;
355   if (!getARMFixupKindMachOInfo(Fixup.getKind(), RelocType, Log2Size))
356     // If we failed to get fixup kind info, it's because there's no legal
357     // relocation type for the fixup kind. This happens when it's a fixup that's
358     // expected to always be resolvable at assembly time and not have any
359     // relocations needed.
360     Asm.getContext().reportFatalError(Fixup.getLoc(),
361                                 "unsupported relocation on symbol");
362
363   // If this is a difference or a defined symbol plus an offset, then we need a
364   // scattered relocation entry.  Differences always require scattered
365   // relocations.
366   if (Target.getSymB()) {
367     if (RelocType == MachO::ARM_RELOC_HALF)
368       return RecordARMScatteredHalfRelocation(Writer, Asm, Layout, Fragment,
369                                               Fixup, Target, FixedValue);
370     return RecordARMScatteredRelocation(Writer, Asm, Layout, Fragment, Fixup,
371                                         Target, RelocType, Log2Size,
372                                         FixedValue);
373   }
374
375   // Get the symbol data, if any.
376   const MCSymbol *A = nullptr;
377   if (Target.getSymA())
378     A = &Target.getSymA()->getSymbol();
379
380   // FIXME: For other platforms, we need to use scattered relocations for
381   // internal relocations with offsets.  If this is an internal relocation with
382   // an offset, it also needs a scattered relocation entry.
383   //
384   // Is this right for ARM?
385   uint32_t Offset = Target.getConstant();
386   if (IsPCRel && RelocType == MachO::ARM_RELOC_VANILLA)
387     Offset += 1 << Log2Size;
388   if (Offset && A && !Writer->doesSymbolRequireExternRelocation(*A))
389     return RecordARMScatteredRelocation(Writer, Asm, Layout, Fragment, Fixup,
390                                         Target, RelocType, Log2Size,
391                                         FixedValue);
392
393   // See <reloc.h>.
394   uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
395   unsigned Index = 0;
396   unsigned Type = 0;
397   const MCSymbol *RelSymbol = nullptr;
398
399   if (Target.isAbsolute()) { // constant
400     // FIXME!
401     report_fatal_error("FIXME: relocations to absolute targets "
402                        "not yet implemented");
403   } else {
404     // Resolve constant variables.
405     if (A->isVariable()) {
406       int64_t Res;
407       if (A->getVariableValue()->EvaluateAsAbsolute(
408               Res, Layout, Writer->getSectionAddressMap())) {
409         FixedValue = Res;
410         return;
411       }
412     }
413
414     // Check whether we need an external or internal relocation.
415     if (requiresExternRelocation(Writer, Asm, *Fragment, RelocType, *A,
416                                  FixedValue)) {
417       RelSymbol = A;
418
419       // For external relocations, make sure to offset the fixup value to
420       // compensate for the addend of the symbol address, if it was
421       // undefined. This occurs with weak definitions, for example.
422       if (!A->isUndefined())
423         FixedValue -= Layout.getSymbolOffset(*A);
424     } else {
425       // The index is the section ordinal (1-based).
426       const MCSectionData &SymSD = Asm.getSectionData(A->getSection());
427       Index = SymSD.getOrdinal() + 1;
428       FixedValue += Writer->getSectionAddress(&SymSD);
429     }
430     if (IsPCRel)
431       FixedValue -= Writer->getSectionAddress(Fragment->getParent());
432
433     // The type is determined by the fixup kind.
434     Type = RelocType;
435   }
436
437   // struct relocation_info (8 bytes)
438   MachO::any_relocation_info MRE;
439   MRE.r_word0 = FixupOffset;
440   MRE.r_word1 =
441       (Index << 0) | (IsPCRel << 24) | (Log2Size << 25) | (Type << 28);
442
443   // Even when it's not a scattered relocation, movw/movt always uses
444   // a PAIR relocation.
445   if (Type == MachO::ARM_RELOC_HALF) {
446     // The other-half value only gets populated for the movt and movw
447     // relocation entries.
448     uint32_t Value = 0;
449     switch ((unsigned)Fixup.getKind()) {
450     default: break;
451     case ARM::fixup_arm_movw_lo16:
452     case ARM::fixup_t2_movw_lo16:
453       Value = (FixedValue >> 16) & 0xffff;
454       break;
455     case ARM::fixup_arm_movt_hi16:
456     case ARM::fixup_t2_movt_hi16:
457       Value = FixedValue & 0xffff;
458       break;
459     }
460     MachO::any_relocation_info MREPair;
461     MREPair.r_word0 = Value;
462     MREPair.r_word1 = ((0xffffff              <<  0) |
463                        (Log2Size              << 25) |
464                        (MachO::ARM_RELOC_PAIR << 28));
465
466     Writer->addRelocation(nullptr, Fragment->getParent(), MREPair);
467   }
468
469   Writer->addRelocation(RelSymbol, Fragment->getParent(), MRE);
470 }
471
472 MCObjectWriter *llvm::createARMMachObjectWriter(raw_pwrite_stream &OS,
473                                                 bool Is64Bit, uint32_t CPUType,
474                                                 uint32_t CPUSubtype) {
475   return createMachObjectWriter(new ARMMachObjectWriter(Is64Bit,
476                                                         CPUType,
477                                                         CPUSubtype),
478                                 OS, /*IsLittleEndian=*/true);
479 }