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