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