xref: /llvm-project-15.0.7/lld/ELF/Arch/Mips.cpp (revision 64f5f6d7)
1 //===- MIPS.cpp -----------------------------------------------------------===//
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 "OutputSections.h"
10 #include "Symbols.h"
11 #include "SyntheticSections.h"
12 #include "Target.h"
13 #include "lld/Common/ErrorHandler.h"
14 #include "llvm/BinaryFormat/ELF.h"
15 
16 using namespace llvm;
17 using namespace llvm::object;
18 using namespace llvm::ELF;
19 using namespace lld;
20 using namespace lld::elf;
21 
22 namespace {
23 template <class ELFT> class MIPS final : public TargetInfo {
24 public:
25   MIPS();
26   uint32_t calcEFlags() const override;
27   RelExpr getRelExpr(RelType type, const Symbol &s,
28                      const uint8_t *loc) const override;
29   int64_t getImplicitAddend(const uint8_t *buf, RelType type) const override;
30   RelType getDynRel(RelType type) const override;
31   void writeGotPlt(uint8_t *buf, const Symbol &s) const override;
32   void writePltHeader(uint8_t *buf) const override;
33   void writePlt(uint8_t *buf, const Symbol &sym,
34                 uint64_t pltEntryAddr) const override;
35   bool needsThunk(RelExpr expr, RelType type, const InputFile *file,
36                   uint64_t branchAddr, const Symbol &s,
37                   int64_t a) const override;
38   void relocate(uint8_t *loc, const Relocation &rel,
39                 uint64_t val) const override;
40   bool usesOnlyLowPageBits(RelType type) const override;
41 };
42 } // namespace
43 
44 template <class ELFT> MIPS<ELFT>::MIPS() {
45   gotPltHeaderEntriesNum = 2;
46   defaultMaxPageSize = 65536;
47   pltEntrySize = 16;
48   pltHeaderSize = 32;
49   copyRel = R_MIPS_COPY;
50   pltRel = R_MIPS_JUMP_SLOT;
51   needsThunks = true;
52 
53   // Set `sigrie 1` as a trap instruction.
54   write32(trapInstr.data(), 0x04170001);
55 
56   if (ELFT::Is64Bits) {
57     relativeRel = (R_MIPS_64 << 8) | R_MIPS_REL32;
58     symbolicRel = R_MIPS_64;
59     tlsGotRel = R_MIPS_TLS_TPREL64;
60     tlsModuleIndexRel = R_MIPS_TLS_DTPMOD64;
61     tlsOffsetRel = R_MIPS_TLS_DTPREL64;
62   } else {
63     relativeRel = R_MIPS_REL32;
64     symbolicRel = R_MIPS_32;
65     tlsGotRel = R_MIPS_TLS_TPREL32;
66     tlsModuleIndexRel = R_MIPS_TLS_DTPMOD32;
67     tlsOffsetRel = R_MIPS_TLS_DTPREL32;
68   }
69 }
70 
71 template <class ELFT> uint32_t MIPS<ELFT>::calcEFlags() const {
72   return calcMipsEFlags<ELFT>();
73 }
74 
75 template <class ELFT>
76 RelExpr MIPS<ELFT>::getRelExpr(RelType type, const Symbol &s,
77                                const uint8_t *loc) const {
78   // See comment in the calculateMipsRelChain.
79   if (ELFT::Is64Bits || config->mipsN32Abi)
80     type &= 0xff;
81 
82   switch (type) {
83   case R_MIPS_JALR:
84     // Older versions of clang would erroneously emit this relocation not only
85     // against functions (loaded from the GOT) but also against data symbols
86     // (e.g. a table of function pointers). When we encounter this, ignore the
87     // relocation and emit a warning instead.
88     if (!s.isFunc() && s.type != STT_NOTYPE) {
89       warn(getErrorLocation(loc) +
90            "found R_MIPS_JALR relocation against non-function symbol " +
91            toString(s) + ". This is invalid and most likely a compiler bug.");
92       return R_NONE;
93     }
94 
95     // If the target symbol is not preemptible and is not microMIPS,
96     // it might be possible to replace jalr/jr instruction by bal/b.
97     // It depends on the target symbol's offset.
98     if (!s.isPreemptible && !(s.getVA() & 0x1))
99       return R_PC;
100     return R_NONE;
101   case R_MICROMIPS_JALR:
102     return R_NONE;
103   case R_MIPS_GPREL16:
104   case R_MIPS_GPREL32:
105   case R_MICROMIPS_GPREL16:
106   case R_MICROMIPS_GPREL7_S2:
107     return R_MIPS_GOTREL;
108   case R_MIPS_26:
109   case R_MICROMIPS_26_S1:
110     return R_PLT;
111   case R_MICROMIPS_PC26_S1:
112     return R_PLT_PC;
113   case R_MIPS_HI16:
114   case R_MIPS_LO16:
115   case R_MIPS_HIGHER:
116   case R_MIPS_HIGHEST:
117   case R_MICROMIPS_HI16:
118   case R_MICROMIPS_LO16:
119     // R_MIPS_HI16/R_MIPS_LO16 relocations against _gp_disp calculate
120     // offset between start of function and 'gp' value which by default
121     // equal to the start of .got section. In that case we consider these
122     // relocations as relative.
123     if (&s == ElfSym::mipsGpDisp)
124       return R_MIPS_GOT_GP_PC;
125     if (&s == ElfSym::mipsLocalGp)
126       return R_MIPS_GOT_GP;
127     LLVM_FALLTHROUGH;
128   case R_MIPS_32:
129   case R_MIPS_64:
130   case R_MIPS_GOT_OFST:
131   case R_MIPS_SUB:
132     return R_ABS;
133   case R_MIPS_TLS_DTPREL_HI16:
134   case R_MIPS_TLS_DTPREL_LO16:
135   case R_MIPS_TLS_DTPREL32:
136   case R_MIPS_TLS_DTPREL64:
137   case R_MICROMIPS_TLS_DTPREL_HI16:
138   case R_MICROMIPS_TLS_DTPREL_LO16:
139     return R_DTPREL;
140   case R_MIPS_TLS_TPREL_HI16:
141   case R_MIPS_TLS_TPREL_LO16:
142   case R_MIPS_TLS_TPREL32:
143   case R_MIPS_TLS_TPREL64:
144   case R_MICROMIPS_TLS_TPREL_HI16:
145   case R_MICROMIPS_TLS_TPREL_LO16:
146     return R_TPREL;
147   case R_MIPS_PC32:
148   case R_MIPS_PC16:
149   case R_MIPS_PC19_S2:
150   case R_MIPS_PC21_S2:
151   case R_MIPS_PC26_S2:
152   case R_MIPS_PCHI16:
153   case R_MIPS_PCLO16:
154   case R_MICROMIPS_PC7_S1:
155   case R_MICROMIPS_PC10_S1:
156   case R_MICROMIPS_PC16_S1:
157   case R_MICROMIPS_PC18_S3:
158   case R_MICROMIPS_PC19_S2:
159   case R_MICROMIPS_PC23_S2:
160   case R_MICROMIPS_PC21_S1:
161     return R_PC;
162   case R_MIPS_GOT16:
163   case R_MICROMIPS_GOT16:
164     if (s.isLocal())
165       return R_MIPS_GOT_LOCAL_PAGE;
166     LLVM_FALLTHROUGH;
167   case R_MIPS_CALL16:
168   case R_MIPS_GOT_DISP:
169   case R_MIPS_TLS_GOTTPREL:
170   case R_MICROMIPS_CALL16:
171   case R_MICROMIPS_TLS_GOTTPREL:
172     return R_MIPS_GOT_OFF;
173   case R_MIPS_CALL_HI16:
174   case R_MIPS_CALL_LO16:
175   case R_MIPS_GOT_HI16:
176   case R_MIPS_GOT_LO16:
177   case R_MICROMIPS_CALL_HI16:
178   case R_MICROMIPS_CALL_LO16:
179   case R_MICROMIPS_GOT_HI16:
180   case R_MICROMIPS_GOT_LO16:
181     return R_MIPS_GOT_OFF32;
182   case R_MIPS_GOT_PAGE:
183     return R_MIPS_GOT_LOCAL_PAGE;
184   case R_MIPS_TLS_GD:
185   case R_MICROMIPS_TLS_GD:
186     return R_MIPS_TLSGD;
187   case R_MIPS_TLS_LDM:
188   case R_MICROMIPS_TLS_LDM:
189     return R_MIPS_TLSLD;
190   case R_MIPS_NONE:
191     return R_NONE;
192   default:
193     error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +
194           ") against symbol " + toString(s));
195     return R_NONE;
196   }
197 }
198 
199 template <class ELFT> RelType MIPS<ELFT>::getDynRel(RelType type) const {
200   if (type == symbolicRel)
201     return type;
202   return R_MIPS_NONE;
203 }
204 
205 template <class ELFT>
206 void MIPS<ELFT>::writeGotPlt(uint8_t *buf, const Symbol &) const {
207   uint64_t va = in.plt->getVA();
208   if (isMicroMips())
209     va |= 1;
210   write32(buf, va);
211 }
212 
213 template <endianness E> static uint32_t readShuffle(const uint8_t *loc) {
214   // The major opcode of a microMIPS instruction needs to appear
215   // in the first 16-bit word (lowest address) for efficient hardware
216   // decode so that it knows if the instruction is 16-bit or 32-bit
217   // as early as possible. To do so, little-endian binaries keep 16-bit
218   // words in a big-endian order. That is why we have to swap these
219   // words to get a correct value.
220   uint32_t v = read32(loc);
221   if (E == support::little)
222     return (v << 16) | (v >> 16);
223   return v;
224 }
225 
226 static void writeValue(uint8_t *loc, uint64_t v, uint8_t bitsSize,
227                        uint8_t shift) {
228   uint32_t instr = read32(loc);
229   uint32_t mask = 0xffffffff >> (32 - bitsSize);
230   uint32_t data = (instr & ~mask) | ((v >> shift) & mask);
231   write32(loc, data);
232 }
233 
234 template <endianness E>
235 static void writeShuffleValue(uint8_t *loc, uint64_t v, uint8_t bitsSize,
236                               uint8_t shift) {
237   // See comments in readShuffle for purpose of this code.
238   uint16_t *words = (uint16_t *)loc;
239   if (E == support::little)
240     std::swap(words[0], words[1]);
241 
242   writeValue(loc, v, bitsSize, shift);
243 
244   if (E == support::little)
245     std::swap(words[0], words[1]);
246 }
247 
248 template <endianness E>
249 static void writeMicroRelocation16(uint8_t *loc, uint64_t v, uint8_t bitsSize,
250                                    uint8_t shift) {
251   uint16_t instr = read16(loc);
252   uint16_t mask = 0xffff >> (16 - bitsSize);
253   uint16_t data = (instr & ~mask) | ((v >> shift) & mask);
254   write16(loc, data);
255 }
256 
257 template <class ELFT> void MIPS<ELFT>::writePltHeader(uint8_t *buf) const {
258   if (isMicroMips()) {
259     uint64_t gotPlt = in.gotPlt->getVA();
260     uint64_t plt = in.plt->getVA();
261     // Overwrite trap instructions written by Writer::writeTrapInstr.
262     memset(buf, 0, pltHeaderSize);
263 
264     write16(buf, isMipsR6() ? 0x7860 : 0x7980);  // addiupc v1, (GOTPLT) - .
265     write16(buf + 4, 0xff23);    // lw      $25, 0($3)
266     write16(buf + 8, 0x0535);    // subu16  $2,  $2, $3
267     write16(buf + 10, 0x2525);   // srl16   $2,  $2, 2
268     write16(buf + 12, 0x3302);   // addiu   $24, $2, -2
269     write16(buf + 14, 0xfffe);
270     write16(buf + 16, 0x0dff);   // move    $15, $31
271     if (isMipsR6()) {
272       write16(buf + 18, 0x0f83); // move    $28, $3
273       write16(buf + 20, 0x472b); // jalrc   $25
274       write16(buf + 22, 0x0c00); // nop
275       relocateNoSym(buf, R_MICROMIPS_PC19_S2, gotPlt - plt);
276     } else {
277       write16(buf + 18, 0x45f9); // jalrc   $25
278       write16(buf + 20, 0x0f83); // move    $28, $3
279       write16(buf + 22, 0x0c00); // nop
280       relocateNoSym(buf, R_MICROMIPS_PC23_S2, gotPlt - plt);
281     }
282     return;
283   }
284 
285   if (config->mipsN32Abi) {
286     write32(buf, 0x3c0e0000);      // lui   $14, %hi(&GOTPLT[0])
287     write32(buf + 4, 0x8dd90000);  // lw    $25, %lo(&GOTPLT[0])($14)
288     write32(buf + 8, 0x25ce0000);  // addiu $14, $14, %lo(&GOTPLT[0])
289     write32(buf + 12, 0x030ec023); // subu  $24, $24, $14
290     write32(buf + 16, 0x03e07825); // move  $15, $31
291     write32(buf + 20, 0x0018c082); // srl   $24, $24, 2
292   } else if (ELFT::Is64Bits) {
293     write32(buf, 0x3c0e0000);      // lui   $14, %hi(&GOTPLT[0])
294     write32(buf + 4, 0xddd90000);  // ld    $25, %lo(&GOTPLT[0])($14)
295     write32(buf + 8, 0x25ce0000);  // addiu $14, $14, %lo(&GOTPLT[0])
296     write32(buf + 12, 0x030ec023); // subu  $24, $24, $14
297     write32(buf + 16, 0x03e07825); // move  $15, $31
298     write32(buf + 20, 0x0018c0c2); // srl   $24, $24, 3
299   } else {
300     write32(buf, 0x3c1c0000);      // lui   $28, %hi(&GOTPLT[0])
301     write32(buf + 4, 0x8f990000);  // lw    $25, %lo(&GOTPLT[0])($28)
302     write32(buf + 8, 0x279c0000);  // addiu $28, $28, %lo(&GOTPLT[0])
303     write32(buf + 12, 0x031cc023); // subu  $24, $24, $28
304     write32(buf + 16, 0x03e07825); // move  $15, $31
305     write32(buf + 20, 0x0018c082); // srl   $24, $24, 2
306   }
307 
308   uint32_t jalrInst = config->zHazardplt ? 0x0320fc09 : 0x0320f809;
309   write32(buf + 24, jalrInst); // jalr.hb $25 or jalr $25
310   write32(buf + 28, 0x2718fffe); // subu  $24, $24, 2
311 
312   uint64_t gotPlt = in.gotPlt->getVA();
313   writeValue(buf, gotPlt + 0x8000, 16, 16);
314   writeValue(buf + 4, gotPlt, 16, 0);
315   writeValue(buf + 8, gotPlt, 16, 0);
316 }
317 
318 template <class ELFT>
319 void MIPS<ELFT>::writePlt(uint8_t *buf, const Symbol &sym,
320                           uint64_t pltEntryAddr) const {
321   uint64_t gotPltEntryAddr = sym.getGotPltVA();
322   if (isMicroMips()) {
323     // Overwrite trap instructions written by Writer::writeTrapInstr.
324     memset(buf, 0, pltEntrySize);
325 
326     if (isMipsR6()) {
327       write16(buf, 0x7840);      // addiupc $2, (GOTPLT) - .
328       write16(buf + 4, 0xff22);  // lw $25, 0($2)
329       write16(buf + 8, 0x0f02);  // move $24, $2
330       write16(buf + 10, 0x4723); // jrc $25 / jr16 $25
331       relocateNoSym(buf, R_MICROMIPS_PC19_S2, gotPltEntryAddr - pltEntryAddr);
332     } else {
333       write16(buf, 0x7900);      // addiupc $2, (GOTPLT) - .
334       write16(buf + 4, 0xff22);  // lw $25, 0($2)
335       write16(buf + 8, 0x4599);  // jrc $25 / jr16 $25
336       write16(buf + 10, 0x0f02); // move $24, $2
337       relocateNoSym(buf, R_MICROMIPS_PC23_S2, gotPltEntryAddr - pltEntryAddr);
338     }
339     return;
340   }
341 
342   uint32_t loadInst = ELFT::Is64Bits ? 0xddf90000 : 0x8df90000;
343   uint32_t jrInst = isMipsR6() ? (config->zHazardplt ? 0x03200409 : 0x03200009)
344                                : (config->zHazardplt ? 0x03200408 : 0x03200008);
345   uint32_t addInst = ELFT::Is64Bits ? 0x65f80000 : 0x25f80000;
346 
347   write32(buf, 0x3c0f0000);     // lui   $15, %hi(.got.plt entry)
348   write32(buf + 4, loadInst);   // l[wd] $25, %lo(.got.plt entry)($15)
349   write32(buf + 8, jrInst);     // jr  $25 / jr.hb $25
350   write32(buf + 12, addInst);   // [d]addiu $24, $15, %lo(.got.plt entry)
351   writeValue(buf, gotPltEntryAddr + 0x8000, 16, 16);
352   writeValue(buf + 4, gotPltEntryAddr, 16, 0);
353   writeValue(buf + 12, gotPltEntryAddr, 16, 0);
354 }
355 
356 template <class ELFT>
357 bool MIPS<ELFT>::needsThunk(RelExpr expr, RelType type, const InputFile *file,
358                             uint64_t branchAddr, const Symbol &s,
359                             int64_t /*a*/) const {
360   // Any MIPS PIC code function is invoked with its address in register $t9.
361   // So if we have a branch instruction from non-PIC code to the PIC one
362   // we cannot make the jump directly and need to create a small stubs
363   // to save the target function address.
364   // See page 3-38 ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
365   if (type != R_MIPS_26 && type != R_MIPS_PC26_S2 &&
366       type != R_MICROMIPS_26_S1 && type != R_MICROMIPS_PC26_S1)
367     return false;
368   auto *f = dyn_cast_or_null<ObjFile<ELFT>>(file);
369   if (!f)
370     return false;
371   // If current file has PIC code, LA25 stub is not required.
372   if (f->getObj().getHeader().e_flags & EF_MIPS_PIC)
373     return false;
374   auto *d = dyn_cast<Defined>(&s);
375   // LA25 is required if target file has PIC code
376   // or target symbol is a PIC symbol.
377   return d && isMipsPIC<ELFT>(d);
378 }
379 
380 template <class ELFT>
381 int64_t MIPS<ELFT>::getImplicitAddend(const uint8_t *buf, RelType type) const {
382   const endianness e = ELFT::TargetEndianness;
383   switch (type) {
384   case R_MIPS_32:
385   case R_MIPS_REL32:
386   case R_MIPS_GPREL32:
387   case R_MIPS_TLS_DTPREL32:
388   case R_MIPS_TLS_DTPMOD32:
389   case R_MIPS_TLS_TPREL32:
390     return SignExtend64<32>(read32(buf));
391   case R_MIPS_26:
392     // FIXME (simon): If the relocation target symbol is not a PLT entry
393     // we should use another expression for calculation:
394     // ((A << 2) | (P & 0xf0000000)) >> 2
395     return SignExtend64<28>(read32(buf) << 2);
396   case R_MIPS_CALL_HI16:
397   case R_MIPS_GOT16:
398   case R_MIPS_GOT_HI16:
399   case R_MIPS_HI16:
400   case R_MIPS_PCHI16:
401     return SignExtend64<16>(read32(buf)) << 16;
402   case R_MIPS_CALL16:
403   case R_MIPS_CALL_LO16:
404   case R_MIPS_GOT_LO16:
405   case R_MIPS_GPREL16:
406   case R_MIPS_LO16:
407   case R_MIPS_PCLO16:
408   case R_MIPS_TLS_DTPREL_HI16:
409   case R_MIPS_TLS_DTPREL_LO16:
410   case R_MIPS_TLS_GD:
411   case R_MIPS_TLS_GOTTPREL:
412   case R_MIPS_TLS_LDM:
413   case R_MIPS_TLS_TPREL_HI16:
414   case R_MIPS_TLS_TPREL_LO16:
415     return SignExtend64<16>(read32(buf));
416   case R_MICROMIPS_GOT16:
417   case R_MICROMIPS_HI16:
418     return SignExtend64<16>(readShuffle<e>(buf)) << 16;
419   case R_MICROMIPS_CALL16:
420   case R_MICROMIPS_GPREL16:
421   case R_MICROMIPS_LO16:
422   case R_MICROMIPS_TLS_DTPREL_HI16:
423   case R_MICROMIPS_TLS_DTPREL_LO16:
424   case R_MICROMIPS_TLS_GD:
425   case R_MICROMIPS_TLS_GOTTPREL:
426   case R_MICROMIPS_TLS_LDM:
427   case R_MICROMIPS_TLS_TPREL_HI16:
428   case R_MICROMIPS_TLS_TPREL_LO16:
429     return SignExtend64<16>(readShuffle<e>(buf));
430   case R_MICROMIPS_GPREL7_S2:
431     return SignExtend64<9>(readShuffle<e>(buf) << 2);
432   case R_MIPS_PC16:
433     return SignExtend64<18>(read32(buf) << 2);
434   case R_MIPS_PC19_S2:
435     return SignExtend64<21>(read32(buf) << 2);
436   case R_MIPS_PC21_S2:
437     return SignExtend64<23>(read32(buf) << 2);
438   case R_MIPS_PC26_S2:
439     return SignExtend64<28>(read32(buf) << 2);
440   case R_MIPS_PC32:
441     return SignExtend64<32>(read32(buf));
442   case R_MICROMIPS_26_S1:
443     return SignExtend64<27>(readShuffle<e>(buf) << 1);
444   case R_MICROMIPS_PC7_S1:
445     return SignExtend64<8>(read16(buf) << 1);
446   case R_MICROMIPS_PC10_S1:
447     return SignExtend64<11>(read16(buf) << 1);
448   case R_MICROMIPS_PC16_S1:
449     return SignExtend64<17>(readShuffle<e>(buf) << 1);
450   case R_MICROMIPS_PC18_S3:
451     return SignExtend64<21>(readShuffle<e>(buf) << 3);
452   case R_MICROMIPS_PC19_S2:
453     return SignExtend64<21>(readShuffle<e>(buf) << 2);
454   case R_MICROMIPS_PC21_S1:
455     return SignExtend64<22>(readShuffle<e>(buf) << 1);
456   case R_MICROMIPS_PC23_S2:
457     return SignExtend64<25>(readShuffle<e>(buf) << 2);
458   case R_MICROMIPS_PC26_S1:
459     return SignExtend64<27>(readShuffle<e>(buf) << 1);
460   case R_MIPS_64:
461   case R_MIPS_TLS_DTPMOD64:
462   case R_MIPS_TLS_DTPREL64:
463   case R_MIPS_TLS_TPREL64:
464   case (R_MIPS_64 << 8) | R_MIPS_REL32:
465     return read64(buf);
466   case R_MIPS_COPY:
467     return config->is64 ? read64(buf) : read32(buf);
468   case R_MIPS_NONE:
469   case R_MIPS_JUMP_SLOT:
470   case R_MIPS_JALR:
471     // These relocations are defined as not having an implicit addend.
472     return 0;
473   default:
474     internalLinkerError(getErrorLocation(buf),
475                         "cannot read addend for relocation " + toString(type));
476     return 0;
477   }
478 }
479 
480 static std::pair<uint32_t, uint64_t>
481 calculateMipsRelChain(uint8_t *loc, RelType type, uint64_t val) {
482   // MIPS N64 ABI packs multiple relocations into the single relocation
483   // record. In general, all up to three relocations can have arbitrary
484   // types. In fact, Clang and GCC uses only a few combinations. For now,
485   // we support two of them. That is allow to pass at least all LLVM
486   // test suite cases.
487   // <any relocation> / R_MIPS_SUB / R_MIPS_HI16 | R_MIPS_LO16
488   // <any relocation> / R_MIPS_64 / R_MIPS_NONE
489   // The first relocation is a 'real' relocation which is calculated
490   // using the corresponding symbol's value. The second and the third
491   // relocations used to modify result of the first one: extend it to
492   // 64-bit, extract high or low part etc. For details, see part 2.9 Relocation
493   // at the https://dmz-portal.mips.com/mw/images/8/82/007-4658-001.pdf
494   RelType type2 = (type >> 8) & 0xff;
495   RelType type3 = (type >> 16) & 0xff;
496   if (type2 == R_MIPS_NONE && type3 == R_MIPS_NONE)
497     return std::make_pair(type, val);
498   if (type2 == R_MIPS_64 && type3 == R_MIPS_NONE)
499     return std::make_pair(type2, val);
500   if (type2 == R_MIPS_SUB && (type3 == R_MIPS_HI16 || type3 == R_MIPS_LO16))
501     return std::make_pair(type3, -val);
502   error(getErrorLocation(loc) + "unsupported relocations combination " +
503         Twine(type));
504   return std::make_pair(type & 0xff, val);
505 }
506 
507 static bool isBranchReloc(RelType type) {
508   return type == R_MIPS_26 || type == R_MIPS_PC26_S2 ||
509          type == R_MIPS_PC21_S2 || type == R_MIPS_PC16;
510 }
511 
512 static bool isMicroBranchReloc(RelType type) {
513   return type == R_MICROMIPS_26_S1 || type == R_MICROMIPS_PC16_S1 ||
514          type == R_MICROMIPS_PC10_S1 || type == R_MICROMIPS_PC7_S1;
515 }
516 
517 template <class ELFT>
518 static uint64_t fixupCrossModeJump(uint8_t *loc, RelType type, uint64_t val) {
519   // Here we need to detect jump/branch from regular MIPS code
520   // to a microMIPS target and vice versa. In that cases jump
521   // instructions need to be replaced by their "cross-mode"
522   // equivalents.
523   const endianness e = ELFT::TargetEndianness;
524   bool isMicroTgt = val & 0x1;
525   bool isCrossJump = (isMicroTgt && isBranchReloc(type)) ||
526                      (!isMicroTgt && isMicroBranchReloc(type));
527   if (!isCrossJump)
528     return val;
529 
530   switch (type) {
531   case R_MIPS_26: {
532     uint32_t inst = read32(loc) >> 26;
533     if (inst == 0x3 || inst == 0x1d) { // JAL or JALX
534       writeValue(loc, 0x1d << 26, 32, 0);
535       return val;
536     }
537     break;
538   }
539   case R_MICROMIPS_26_S1: {
540     uint32_t inst = readShuffle<e>(loc) >> 26;
541     if (inst == 0x3d || inst == 0x3c) { // JAL32 or JALX32
542       val >>= 1;
543       writeShuffleValue<e>(loc, 0x3c << 26, 32, 0);
544       return val;
545     }
546     break;
547   }
548   case R_MIPS_PC26_S2:
549   case R_MIPS_PC21_S2:
550   case R_MIPS_PC16:
551   case R_MICROMIPS_PC16_S1:
552   case R_MICROMIPS_PC10_S1:
553   case R_MICROMIPS_PC7_S1:
554     // FIXME (simon): Support valid branch relocations.
555     break;
556   default:
557     llvm_unreachable("unexpected jump/branch relocation");
558   }
559 
560   error(getErrorLocation(loc) +
561         "unsupported jump/branch instruction between ISA modes referenced by " +
562         toString(type) + " relocation");
563   return val;
564 }
565 
566 template <class ELFT>
567 void MIPS<ELFT>::relocate(uint8_t *loc, const Relocation &rel,
568                           uint64_t val) const {
569   const endianness e = ELFT::TargetEndianness;
570   RelType type = rel.type;
571 
572   if (ELFT::Is64Bits || config->mipsN32Abi)
573     std::tie(type, val) = calculateMipsRelChain(loc, type, val);
574 
575   // Detect cross-mode jump/branch and fix instruction.
576   val = fixupCrossModeJump<ELFT>(loc, type, val);
577 
578   // Thread pointer and DRP offsets from the start of TLS data area.
579   // https://www.linux-mips.org/wiki/NPTL
580   if (type == R_MIPS_TLS_DTPREL_HI16 || type == R_MIPS_TLS_DTPREL_LO16 ||
581       type == R_MIPS_TLS_DTPREL32 || type == R_MIPS_TLS_DTPREL64 ||
582       type == R_MICROMIPS_TLS_DTPREL_HI16 ||
583       type == R_MICROMIPS_TLS_DTPREL_LO16) {
584     val -= 0x8000;
585   }
586 
587   switch (type) {
588   case R_MIPS_32:
589   case R_MIPS_GPREL32:
590   case R_MIPS_TLS_DTPREL32:
591   case R_MIPS_TLS_TPREL32:
592     write32(loc, val);
593     break;
594   case R_MIPS_64:
595   case R_MIPS_TLS_DTPREL64:
596   case R_MIPS_TLS_TPREL64:
597     write64(loc, val);
598     break;
599   case R_MIPS_26:
600     writeValue(loc, val, 26, 2);
601     break;
602   case R_MIPS_GOT16:
603     // The R_MIPS_GOT16 relocation's value in "relocatable" linking mode
604     // is updated addend (not a GOT index). In that case write high 16 bits
605     // to store a correct addend value.
606     if (config->relocatable) {
607       writeValue(loc, val + 0x8000, 16, 16);
608     } else {
609       checkInt(loc, val, 16, rel);
610       writeValue(loc, val, 16, 0);
611     }
612     break;
613   case R_MICROMIPS_GOT16:
614     if (config->relocatable) {
615       writeShuffleValue<e>(loc, val + 0x8000, 16, 16);
616     } else {
617       checkInt(loc, val, 16, rel);
618       writeShuffleValue<e>(loc, val, 16, 0);
619     }
620     break;
621   case R_MIPS_CALL16:
622   case R_MIPS_GOT_DISP:
623   case R_MIPS_GOT_PAGE:
624   case R_MIPS_GPREL16:
625   case R_MIPS_TLS_GD:
626   case R_MIPS_TLS_GOTTPREL:
627   case R_MIPS_TLS_LDM:
628     checkInt(loc, val, 16, rel);
629     LLVM_FALLTHROUGH;
630   case R_MIPS_CALL_LO16:
631   case R_MIPS_GOT_LO16:
632   case R_MIPS_GOT_OFST:
633   case R_MIPS_LO16:
634   case R_MIPS_PCLO16:
635   case R_MIPS_TLS_DTPREL_LO16:
636   case R_MIPS_TLS_TPREL_LO16:
637     writeValue(loc, val, 16, 0);
638     break;
639   case R_MICROMIPS_GPREL16:
640   case R_MICROMIPS_TLS_GD:
641   case R_MICROMIPS_TLS_LDM:
642     checkInt(loc, val, 16, rel);
643     writeShuffleValue<e>(loc, val, 16, 0);
644     break;
645   case R_MICROMIPS_CALL16:
646   case R_MICROMIPS_CALL_LO16:
647   case R_MICROMIPS_LO16:
648   case R_MICROMIPS_TLS_DTPREL_LO16:
649   case R_MICROMIPS_TLS_GOTTPREL:
650   case R_MICROMIPS_TLS_TPREL_LO16:
651     writeShuffleValue<e>(loc, val, 16, 0);
652     break;
653   case R_MICROMIPS_GPREL7_S2:
654     checkInt(loc, val, 7, rel);
655     writeShuffleValue<e>(loc, val, 7, 2);
656     break;
657   case R_MIPS_CALL_HI16:
658   case R_MIPS_GOT_HI16:
659   case R_MIPS_HI16:
660   case R_MIPS_PCHI16:
661   case R_MIPS_TLS_DTPREL_HI16:
662   case R_MIPS_TLS_TPREL_HI16:
663     writeValue(loc, val + 0x8000, 16, 16);
664     break;
665   case R_MICROMIPS_CALL_HI16:
666   case R_MICROMIPS_GOT_HI16:
667   case R_MICROMIPS_HI16:
668   case R_MICROMIPS_TLS_DTPREL_HI16:
669   case R_MICROMIPS_TLS_TPREL_HI16:
670     writeShuffleValue<e>(loc, val + 0x8000, 16, 16);
671     break;
672   case R_MIPS_HIGHER:
673     writeValue(loc, val + 0x80008000, 16, 32);
674     break;
675   case R_MIPS_HIGHEST:
676     writeValue(loc, val + 0x800080008000, 16, 48);
677     break;
678   case R_MIPS_JALR:
679     val -= 4;
680     // Replace jalr/jr instructions by bal/b if the target
681     // offset fits into the 18-bit range.
682     if (isInt<18>(val)) {
683       switch (read32(loc)) {
684       case 0x0320f809:  // jalr $25 => bal sym
685         write32(loc, 0x04110000 | ((val >> 2) & 0xffff));
686         break;
687       case 0x03200008:  // jr $25 => b sym
688         write32(loc, 0x10000000 | ((val >> 2) & 0xffff));
689         break;
690       }
691     }
692     break;
693   case R_MICROMIPS_JALR:
694     // Ignore this optimization relocation for now
695     break;
696   case R_MIPS_PC16:
697     checkAlignment(loc, val, 4, rel);
698     checkInt(loc, val, 18, rel);
699     writeValue(loc, val, 16, 2);
700     break;
701   case R_MIPS_PC19_S2:
702     checkAlignment(loc, val, 4, rel);
703     checkInt(loc, val, 21, rel);
704     writeValue(loc, val, 19, 2);
705     break;
706   case R_MIPS_PC21_S2:
707     checkAlignment(loc, val, 4, rel);
708     checkInt(loc, val, 23, rel);
709     writeValue(loc, val, 21, 2);
710     break;
711   case R_MIPS_PC26_S2:
712     checkAlignment(loc, val, 4, rel);
713     checkInt(loc, val, 28, rel);
714     writeValue(loc, val, 26, 2);
715     break;
716   case R_MIPS_PC32:
717     writeValue(loc, val, 32, 0);
718     break;
719   case R_MICROMIPS_26_S1:
720   case R_MICROMIPS_PC26_S1:
721     checkInt(loc, val, 27, rel);
722     writeShuffleValue<e>(loc, val, 26, 1);
723     break;
724   case R_MICROMIPS_PC7_S1:
725     checkInt(loc, val, 8, rel);
726     writeMicroRelocation16<e>(loc, val, 7, 1);
727     break;
728   case R_MICROMIPS_PC10_S1:
729     checkInt(loc, val, 11, rel);
730     writeMicroRelocation16<e>(loc, val, 10, 1);
731     break;
732   case R_MICROMIPS_PC16_S1:
733     checkInt(loc, val, 17, rel);
734     writeShuffleValue<e>(loc, val, 16, 1);
735     break;
736   case R_MICROMIPS_PC18_S3:
737     checkInt(loc, val, 21, rel);
738     writeShuffleValue<e>(loc, val, 18, 3);
739     break;
740   case R_MICROMIPS_PC19_S2:
741     checkInt(loc, val, 21, rel);
742     writeShuffleValue<e>(loc, val, 19, 2);
743     break;
744   case R_MICROMIPS_PC21_S1:
745     checkInt(loc, val, 22, rel);
746     writeShuffleValue<e>(loc, val, 21, 1);
747     break;
748   case R_MICROMIPS_PC23_S2:
749     checkInt(loc, val, 25, rel);
750     writeShuffleValue<e>(loc, val, 23, 2);
751     break;
752   default:
753     llvm_unreachable("unknown relocation");
754   }
755 }
756 
757 template <class ELFT> bool MIPS<ELFT>::usesOnlyLowPageBits(RelType type) const {
758   return type == R_MIPS_LO16 || type == R_MIPS_GOT_OFST ||
759          type == R_MICROMIPS_LO16;
760 }
761 
762 // Return true if the symbol is a PIC function.
763 template <class ELFT> bool elf::isMipsPIC(const Defined *sym) {
764   if (!sym->isFunc())
765     return false;
766 
767   if (sym->stOther & STO_MIPS_PIC)
768     return true;
769 
770   if (!sym->section)
771     return false;
772 
773   ObjFile<ELFT> *file =
774       cast<InputSectionBase>(sym->section)->template getFile<ELFT>();
775   if (!file)
776     return false;
777 
778   return file->getObj().getHeader().e_flags & EF_MIPS_PIC;
779 }
780 
781 template <class ELFT> TargetInfo *elf::getMipsTargetInfo() {
782   static MIPS<ELFT> target;
783   return &target;
784 }
785 
786 template TargetInfo *elf::getMipsTargetInfo<ELF32LE>();
787 template TargetInfo *elf::getMipsTargetInfo<ELF32BE>();
788 template TargetInfo *elf::getMipsTargetInfo<ELF64LE>();
789 template TargetInfo *elf::getMipsTargetInfo<ELF64BE>();
790 
791 template bool elf::isMipsPIC<ELF32LE>(const Defined *);
792 template bool elf::isMipsPIC<ELF32BE>(const Defined *);
793 template bool elf::isMipsPIC<ELF64LE>(const Defined *);
794 template bool elf::isMipsPIC<ELF64BE>(const Defined *);
795