xref: /llvm-project/llvm/lib/Target/Mips/MCTargetDesc/MipsELFObjectWriter.cpp (revision 6764fa78407e3b01e85e4cfd3a10792ae73d3b63)
1 //===-- MipsELFObjectWriter.cpp - Mips ELF 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/MipsBaseInfo.h"
11 #include "MCTargetDesc/MipsFixupKinds.h"
12 #include "MCTargetDesc/MipsMCTargetDesc.h"
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/MC/MCAssembler.h"
15 #include "llvm/MC/MCELFObjectWriter.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCSection.h"
18 #include "llvm/MC/MCSymbolELF.h"
19 #include "llvm/MC/MCValue.h"
20 #include "llvm/Support/ErrorHandling.h"
21 
22 using namespace llvm;
23 
24 namespace {
25 // A helper structure based on ELFRelocationEntry, used for sorting entries in
26 // the relocation table.
27 struct MipsRelocationEntry {
28   MipsRelocationEntry(const ELFRelocationEntry &R)
29       : R(R), SortOffset(R.Offset), HasMatchingHi(false) {}
30   const ELFRelocationEntry R;
31   // SortOffset equals R.Offset except for the *HI16 relocations, for which it
32   // will be set based on the R.Offset of the matching *LO16 relocation.
33   int64_t SortOffset;
34   // True when this is a *LO16 relocation chosen as a match for a *HI16
35   // relocation.
36   bool HasMatchingHi;
37 };
38 
39   class MipsELFObjectWriter : public MCELFObjectTargetWriter {
40   public:
41     MipsELFObjectWriter(bool _is64Bit, uint8_t OSABI,
42                         bool _isN64, bool IsLittleEndian);
43 
44     ~MipsELFObjectWriter() override;
45 
46     unsigned getRelocType(MCContext &Ctx, const MCValue &Target,
47                           const MCFixup &Fixup, bool IsPCRel) const override;
48     bool needsRelocateWithSymbol(const MCSymbol &Sym,
49                                  unsigned Type) const override;
50     virtual void sortRelocs(const MCAssembler &Asm,
51                             std::vector<ELFRelocationEntry> &Relocs) override;
52   };
53 }
54 
55 MipsELFObjectWriter::MipsELFObjectWriter(bool _is64Bit, uint8_t OSABI,
56                                          bool _isN64, bool IsLittleEndian)
57     : MCELFObjectTargetWriter(_is64Bit, OSABI, ELF::EM_MIPS,
58                               /*HasRelocationAddend*/ _isN64,
59                               /*IsN64*/ _isN64) {}
60 
61 MipsELFObjectWriter::~MipsELFObjectWriter() {}
62 
63 unsigned MipsELFObjectWriter::getRelocType(MCContext &Ctx,
64                                            const MCValue &Target,
65                                            const MCFixup &Fixup,
66                                            bool IsPCRel) const {
67   // Determine the type of the relocation.
68   unsigned Kind = (unsigned)Fixup.getKind();
69 
70   switch (Kind) {
71   case Mips::fixup_Mips_NONE:
72     return ELF::R_MIPS_NONE;
73   case Mips::fixup_Mips_16:
74   case FK_Data_2:
75     return IsPCRel ? ELF::R_MIPS_PC16 : ELF::R_MIPS_16;
76   case Mips::fixup_Mips_32:
77   case FK_Data_4:
78     return IsPCRel ? ELF::R_MIPS_PC32 : ELF::R_MIPS_32;
79   }
80 
81   if (IsPCRel) {
82     switch (Kind) {
83     case Mips::fixup_Mips_Branch_PCRel:
84     case Mips::fixup_Mips_PC16:
85       return ELF::R_MIPS_PC16;
86     case Mips::fixup_MICROMIPS_PC7_S1:
87       return ELF::R_MICROMIPS_PC7_S1;
88     case Mips::fixup_MICROMIPS_PC10_S1:
89       return ELF::R_MICROMIPS_PC10_S1;
90     case Mips::fixup_MICROMIPS_PC16_S1:
91       return ELF::R_MICROMIPS_PC16_S1;
92     case Mips::fixup_MICROMIPS_PC26_S1:
93       return ELF::R_MICROMIPS_PC26_S1;
94     case Mips::fixup_MICROMIPS_PC19_S2:
95       return ELF::R_MICROMIPS_PC19_S2;
96     case Mips::fixup_MIPS_PC19_S2:
97       return ELF::R_MIPS_PC19_S2;
98     case Mips::fixup_MIPS_PC18_S3:
99       return ELF::R_MIPS_PC18_S3;
100     case Mips::fixup_MIPS_PC21_S2:
101       return ELF::R_MIPS_PC21_S2;
102     case Mips::fixup_MIPS_PC26_S2:
103       return ELF::R_MIPS_PC26_S2;
104     case Mips::fixup_MIPS_PCHI16:
105       return ELF::R_MIPS_PCHI16;
106     case Mips::fixup_MIPS_PCLO16:
107       return ELF::R_MIPS_PCLO16;
108     }
109 
110     llvm_unreachable("invalid PC-relative fixup kind!");
111   }
112 
113   switch (Kind) {
114   case Mips::fixup_Mips_64:
115   case FK_Data_8:
116     return ELF::R_MIPS_64;
117   case FK_GPRel_4:
118     if (isN64()) {
119       unsigned Type = (unsigned)ELF::R_MIPS_NONE;
120       Type = setRType((unsigned)ELF::R_MIPS_GPREL32, Type);
121       Type = setRType2((unsigned)ELF::R_MIPS_64, Type);
122       Type = setRType3((unsigned)ELF::R_MIPS_NONE, Type);
123       return Type;
124     }
125     return ELF::R_MIPS_GPREL32;
126   case Mips::fixup_Mips_GPREL16:
127     return ELF::R_MIPS_GPREL16;
128   case Mips::fixup_Mips_26:
129     return ELF::R_MIPS_26;
130   case Mips::fixup_Mips_CALL16:
131     return ELF::R_MIPS_CALL16;
132   case Mips::fixup_Mips_GOT_Global:
133   case Mips::fixup_Mips_GOT_Local:
134     return ELF::R_MIPS_GOT16;
135   case Mips::fixup_Mips_HI16:
136     return ELF::R_MIPS_HI16;
137   case Mips::fixup_Mips_LO16:
138     return ELF::R_MIPS_LO16;
139   case Mips::fixup_Mips_TLSGD:
140     return ELF::R_MIPS_TLS_GD;
141   case Mips::fixup_Mips_GOTTPREL:
142     return ELF::R_MIPS_TLS_GOTTPREL;
143   case Mips::fixup_Mips_TPREL_HI:
144     return ELF::R_MIPS_TLS_TPREL_HI16;
145   case Mips::fixup_Mips_TPREL_LO:
146     return ELF::R_MIPS_TLS_TPREL_LO16;
147   case Mips::fixup_Mips_TLSLDM:
148     return ELF::R_MIPS_TLS_LDM;
149   case Mips::fixup_Mips_DTPREL_HI:
150     return ELF::R_MIPS_TLS_DTPREL_HI16;
151   case Mips::fixup_Mips_DTPREL_LO:
152     return ELF::R_MIPS_TLS_DTPREL_LO16;
153   case Mips::fixup_Mips_GOT_PAGE:
154     return ELF::R_MIPS_GOT_PAGE;
155   case Mips::fixup_Mips_GOT_OFST:
156     return ELF::R_MIPS_GOT_OFST;
157   case Mips::fixup_Mips_GOT_DISP:
158     return ELF::R_MIPS_GOT_DISP;
159   case Mips::fixup_Mips_GPOFF_HI: {
160     unsigned Type = (unsigned)ELF::R_MIPS_NONE;
161     Type = setRType((unsigned)ELF::R_MIPS_GPREL16, Type);
162     Type = setRType2((unsigned)ELF::R_MIPS_SUB, Type);
163     Type = setRType3((unsigned)ELF::R_MIPS_HI16, Type);
164     return Type;
165   }
166   case Mips::fixup_Mips_GPOFF_LO: {
167     unsigned Type = (unsigned)ELF::R_MIPS_NONE;
168     Type = setRType((unsigned)ELF::R_MIPS_GPREL16, Type);
169     Type = setRType2((unsigned)ELF::R_MIPS_SUB, Type);
170     Type = setRType3((unsigned)ELF::R_MIPS_LO16, Type);
171     return Type;
172   }
173   case Mips::fixup_Mips_HIGHER:
174     return ELF::R_MIPS_HIGHER;
175   case Mips::fixup_Mips_HIGHEST:
176     return ELF::R_MIPS_HIGHEST;
177   case Mips::fixup_Mips_GOT_HI16:
178     return ELF::R_MIPS_GOT_HI16;
179   case Mips::fixup_Mips_GOT_LO16:
180     return ELF::R_MIPS_GOT_LO16;
181   case Mips::fixup_Mips_CALL_HI16:
182     return ELF::R_MIPS_CALL_HI16;
183   case Mips::fixup_Mips_CALL_LO16:
184     return ELF::R_MIPS_CALL_LO16;
185   case Mips::fixup_MICROMIPS_26_S1:
186     return ELF::R_MICROMIPS_26_S1;
187   case Mips::fixup_MICROMIPS_HI16:
188     return ELF::R_MICROMIPS_HI16;
189   case Mips::fixup_MICROMIPS_LO16:
190     return ELF::R_MICROMIPS_LO16;
191   case Mips::fixup_MICROMIPS_GOT16:
192     return ELF::R_MICROMIPS_GOT16;
193   case Mips::fixup_MICROMIPS_CALL16:
194     return ELF::R_MICROMIPS_CALL16;
195   case Mips::fixup_MICROMIPS_GOT_DISP:
196     return ELF::R_MICROMIPS_GOT_DISP;
197   case Mips::fixup_MICROMIPS_GOT_PAGE:
198     return ELF::R_MICROMIPS_GOT_PAGE;
199   case Mips::fixup_MICROMIPS_GOT_OFST:
200     return ELF::R_MICROMIPS_GOT_OFST;
201   case Mips::fixup_MICROMIPS_TLS_GD:
202     return ELF::R_MICROMIPS_TLS_GD;
203   case Mips::fixup_MICROMIPS_TLS_LDM:
204     return ELF::R_MICROMIPS_TLS_LDM;
205   case Mips::fixup_MICROMIPS_TLS_DTPREL_HI16:
206     return ELF::R_MICROMIPS_TLS_DTPREL_HI16;
207   case Mips::fixup_MICROMIPS_TLS_DTPREL_LO16:
208     return ELF::R_MICROMIPS_TLS_DTPREL_LO16;
209   case Mips::fixup_MICROMIPS_TLS_TPREL_HI16:
210     return ELF::R_MICROMIPS_TLS_TPREL_HI16;
211   case Mips::fixup_MICROMIPS_TLS_TPREL_LO16:
212     return ELF::R_MICROMIPS_TLS_TPREL_LO16;
213   }
214 
215   llvm_unreachable("invalid fixup kind!");
216 }
217 
218 // Sort entries by SortOffset in descending order.
219 // When there are more *HI16 relocs paired with one *LO16 reloc, the 2nd rule
220 // sorts them in ascending order of R.Offset.
221 static int cmpRelMips(const MipsRelocationEntry *AP,
222                       const MipsRelocationEntry *BP) {
223   const MipsRelocationEntry &A = *AP;
224   const MipsRelocationEntry &B = *BP;
225   if (A.SortOffset != B.SortOffset)
226     return B.SortOffset - A.SortOffset;
227   if (A.R.Offset != B.R.Offset)
228     return A.R.Offset - B.R.Offset;
229   if (B.R.Type != A.R.Type)
230     return B.R.Type - A.R.Type;
231   //llvm_unreachable("ELFRelocs might be unstable!");
232   return 0;
233 }
234 
235 // For the given Reloc.Type, return the matching relocation type, as in the
236 // table below.
237 static unsigned getMatchingLoType(const MCAssembler &Asm,
238                                   const ELFRelocationEntry &Reloc) {
239   unsigned Type = Reloc.Type;
240   if (Type == ELF::R_MIPS_HI16)
241     return ELF::R_MIPS_LO16;
242   if (Type == ELF::R_MICROMIPS_HI16)
243     return ELF::R_MICROMIPS_LO16;
244   if (Type == ELF::R_MIPS16_HI16)
245     return ELF::R_MIPS16_LO16;
246 
247   if (Reloc.Symbol->getBinding() != ELF::STB_LOCAL)
248     return ELF::R_MIPS_NONE;
249 
250   if (Type == ELF::R_MIPS_GOT16)
251     return ELF::R_MIPS_LO16;
252   if (Type == ELF::R_MICROMIPS_GOT16)
253     return ELF::R_MICROMIPS_LO16;
254   if (Type == ELF::R_MIPS16_GOT16)
255     return ELF::R_MIPS16_LO16;
256 
257   return ELF::R_MIPS_NONE;
258 }
259 
260 // Return true if First needs a matching *LO16, its matching *LO16 type equals
261 // Second's type and both relocations are against the same symbol.
262 static bool areMatchingHiAndLo(const MCAssembler &Asm,
263                                const ELFRelocationEntry &First,
264                                const ELFRelocationEntry &Second) {
265   return getMatchingLoType(Asm, First) != ELF::R_MIPS_NONE &&
266          getMatchingLoType(Asm, First) == Second.Type &&
267          First.Symbol && First.Symbol == Second.Symbol;
268 }
269 
270 // Return true if MipsRelocs[Index] is a *LO16 preceded by a matching *HI16.
271 static bool
272 isPrecededByMatchingHi(const MCAssembler &Asm, uint32_t Index,
273                        std::vector<MipsRelocationEntry> &MipsRelocs) {
274   return Index < MipsRelocs.size() - 1 &&
275          areMatchingHiAndLo(Asm, MipsRelocs[Index + 1].R, MipsRelocs[Index].R);
276 }
277 
278 // Return true if MipsRelocs[Index] is a *LO16 not preceded by a matching *HI16
279 // and not chosen by a *HI16 as a match.
280 static bool isFreeLo(const MCAssembler &Asm, uint32_t Index,
281                      std::vector<MipsRelocationEntry> &MipsRelocs) {
282   return Index < MipsRelocs.size() && !MipsRelocs[Index].HasMatchingHi &&
283          !isPrecededByMatchingHi(Asm, Index, MipsRelocs);
284 }
285 
286 // Lo is chosen as a match for Hi, set their fields accordingly.
287 // Mips instructions have fixed length of at least two bytes (two for
288 // micromips/mips16, four for mips32/64), so we can set HI's SortOffset to
289 // matching LO's Offset minus one to simplify the sorting function.
290 static void setMatch(MipsRelocationEntry &Hi, MipsRelocationEntry &Lo) {
291   Lo.HasMatchingHi = true;
292   Hi.SortOffset = Lo.R.Offset - 1;
293 }
294 
295 // We sort relocation table entries by offset, except for one additional rule
296 // required by MIPS ABI: every *HI16 relocation must be immediately followed by
297 // the corresponding *LO16 relocation. We also support a GNU extension that
298 // allows more *HI16s paired with one *LO16.
299 //
300 // *HI16 relocations and their matching *LO16 are:
301 //
302 // +---------------------------------------------+-------------------+
303 // |               *HI16                         |  matching *LO16   |
304 // |---------------------------------------------+-------------------|
305 // |  R_MIPS_HI16, local R_MIPS_GOT16            |    R_MIPS_LO16    |
306 // |  R_MICROMIPS_HI16, local R_MICROMIPS_GOT16  | R_MICROMIPS_LO16  |
307 // |  R_MIPS16_HI16, local R_MIPS16_GOT16        |  R_MIPS16_LO16    |
308 // +---------------------------------------------+-------------------+
309 //
310 // (local R_*_GOT16 meaning R_*_GOT16 against the local symbol.)
311 //
312 // To handle *HI16 and *LO16 relocations, the linker needs a combined addend
313 // ("AHL") calculated from both *HI16 ("AHI") and *LO16 ("ALO") relocations:
314 // AHL = (AHI << 16) + (short)ALO;
315 //
316 // We are reusing gnu as sorting algorithm so we are emitting the relocation
317 // table sorted the same way as gnu as would sort it, for easier comparison of
318 // the generated .o files.
319 //
320 // The logic is:
321 // search the table (starting from the highest offset and going back to zero)
322 // for all *HI16 relocations that don't have a matching *LO16.
323 // For every such HI, find a matching LO with highest offset that isn't already
324 // matched with another HI. If there are no free LOs, match it with the first
325 // found (starting from lowest offset).
326 // When there are more HIs matched with one LO, sort them in descending order by
327 // offset.
328 //
329 // In other words, when searching for a matching LO:
330 // - don't look for a 'better' match for the HIs that are already followed by a
331 //   matching LO;
332 // - prefer LOs without a pair;
333 // - prefer LOs with higher offset;
334 
335 static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
336   const ELFRelocationEntry &A = *AP;
337   const ELFRelocationEntry &B = *BP;
338   if (A.Offset < B.Offset)
339     return 1;
340   if (A.Offset > B.Offset)
341     return -1;
342   assert(B.Type != A.Type && "We don't have a total order");
343   return A.Type - B.Type;
344 }
345 
346 void MipsELFObjectWriter::sortRelocs(const MCAssembler &Asm,
347                                      std::vector<ELFRelocationEntry> &Relocs) {
348   if (Relocs.size() < 2)
349     return;
350 
351   // Sorts entries by Offset in descending order.
352   array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
353 
354   // Init MipsRelocs from Relocs.
355   std::vector<MipsRelocationEntry> MipsRelocs;
356   for (unsigned I = 0, E = Relocs.size(); I != E; ++I)
357     MipsRelocs.push_back(MipsRelocationEntry(Relocs[I]));
358 
359   // Find a matching LO for all HIs that need it.
360   for (int32_t I = 0, E = MipsRelocs.size(); I != E; ++I) {
361     if (getMatchingLoType(Asm, MipsRelocs[I].R) == ELF::R_MIPS_NONE ||
362         (I > 0 && isPrecededByMatchingHi(Asm, I - 1, MipsRelocs)))
363       continue;
364 
365     int32_t MatchedLoIndex = -1;
366 
367     // Search the list in the ascending order of Offset.
368     for (int32_t J = MipsRelocs.size() - 1, N = -1; J != N; --J) {
369       // check for a match
370       if (areMatchingHiAndLo(Asm, MipsRelocs[I].R, MipsRelocs[J].R) &&
371           (MatchedLoIndex == -1 || // first match
372            // or we already have a match,
373            // but this one is with higher offset and it's free
374            (MatchedLoIndex > J && isFreeLo(Asm, J, MipsRelocs))))
375         MatchedLoIndex = J;
376     }
377 
378     if (MatchedLoIndex != -1)
379       // We have a match.
380       setMatch(MipsRelocs[I], MipsRelocs[MatchedLoIndex]);
381   }
382 
383   // SortOffsets are calculated, call the sorting function.
384   array_pod_sort(MipsRelocs.begin(), MipsRelocs.end(), cmpRelMips);
385 
386   // Copy sorted MipsRelocs back to Relocs.
387   for (unsigned I = 0, E = MipsRelocs.size(); I != E; ++I)
388     Relocs[I] = MipsRelocs[I].R;
389 }
390 
391 bool MipsELFObjectWriter::needsRelocateWithSymbol(const MCSymbol &Sym,
392                                                   unsigned Type) const {
393   // FIXME: This is extremely conservative. This really needs to use a
394   // whitelist with a clear explanation for why each realocation needs to
395   // point to the symbol, not to the section.
396   switch (Type) {
397   default:
398     return true;
399 
400   case ELF::R_MIPS_GOT16:
401   case ELF::R_MIPS16_GOT16:
402   case ELF::R_MICROMIPS_GOT16:
403     llvm_unreachable("Should have been handled already");
404 
405   // These relocations might be paired with another relocation. The pairing is
406   // done by the static linker by matching the symbol. Since we only see one
407   // relocation at a time, we have to force them to relocate with a symbol to
408   // avoid ending up with a pair where one points to a section and another
409   // points to a symbol.
410   case ELF::R_MIPS_HI16:
411   case ELF::R_MIPS16_HI16:
412   case ELF::R_MICROMIPS_HI16:
413   case ELF::R_MIPS_LO16:
414   case ELF::R_MIPS16_LO16:
415   case ELF::R_MICROMIPS_LO16:
416     return true;
417 
418   case ELF::R_MIPS_16:
419   case ELF::R_MIPS_32:
420     if (cast<MCSymbolELF>(Sym).getOther() & ELF::STO_MIPS_MICROMIPS)
421       return true;
422     // falltrough
423   case ELF::R_MIPS_26:
424   case ELF::R_MIPS_64:
425   case ELF::R_MIPS_GPREL16:
426     return false;
427   }
428 }
429 
430 MCObjectWriter *llvm::createMipsELFObjectWriter(raw_pwrite_stream &OS,
431                                                 uint8_t OSABI,
432                                                 bool IsLittleEndian,
433                                                 bool Is64Bit) {
434   MCELFObjectTargetWriter *MOTW =
435       new MipsELFObjectWriter(Is64Bit, OSABI, Is64Bit, IsLittleEndian);
436   return createELFObjectWriter(MOTW, OS, IsLittleEndian);
437 }
438