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/MipsFixupKinds.h"
11 #include "MCTargetDesc/MipsMCTargetDesc.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/BinaryFormat/ELF.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCELFObjectWriter.h"
16 #include "llvm/MC/MCFixup.h"
17 #include "llvm/MC/MCObjectWriter.h"
18 #include "llvm/MC/MCSymbolELF.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <algorithm>
26 #include <cassert>
27 #include <cstdint>
28 #include <iterator>
29 #include <list>
30 #include <utility>
31 
32 #define DEBUG_TYPE "mips-elf-object-writer"
33 
34 using namespace llvm;
35 
36 namespace {
37 
38 /// Holds additional information needed by the relocation ordering algorithm.
39 struct MipsRelocationEntry {
40   const ELFRelocationEntry R; ///< The relocation.
41   bool Matched = false;       ///< Is this relocation part of a match.
42 
43   MipsRelocationEntry(const ELFRelocationEntry &R) : R(R) {}
44 
45   void print(raw_ostream &Out) const {
46     R.print(Out);
47     Out << ", Matched=" << Matched;
48   }
49 };
50 
51 #ifndef NDEBUG
52 raw_ostream &operator<<(raw_ostream &OS, const MipsRelocationEntry &RHS) {
53   RHS.print(OS);
54   return OS;
55 }
56 #endif
57 
58 class MipsELFObjectWriter : public MCELFObjectTargetWriter {
59 public:
60   MipsELFObjectWriter(uint8_t OSABI, bool HasRelocationAddend, bool Is64);
61 
62   ~MipsELFObjectWriter() override = default;
63 
64   unsigned getRelocType(MCContext &Ctx, const MCValue &Target,
65                         const MCFixup &Fixup, bool IsPCRel) const override;
66   bool needsRelocateWithSymbol(const MCSymbol &Sym,
67                                unsigned Type) const override;
68   void sortRelocs(const MCAssembler &Asm,
69                   std::vector<ELFRelocationEntry> &Relocs) override;
70 };
71 
72 /// The possible results of the Predicate function used by find_best.
73 enum FindBestPredicateResult {
74   FindBest_NoMatch = 0,  ///< The current element is not a match.
75   FindBest_Match,        ///< The current element is a match but better ones are
76                          ///  possible.
77   FindBest_PerfectMatch, ///< The current element is an unbeatable match.
78 };
79 
80 } // end anonymous namespace
81 
82 /// Copy elements in the range [First, Last) to d1 when the predicate is true or
83 /// d2 when the predicate is false. This is essentially both std::copy_if and
84 /// std::remove_copy_if combined into a single pass.
85 template <class InputIt, class OutputIt1, class OutputIt2, class UnaryPredicate>
86 static std::pair<OutputIt1, OutputIt2> copy_if_else(InputIt First, InputIt Last,
87                                                     OutputIt1 d1, OutputIt2 d2,
88                                                     UnaryPredicate Predicate) {
89   for (InputIt I = First; I != Last; ++I) {
90     if (Predicate(*I)) {
91       *d1 = *I;
92       d1++;
93     } else {
94       *d2 = *I;
95       d2++;
96     }
97   }
98 
99   return std::make_pair(d1, d2);
100 }
101 
102 /// Find the best match in the range [First, Last).
103 ///
104 /// An element matches when Predicate(X) returns FindBest_Match or
105 /// FindBest_PerfectMatch. A value of FindBest_PerfectMatch also terminates
106 /// the search. BetterThan(A, B) is a comparator that returns true when A is a
107 /// better match than B. The return value is the position of the best match.
108 ///
109 /// This is similar to std::find_if but finds the best of multiple possible
110 /// matches.
111 template <class InputIt, class UnaryPredicate, class Comparator>
112 static InputIt find_best(InputIt First, InputIt Last, UnaryPredicate Predicate,
113                          Comparator BetterThan) {
114   InputIt Best = Last;
115 
116   for (InputIt I = First; I != Last; ++I) {
117     unsigned Matched = Predicate(*I);
118     if (Matched != FindBest_NoMatch) {
119       LLVM_DEBUG(dbgs() << std::distance(First, I) << " is a match (";
120                  I->print(dbgs()); dbgs() << ")\n");
121       if (Best == Last || BetterThan(*I, *Best)) {
122         LLVM_DEBUG(dbgs() << ".. and it beats the last one\n");
123         Best = I;
124       }
125     }
126     if (Matched == FindBest_PerfectMatch) {
127       LLVM_DEBUG(dbgs() << ".. and it is unbeatable\n");
128       break;
129     }
130   }
131 
132   return Best;
133 }
134 
135 /// Determine the low relocation that matches the given relocation.
136 /// If the relocation does not need a low relocation then the return value
137 /// is ELF::R_MIPS_NONE.
138 ///
139 /// The relocations that need a matching low part are
140 /// R_(MIPS|MICROMIPS|MIPS16)_HI16 for all symbols and
141 /// R_(MIPS|MICROMIPS|MIPS16)_GOT16 for local symbols only.
142 static unsigned getMatchingLoType(const ELFRelocationEntry &Reloc) {
143   unsigned Type = Reloc.Type;
144   if (Type == ELF::R_MIPS_HI16)
145     return ELF::R_MIPS_LO16;
146   if (Type == ELF::R_MICROMIPS_HI16)
147     return ELF::R_MICROMIPS_LO16;
148   if (Type == ELF::R_MIPS16_HI16)
149     return ELF::R_MIPS16_LO16;
150 
151   if (Reloc.OriginalSymbol &&
152       Reloc.OriginalSymbol->getBinding() != ELF::STB_LOCAL)
153     return ELF::R_MIPS_NONE;
154 
155   if (Type == ELF::R_MIPS_GOT16)
156     return ELF::R_MIPS_LO16;
157   if (Type == ELF::R_MICROMIPS_GOT16)
158     return ELF::R_MICROMIPS_LO16;
159   if (Type == ELF::R_MIPS16_GOT16)
160     return ELF::R_MIPS16_LO16;
161 
162   return ELF::R_MIPS_NONE;
163 }
164 
165 /// Determine whether a relocation (X) matches the one given in R.
166 ///
167 /// A relocation matches if:
168 /// - It's type matches that of a corresponding low part. This is provided in
169 ///   MatchingType for efficiency.
170 /// - It's based on the same symbol.
171 /// - It's offset of greater or equal to that of the one given in R.
172 ///   It should be noted that this rule assumes the programmer does not use
173 ///   offsets that exceed the alignment of the symbol. The carry-bit will be
174 ///   incorrect if this is not true.
175 ///
176 /// A matching relocation is unbeatable if:
177 /// - It is not already involved in a match.
178 /// - It's offset is exactly that of the one given in R.
179 static FindBestPredicateResult isMatchingReloc(const MipsRelocationEntry &X,
180                                                const ELFRelocationEntry &R,
181                                                unsigned MatchingType) {
182   if (X.R.Type == MatchingType && X.R.OriginalSymbol == R.OriginalSymbol) {
183     if (!X.Matched &&
184         X.R.OriginalAddend == R.OriginalAddend)
185       return FindBest_PerfectMatch;
186     else if (X.R.OriginalAddend >= R.OriginalAddend)
187       return FindBest_Match;
188   }
189   return FindBest_NoMatch;
190 }
191 
192 /// Determine whether Candidate or PreviousBest is the better match.
193 /// The return value is true if Candidate is the better match.
194 ///
195 /// A matching relocation is a better match if:
196 /// - It has a smaller addend.
197 /// - It is not already involved in a match.
198 static bool compareMatchingRelocs(const MipsRelocationEntry &Candidate,
199                                   const MipsRelocationEntry &PreviousBest) {
200   if (Candidate.R.OriginalAddend != PreviousBest.R.OriginalAddend)
201     return Candidate.R.OriginalAddend < PreviousBest.R.OriginalAddend;
202   return PreviousBest.Matched && !Candidate.Matched;
203 }
204 
205 #ifndef NDEBUG
206 /// Print all the relocations.
207 template <class Container>
208 static void dumpRelocs(const char *Prefix, const Container &Relocs) {
209   for (const auto &R : Relocs)
210     dbgs() << Prefix << R << "\n";
211 }
212 #endif
213 
214 MipsELFObjectWriter::MipsELFObjectWriter(uint8_t OSABI,
215                                          bool HasRelocationAddend, bool Is64)
216     : MCELFObjectTargetWriter(Is64, OSABI, ELF::EM_MIPS, HasRelocationAddend) {}
217 
218 unsigned MipsELFObjectWriter::getRelocType(MCContext &Ctx,
219                                            const MCValue &Target,
220                                            const MCFixup &Fixup,
221                                            bool IsPCRel) const {
222   // Determine the type of the relocation.
223   unsigned Kind = (unsigned)Fixup.getKind();
224 
225   switch (Kind) {
226   case Mips::fixup_Mips_NONE:
227     return ELF::R_MIPS_NONE;
228   case FK_Data_1:
229     Ctx.reportError(Fixup.getLoc(),
230                     "MIPS does not support one byte relocations");
231     return ELF::R_MIPS_NONE;
232   case Mips::fixup_Mips_16:
233   case FK_Data_2:
234     return IsPCRel ? ELF::R_MIPS_PC16 : ELF::R_MIPS_16;
235   case Mips::fixup_Mips_32:
236   case FK_Data_4:
237     return IsPCRel ? ELF::R_MIPS_PC32 : ELF::R_MIPS_32;
238   }
239 
240   if (IsPCRel) {
241     switch (Kind) {
242     case Mips::fixup_Mips_Branch_PCRel:
243     case Mips::fixup_Mips_PC16:
244       return ELF::R_MIPS_PC16;
245     case Mips::fixup_MICROMIPS_PC7_S1:
246       return ELF::R_MICROMIPS_PC7_S1;
247     case Mips::fixup_MICROMIPS_PC10_S1:
248       return ELF::R_MICROMIPS_PC10_S1;
249     case Mips::fixup_MICROMIPS_PC16_S1:
250       return ELF::R_MICROMIPS_PC16_S1;
251     case Mips::fixup_MICROMIPS_PC26_S1:
252       return ELF::R_MICROMIPS_PC26_S1;
253     case Mips::fixup_MICROMIPS_PC19_S2:
254       return ELF::R_MICROMIPS_PC19_S2;
255     case Mips::fixup_MICROMIPS_PC18_S3:
256       return ELF::R_MICROMIPS_PC18_S3;
257     case Mips::fixup_MICROMIPS_PC21_S1:
258       return ELF::R_MICROMIPS_PC21_S1;
259     case Mips::fixup_MIPS_PC19_S2:
260       return ELF::R_MIPS_PC19_S2;
261     case Mips::fixup_MIPS_PC18_S3:
262       return ELF::R_MIPS_PC18_S3;
263     case Mips::fixup_MIPS_PC21_S2:
264       return ELF::R_MIPS_PC21_S2;
265     case Mips::fixup_MIPS_PC26_S2:
266       return ELF::R_MIPS_PC26_S2;
267     case Mips::fixup_MIPS_PCHI16:
268       return ELF::R_MIPS_PCHI16;
269     case Mips::fixup_MIPS_PCLO16:
270       return ELF::R_MIPS_PCLO16;
271     }
272 
273     llvm_unreachable("invalid PC-relative fixup kind!");
274   }
275 
276   switch (Kind) {
277   case Mips::fixup_Mips_64:
278   case FK_Data_8:
279     return ELF::R_MIPS_64;
280   case FK_DTPRel_4:
281     return ELF::R_MIPS_TLS_DTPREL32;
282   case FK_DTPRel_8:
283     return ELF::R_MIPS_TLS_DTPREL64;
284   case FK_TPRel_4:
285     return ELF::R_MIPS_TLS_TPREL32;
286   case FK_TPRel_8:
287     return ELF::R_MIPS_TLS_TPREL64;
288   case FK_GPRel_4:
289     if (is64Bit()) {
290       unsigned Type = (unsigned)ELF::R_MIPS_NONE;
291       Type = setRType((unsigned)ELF::R_MIPS_GPREL32, Type);
292       Type = setRType2((unsigned)ELF::R_MIPS_64, Type);
293       Type = setRType3((unsigned)ELF::R_MIPS_NONE, Type);
294       return Type;
295     }
296     return ELF::R_MIPS_GPREL32;
297   case Mips::fixup_Mips_GPREL16:
298     return ELF::R_MIPS_GPREL16;
299   case Mips::fixup_Mips_26:
300     return ELF::R_MIPS_26;
301   case Mips::fixup_Mips_CALL16:
302     return ELF::R_MIPS_CALL16;
303   case Mips::fixup_Mips_GOT:
304     return ELF::R_MIPS_GOT16;
305   case Mips::fixup_Mips_HI16:
306     return ELF::R_MIPS_HI16;
307   case Mips::fixup_Mips_LO16:
308     return ELF::R_MIPS_LO16;
309   case Mips::fixup_Mips_TLSGD:
310     return ELF::R_MIPS_TLS_GD;
311   case Mips::fixup_Mips_GOTTPREL:
312     return ELF::R_MIPS_TLS_GOTTPREL;
313   case Mips::fixup_Mips_TPREL_HI:
314     return ELF::R_MIPS_TLS_TPREL_HI16;
315   case Mips::fixup_Mips_TPREL_LO:
316     return ELF::R_MIPS_TLS_TPREL_LO16;
317   case Mips::fixup_Mips_TLSLDM:
318     return ELF::R_MIPS_TLS_LDM;
319   case Mips::fixup_Mips_DTPREL_HI:
320     return ELF::R_MIPS_TLS_DTPREL_HI16;
321   case Mips::fixup_Mips_DTPREL_LO:
322     return ELF::R_MIPS_TLS_DTPREL_LO16;
323   case Mips::fixup_Mips_GOT_PAGE:
324     return ELF::R_MIPS_GOT_PAGE;
325   case Mips::fixup_Mips_GOT_OFST:
326     return ELF::R_MIPS_GOT_OFST;
327   case Mips::fixup_Mips_GOT_DISP:
328     return ELF::R_MIPS_GOT_DISP;
329   case Mips::fixup_Mips_GPOFF_HI: {
330     unsigned Type = (unsigned)ELF::R_MIPS_NONE;
331     Type = setRType((unsigned)ELF::R_MIPS_GPREL16, Type);
332     Type = setRType2((unsigned)ELF::R_MIPS_SUB, Type);
333     Type = setRType3((unsigned)ELF::R_MIPS_HI16, Type);
334     return Type;
335   }
336   case Mips::fixup_MICROMIPS_GPOFF_HI: {
337     unsigned Type = (unsigned)ELF::R_MIPS_NONE;
338     Type = setRType((unsigned)ELF::R_MICROMIPS_GPREL16, Type);
339     Type = setRType2((unsigned)ELF::R_MICROMIPS_SUB, Type);
340     Type = setRType3((unsigned)ELF::R_MICROMIPS_HI16, Type);
341     return Type;
342   }
343   case Mips::fixup_Mips_GPOFF_LO: {
344     unsigned Type = (unsigned)ELF::R_MIPS_NONE;
345     Type = setRType((unsigned)ELF::R_MIPS_GPREL16, Type);
346     Type = setRType2((unsigned)ELF::R_MIPS_SUB, Type);
347     Type = setRType3((unsigned)ELF::R_MIPS_LO16, Type);
348     return Type;
349   }
350   case Mips::fixup_MICROMIPS_GPOFF_LO: {
351     unsigned Type = (unsigned)ELF::R_MIPS_NONE;
352     Type = setRType((unsigned)ELF::R_MICROMIPS_GPREL16, Type);
353     Type = setRType2((unsigned)ELF::R_MICROMIPS_SUB, Type);
354     Type = setRType3((unsigned)ELF::R_MICROMIPS_LO16, Type);
355     return Type;
356   }
357   case Mips::fixup_Mips_HIGHER:
358     return ELF::R_MIPS_HIGHER;
359   case Mips::fixup_Mips_HIGHEST:
360     return ELF::R_MIPS_HIGHEST;
361   case Mips::fixup_Mips_SUB:
362     return ELF::R_MIPS_SUB;
363   case Mips::fixup_Mips_GOT_HI16:
364     return ELF::R_MIPS_GOT_HI16;
365   case Mips::fixup_Mips_GOT_LO16:
366     return ELF::R_MIPS_GOT_LO16;
367   case Mips::fixup_Mips_CALL_HI16:
368     return ELF::R_MIPS_CALL_HI16;
369   case Mips::fixup_Mips_CALL_LO16:
370     return ELF::R_MIPS_CALL_LO16;
371   case Mips::fixup_MICROMIPS_26_S1:
372     return ELF::R_MICROMIPS_26_S1;
373   case Mips::fixup_MICROMIPS_HI16:
374     return ELF::R_MICROMIPS_HI16;
375   case Mips::fixup_MICROMIPS_LO16:
376     return ELF::R_MICROMIPS_LO16;
377   case Mips::fixup_MICROMIPS_GOT16:
378     return ELF::R_MICROMIPS_GOT16;
379   case Mips::fixup_MICROMIPS_CALL16:
380     return ELF::R_MICROMIPS_CALL16;
381   case Mips::fixup_MICROMIPS_GOT_DISP:
382     return ELF::R_MICROMIPS_GOT_DISP;
383   case Mips::fixup_MICROMIPS_GOT_PAGE:
384     return ELF::R_MICROMIPS_GOT_PAGE;
385   case Mips::fixup_MICROMIPS_GOT_OFST:
386     return ELF::R_MICROMIPS_GOT_OFST;
387   case Mips::fixup_MICROMIPS_TLS_GD:
388     return ELF::R_MICROMIPS_TLS_GD;
389   case Mips::fixup_MICROMIPS_TLS_LDM:
390     return ELF::R_MICROMIPS_TLS_LDM;
391   case Mips::fixup_MICROMIPS_TLS_DTPREL_HI16:
392     return ELF::R_MICROMIPS_TLS_DTPREL_HI16;
393   case Mips::fixup_MICROMIPS_TLS_DTPREL_LO16:
394     return ELF::R_MICROMIPS_TLS_DTPREL_LO16;
395   case Mips::fixup_MICROMIPS_GOTTPREL:
396     return ELF::R_MICROMIPS_TLS_GOTTPREL;
397   case Mips::fixup_MICROMIPS_TLS_TPREL_HI16:
398     return ELF::R_MICROMIPS_TLS_TPREL_HI16;
399   case Mips::fixup_MICROMIPS_TLS_TPREL_LO16:
400     return ELF::R_MICROMIPS_TLS_TPREL_LO16;
401   case Mips::fixup_MICROMIPS_SUB:
402     return ELF::R_MICROMIPS_SUB;
403   case Mips::fixup_MICROMIPS_HIGHER:
404     return ELF::R_MICROMIPS_HIGHER;
405   case Mips::fixup_MICROMIPS_HIGHEST:
406     return ELF::R_MICROMIPS_HIGHEST;
407   case Mips::fixup_Mips_JALR:
408     return ELF::R_MIPS_JALR;
409   case Mips::fixup_MICROMIPS_JALR:
410     return ELF::R_MICROMIPS_JALR;
411   }
412 
413   llvm_unreachable("invalid fixup kind!");
414 }
415 
416 /// Sort relocation table entries by offset except where another order is
417 /// required by the MIPS ABI.
418 ///
419 /// MIPS has a few relocations that have an AHL component in the expression used
420 /// to evaluate them. This AHL component is an addend with the same number of
421 /// bits as a symbol value but not all of our ABI's are able to supply a
422 /// sufficiently sized addend in a single relocation.
423 ///
424 /// The O32 ABI for example, uses REL relocations which store the addend in the
425 /// section data. All the relocations with AHL components affect 16-bit fields
426 /// so the addend for a single relocation is limited to 16-bit. This ABI
427 /// resolves the limitation by linking relocations (e.g. R_MIPS_HI16 and
428 /// R_MIPS_LO16) and distributing the addend between the linked relocations. The
429 /// ABI mandates that such relocations must be next to each other in a
430 /// particular order (e.g. R_MIPS_HI16 must be immediately followed by a
431 /// matching R_MIPS_LO16) but the rule is less strict in practice.
432 ///
433 /// The de facto standard is lenient in the following ways:
434 /// - 'Immediately following' does not refer to the next relocation entry but
435 ///   the next matching relocation.
436 /// - There may be multiple high parts relocations for one low part relocation.
437 /// - There may be multiple low part relocations for one high part relocation.
438 /// - The AHL addend in each part does not have to be exactly equal as long as
439 ///   the difference does not affect the carry bit from bit 15 into 16. This is
440 ///   to allow, for example, the use of %lo(foo) and %lo(foo+4) when loading
441 ///   both halves of a long long.
442 ///
443 /// See getMatchingLoType() for a description of which high part relocations
444 /// match which low part relocations. One particular thing to note is that
445 /// R_MIPS_GOT16 and similar only have AHL addends if they refer to local
446 /// symbols.
447 ///
448 /// It should also be noted that this function is not affected by whether
449 /// the symbol was kept or rewritten into a section-relative equivalent. We
450 /// always match using the expressions from the source.
451 void MipsELFObjectWriter::sortRelocs(const MCAssembler &Asm,
452                                      std::vector<ELFRelocationEntry> &Relocs) {
453   // We do not need to sort the relocation table for RELA relocations which
454   // N32/N64 uses as the relocation addend contains the value we require,
455   // rather than it being split across a pair of relocations.
456   if (hasRelocationAddend())
457     return;
458 
459   if (Relocs.size() < 2)
460     return;
461 
462   // Sort relocations by the address they are applied to.
463   llvm::sort(Relocs,
464              [](const ELFRelocationEntry &A, const ELFRelocationEntry &B) {
465                return A.Offset < B.Offset;
466              });
467 
468   std::list<MipsRelocationEntry> Sorted;
469   std::list<ELFRelocationEntry> Remainder;
470 
471   LLVM_DEBUG(dumpRelocs("R: ", Relocs));
472 
473   // Separate the movable relocations (AHL relocations using the high bits) from
474   // the immobile relocations (everything else). This does not preserve high/low
475   // matches that already existed in the input.
476   copy_if_else(Relocs.begin(), Relocs.end(), std::back_inserter(Remainder),
477                std::back_inserter(Sorted), [](const ELFRelocationEntry &Reloc) {
478                  return getMatchingLoType(Reloc) != ELF::R_MIPS_NONE;
479                });
480 
481   for (auto &R : Remainder) {
482     LLVM_DEBUG(dbgs() << "Matching: " << R << "\n");
483 
484     unsigned MatchingType = getMatchingLoType(R);
485     assert(MatchingType != ELF::R_MIPS_NONE &&
486            "Wrong list for reloc that doesn't need a match");
487 
488     // Find the best matching relocation for the current high part.
489     // See isMatchingReloc for a description of a matching relocation and
490     // compareMatchingRelocs for a description of what 'best' means.
491     auto InsertionPoint =
492         find_best(Sorted.begin(), Sorted.end(),
493                   [&R, &MatchingType](const MipsRelocationEntry &X) {
494                     return isMatchingReloc(X, R, MatchingType);
495                   },
496                   compareMatchingRelocs);
497 
498     // If we matched then insert the high part in front of the match and mark
499     // both relocations as being involved in a match. We only mark the high
500     // part for cosmetic reasons in the debug output.
501     //
502     // If we failed to find a match then the high part is orphaned. This is not
503     // permitted since the relocation cannot be evaluated without knowing the
504     // carry-in. We can sometimes handle this using a matching low part that is
505     // already used in a match but we already cover that case in
506     // isMatchingReloc and compareMatchingRelocs. For the remaining cases we
507     // should insert the high part at the end of the list. This will cause the
508     // linker to fail but the alternative is to cause the linker to bind the
509     // high part to a semi-matching low part and silently calculate the wrong
510     // value. Unfortunately we have no means to warn the user that we did this
511     // so leave it up to the linker to complain about it.
512     if (InsertionPoint != Sorted.end())
513       InsertionPoint->Matched = true;
514     Sorted.insert(InsertionPoint, R)->Matched = true;
515   }
516 
517   LLVM_DEBUG(dumpRelocs("S: ", Sorted));
518 
519   assert(Relocs.size() == Sorted.size() && "Some relocs were not consumed");
520 
521   // Overwrite the original vector with the sorted elements. The caller expects
522   // them in reverse order.
523   unsigned CopyTo = 0;
524   for (const auto &R : reverse(Sorted))
525     Relocs[CopyTo++] = R.R;
526 }
527 
528 bool MipsELFObjectWriter::needsRelocateWithSymbol(const MCSymbol &Sym,
529                                                   unsigned Type) const {
530   // If it's a compound relocation for N64 then we need the relocation if any
531   // sub-relocation needs it.
532   if (!isUInt<8>(Type))
533     return needsRelocateWithSymbol(Sym, Type & 0xff) ||
534            needsRelocateWithSymbol(Sym, (Type >> 8) & 0xff) ||
535            needsRelocateWithSymbol(Sym, (Type >> 16) & 0xff);
536 
537   switch (Type) {
538   default:
539     errs() << Type << "\n";
540     llvm_unreachable("Unexpected relocation");
541     return true;
542 
543   // This relocation doesn't affect the section data.
544   case ELF::R_MIPS_NONE:
545     return false;
546 
547   // On REL ABI's (e.g. O32), these relocations form pairs. The pairing is done
548   // by the static linker by matching the symbol and offset.
549   // We only see one relocation at a time but it's still safe to relocate with
550   // the section so long as both relocations make the same decision.
551   //
552   // Some older linkers may require the symbol for particular cases. Such cases
553   // are not supported yet but can be added as required.
554   case ELF::R_MIPS_GOT16:
555   case ELF::R_MIPS16_GOT16:
556   case ELF::R_MICROMIPS_GOT16:
557   case ELF::R_MIPS_HIGHER:
558   case ELF::R_MIPS_HIGHEST:
559   case ELF::R_MIPS_HI16:
560   case ELF::R_MIPS16_HI16:
561   case ELF::R_MICROMIPS_HI16:
562   case ELF::R_MIPS_LO16:
563   case ELF::R_MIPS16_LO16:
564   case ELF::R_MICROMIPS_LO16:
565     // FIXME: It should be safe to return false for the STO_MIPS_MICROMIPS but
566     //        we neglect to handle the adjustment to the LSB of the addend that
567     //        it causes in applyFixup() and similar.
568     if (cast<MCSymbolELF>(Sym).getOther() & ELF::STO_MIPS_MICROMIPS)
569       return true;
570     return false;
571 
572   case ELF::R_MIPS_GOT_PAGE:
573   case ELF::R_MICROMIPS_GOT_PAGE:
574   case ELF::R_MIPS_GOT_OFST:
575   case ELF::R_MICROMIPS_GOT_OFST:
576   case ELF::R_MIPS_16:
577   case ELF::R_MIPS_32:
578   case ELF::R_MIPS_GPREL32:
579     if (cast<MCSymbolELF>(Sym).getOther() & ELF::STO_MIPS_MICROMIPS)
580       return true;
581     LLVM_FALLTHROUGH;
582   case ELF::R_MIPS_26:
583   case ELF::R_MIPS_64:
584   case ELF::R_MIPS_GPREL16:
585   case ELF::R_MIPS_PC16:
586   case ELF::R_MIPS_SUB:
587     return false;
588 
589   // FIXME: Many of these relocations should probably return false but this
590   //        hasn't been confirmed to be safe yet.
591   case ELF::R_MIPS_REL32:
592   case ELF::R_MIPS_LITERAL:
593   case ELF::R_MIPS_CALL16:
594   case ELF::R_MIPS_SHIFT5:
595   case ELF::R_MIPS_SHIFT6:
596   case ELF::R_MIPS_GOT_DISP:
597   case ELF::R_MIPS_GOT_HI16:
598   case ELF::R_MIPS_GOT_LO16:
599   case ELF::R_MIPS_INSERT_A:
600   case ELF::R_MIPS_INSERT_B:
601   case ELF::R_MIPS_DELETE:
602   case ELF::R_MIPS_CALL_HI16:
603   case ELF::R_MIPS_CALL_LO16:
604   case ELF::R_MIPS_SCN_DISP:
605   case ELF::R_MIPS_REL16:
606   case ELF::R_MIPS_ADD_IMMEDIATE:
607   case ELF::R_MIPS_PJUMP:
608   case ELF::R_MIPS_RELGOT:
609   case ELF::R_MIPS_JALR:
610   case ELF::R_MIPS_TLS_DTPMOD32:
611   case ELF::R_MIPS_TLS_DTPREL32:
612   case ELF::R_MIPS_TLS_DTPMOD64:
613   case ELF::R_MIPS_TLS_DTPREL64:
614   case ELF::R_MIPS_TLS_GD:
615   case ELF::R_MIPS_TLS_LDM:
616   case ELF::R_MIPS_TLS_DTPREL_HI16:
617   case ELF::R_MIPS_TLS_DTPREL_LO16:
618   case ELF::R_MIPS_TLS_GOTTPREL:
619   case ELF::R_MIPS_TLS_TPREL32:
620   case ELF::R_MIPS_TLS_TPREL64:
621   case ELF::R_MIPS_TLS_TPREL_HI16:
622   case ELF::R_MIPS_TLS_TPREL_LO16:
623   case ELF::R_MIPS_GLOB_DAT:
624   case ELF::R_MIPS_PC21_S2:
625   case ELF::R_MIPS_PC26_S2:
626   case ELF::R_MIPS_PC18_S3:
627   case ELF::R_MIPS_PC19_S2:
628   case ELF::R_MIPS_PCHI16:
629   case ELF::R_MIPS_PCLO16:
630   case ELF::R_MIPS_COPY:
631   case ELF::R_MIPS_JUMP_SLOT:
632   case ELF::R_MIPS_NUM:
633   case ELF::R_MIPS_PC32:
634   case ELF::R_MIPS_EH:
635   case ELF::R_MICROMIPS_26_S1:
636   case ELF::R_MICROMIPS_GPREL16:
637   case ELF::R_MICROMIPS_LITERAL:
638   case ELF::R_MICROMIPS_PC7_S1:
639   case ELF::R_MICROMIPS_PC10_S1:
640   case ELF::R_MICROMIPS_PC16_S1:
641   case ELF::R_MICROMIPS_CALL16:
642   case ELF::R_MICROMIPS_GOT_DISP:
643   case ELF::R_MICROMIPS_GOT_HI16:
644   case ELF::R_MICROMIPS_GOT_LO16:
645   case ELF::R_MICROMIPS_SUB:
646   case ELF::R_MICROMIPS_HIGHER:
647   case ELF::R_MICROMIPS_HIGHEST:
648   case ELF::R_MICROMIPS_CALL_HI16:
649   case ELF::R_MICROMIPS_CALL_LO16:
650   case ELF::R_MICROMIPS_SCN_DISP:
651   case ELF::R_MICROMIPS_JALR:
652   case ELF::R_MICROMIPS_HI0_LO16:
653   case ELF::R_MICROMIPS_TLS_GD:
654   case ELF::R_MICROMIPS_TLS_LDM:
655   case ELF::R_MICROMIPS_TLS_DTPREL_HI16:
656   case ELF::R_MICROMIPS_TLS_DTPREL_LO16:
657   case ELF::R_MICROMIPS_TLS_GOTTPREL:
658   case ELF::R_MICROMIPS_TLS_TPREL_HI16:
659   case ELF::R_MICROMIPS_TLS_TPREL_LO16:
660   case ELF::R_MICROMIPS_GPREL7_S2:
661   case ELF::R_MICROMIPS_PC23_S2:
662   case ELF::R_MICROMIPS_PC21_S1:
663   case ELF::R_MICROMIPS_PC26_S1:
664   case ELF::R_MICROMIPS_PC18_S3:
665   case ELF::R_MICROMIPS_PC19_S2:
666     return true;
667 
668   // FIXME: Many of these should probably return false but MIPS16 isn't
669   //        supported by the integrated assembler.
670   case ELF::R_MIPS16_26:
671   case ELF::R_MIPS16_GPREL:
672   case ELF::R_MIPS16_CALL16:
673   case ELF::R_MIPS16_TLS_GD:
674   case ELF::R_MIPS16_TLS_LDM:
675   case ELF::R_MIPS16_TLS_DTPREL_HI16:
676   case ELF::R_MIPS16_TLS_DTPREL_LO16:
677   case ELF::R_MIPS16_TLS_GOTTPREL:
678   case ELF::R_MIPS16_TLS_TPREL_HI16:
679   case ELF::R_MIPS16_TLS_TPREL_LO16:
680     llvm_unreachable("Unsupported MIPS16 relocation");
681     return true;
682   }
683 }
684 
685 std::unique_ptr<MCObjectTargetWriter>
686 llvm::createMipsELFObjectWriter(const Triple &TT, bool IsN32) {
687   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
688   bool IsN64 = TT.isArch64Bit() && !IsN32;
689   bool HasRelocationAddend = TT.isArch64Bit();
690   return llvm::make_unique<MipsELFObjectWriter>(OSABI, HasRelocationAddend,
691                                                 IsN64);
692 }
693