1 //===-- HexagonAsmBackend.cpp - Hexagon Assembler Backend -----------------===//
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 "HexagonFixupKinds.h"
10 #include "MCTargetDesc/HexagonBaseInfo.h"
11 #include "MCTargetDesc/HexagonMCChecker.h"
12 #include "MCTargetDesc/HexagonMCCodeEmitter.h"
13 #include "MCTargetDesc/HexagonMCInstrInfo.h"
14 #include "MCTargetDesc/HexagonMCShuffler.h"
15 #include "MCTargetDesc/HexagonMCTargetDesc.h"
16 #include "llvm/MC/MCAsmBackend.h"
17 #include "llvm/MC/MCAsmLayout.h"
18 #include "llvm/MC/MCAssembler.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCELFObjectWriter.h"
21 #include "llvm/MC/MCFixupKindInfo.h"
22 #include "llvm/MC/MCInstrInfo.h"
23 #include "llvm/MC/MCObjectWriter.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/TargetRegistry.h"
26 
27 #include <sstream>
28 
29 using namespace llvm;
30 using namespace Hexagon;
31 
32 #define DEBUG_TYPE "hexagon-asm-backend"
33 
34 static cl::opt<bool> DisableFixup
35   ("mno-fixup", cl::desc("Disable fixing up resolved relocations for Hexagon"));
36 
37 namespace {
38 
39 class HexagonAsmBackend : public MCAsmBackend {
40   uint8_t OSABI;
41   StringRef CPU;
42   mutable uint64_t relaxedCnt;
43   std::unique_ptr <MCInstrInfo> MCII;
44   std::unique_ptr <MCInst *> RelaxTarget;
45   MCInst * Extender;
46 
47   void ReplaceInstruction(MCCodeEmitter &E, MCRelaxableFragment &RF,
48                           MCInst &HMB) const {
49     SmallVector<MCFixup, 4> Fixups;
50     SmallString<256> Code;
51     raw_svector_ostream VecOS(Code);
52     E.encodeInstruction(HMB, VecOS, Fixups, *RF.getSubtargetInfo());
53 
54     // Update the fragment.
55     RF.setInst(HMB);
56     RF.getContents() = Code;
57     RF.getFixups() = Fixups;
58   }
59 
60 public:
61   HexagonAsmBackend(const Target &T, const Triple &TT, uint8_t OSABI,
62                     StringRef CPU)
63       : MCAsmBackend(support::little), OSABI(OSABI), CPU(CPU), relaxedCnt(0),
64         MCII(T.createMCInstrInfo()), RelaxTarget(new MCInst *),
65         Extender(nullptr) {}
66 
67   std::unique_ptr<MCObjectTargetWriter>
68   createObjectTargetWriter() const override {
69     return createHexagonELFObjectWriter(OSABI, CPU);
70   }
71 
72   void setExtender(MCContext &Context) const {
73     if (Extender == nullptr)
74       const_cast<HexagonAsmBackend *>(this)->Extender = new (Context) MCInst;
75   }
76 
77   MCInst *takeExtender() const {
78     assert(Extender != nullptr);
79     MCInst * Result = Extender;
80     const_cast<HexagonAsmBackend *>(this)->Extender = nullptr;
81     return Result;
82   }
83 
84   unsigned getNumFixupKinds() const override {
85     return Hexagon::NumTargetFixupKinds;
86   }
87 
88   const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override {
89     const static MCFixupKindInfo Infos[Hexagon::NumTargetFixupKinds] = {
90       // This table *must* be in same the order of fixup_* kinds in
91       // HexagonFixupKinds.h.
92       //
93       // namei                          offset  bits    flags
94       { "fixup_Hexagon_B22_PCREL",      0,      32,     MCFixupKindInfo::FKF_IsPCRel },
95       { "fixup_Hexagon_B15_PCREL",      0,      32,     MCFixupKindInfo::FKF_IsPCRel },
96       { "fixup_Hexagon_B7_PCREL",       0,      32,     MCFixupKindInfo::FKF_IsPCRel },
97       { "fixup_Hexagon_LO16",           0,      32,     0 },
98       { "fixup_Hexagon_HI16",           0,      32,     0 },
99       { "fixup_Hexagon_32",             0,      32,     0 },
100       { "fixup_Hexagon_16",             0,      32,     0 },
101       { "fixup_Hexagon_8",              0,      32,     0 },
102       { "fixup_Hexagon_GPREL16_0",      0,      32,     0 },
103       { "fixup_Hexagon_GPREL16_1",      0,      32,     0 },
104       { "fixup_Hexagon_GPREL16_2",      0,      32,     0 },
105       { "fixup_Hexagon_GPREL16_3",      0,      32,     0 },
106       { "fixup_Hexagon_HL16",           0,      32,     0 },
107       { "fixup_Hexagon_B13_PCREL",      0,      32,     MCFixupKindInfo::FKF_IsPCRel },
108       { "fixup_Hexagon_B9_PCREL",       0,      32,     MCFixupKindInfo::FKF_IsPCRel },
109       { "fixup_Hexagon_B32_PCREL_X",    0,      32,     MCFixupKindInfo::FKF_IsPCRel },
110       { "fixup_Hexagon_32_6_X",         0,      32,     0 },
111       { "fixup_Hexagon_B22_PCREL_X",    0,      32,     MCFixupKindInfo::FKF_IsPCRel },
112       { "fixup_Hexagon_B15_PCREL_X",    0,      32,     MCFixupKindInfo::FKF_IsPCRel },
113       { "fixup_Hexagon_B13_PCREL_X",    0,      32,     MCFixupKindInfo::FKF_IsPCRel },
114       { "fixup_Hexagon_B9_PCREL_X",     0,      32,     MCFixupKindInfo::FKF_IsPCRel },
115       { "fixup_Hexagon_B7_PCREL_X",     0,      32,     MCFixupKindInfo::FKF_IsPCRel },
116       { "fixup_Hexagon_16_X",           0,      32,     0 },
117       { "fixup_Hexagon_12_X",           0,      32,     0 },
118       { "fixup_Hexagon_11_X",           0,      32,     0 },
119       { "fixup_Hexagon_10_X",           0,      32,     0 },
120       { "fixup_Hexagon_9_X",            0,      32,     0 },
121       { "fixup_Hexagon_8_X",            0,      32,     0 },
122       { "fixup_Hexagon_7_X",            0,      32,     0 },
123       { "fixup_Hexagon_6_X",            0,      32,     0 },
124       { "fixup_Hexagon_32_PCREL",       0,      32,     MCFixupKindInfo::FKF_IsPCRel },
125       { "fixup_Hexagon_COPY",           0,      32,     0 },
126       { "fixup_Hexagon_GLOB_DAT",       0,      32,     0 },
127       { "fixup_Hexagon_JMP_SLOT",       0,      32,     0 },
128       { "fixup_Hexagon_RELATIVE",       0,      32,     0 },
129       { "fixup_Hexagon_PLT_B22_PCREL",  0,      32,     MCFixupKindInfo::FKF_IsPCRel },
130       { "fixup_Hexagon_GOTREL_LO16",    0,      32,     0 },
131       { "fixup_Hexagon_GOTREL_HI16",    0,      32,     0 },
132       { "fixup_Hexagon_GOTREL_32",      0,      32,     0 },
133       { "fixup_Hexagon_GOT_LO16",       0,      32,     0 },
134       { "fixup_Hexagon_GOT_HI16",       0,      32,     0 },
135       { "fixup_Hexagon_GOT_32",         0,      32,     0 },
136       { "fixup_Hexagon_GOT_16",         0,      32,     0 },
137       { "fixup_Hexagon_DTPMOD_32",      0,      32,     0 },
138       { "fixup_Hexagon_DTPREL_LO16",    0,      32,     0 },
139       { "fixup_Hexagon_DTPREL_HI16",    0,      32,     0 },
140       { "fixup_Hexagon_DTPREL_32",      0,      32,     0 },
141       { "fixup_Hexagon_DTPREL_16",      0,      32,     0 },
142       { "fixup_Hexagon_GD_PLT_B22_PCREL",0,     32,     MCFixupKindInfo::FKF_IsPCRel },
143       { "fixup_Hexagon_LD_PLT_B22_PCREL",0,     32,     MCFixupKindInfo::FKF_IsPCRel },
144       { "fixup_Hexagon_GD_GOT_LO16",    0,      32,     0 },
145       { "fixup_Hexagon_GD_GOT_HI16",    0,      32,     0 },
146       { "fixup_Hexagon_GD_GOT_32",      0,      32,     0 },
147       { "fixup_Hexagon_GD_GOT_16",      0,      32,     0 },
148       { "fixup_Hexagon_LD_GOT_LO16",    0,      32,     0 },
149       { "fixup_Hexagon_LD_GOT_HI16",    0,      32,     0 },
150       { "fixup_Hexagon_LD_GOT_32",      0,      32,     0 },
151       { "fixup_Hexagon_LD_GOT_16",      0,      32,     0 },
152       { "fixup_Hexagon_IE_LO16",        0,      32,     0 },
153       { "fixup_Hexagon_IE_HI16",        0,      32,     0 },
154       { "fixup_Hexagon_IE_32",          0,      32,     0 },
155       { "fixup_Hexagon_IE_16",          0,      32,     0 },
156       { "fixup_Hexagon_IE_GOT_LO16",    0,      32,     0 },
157       { "fixup_Hexagon_IE_GOT_HI16",    0,      32,     0 },
158       { "fixup_Hexagon_IE_GOT_32",      0,      32,     0 },
159       { "fixup_Hexagon_IE_GOT_16",      0,      32,     0 },
160       { "fixup_Hexagon_TPREL_LO16",     0,      32,     0 },
161       { "fixup_Hexagon_TPREL_HI16",     0,      32,     0 },
162       { "fixup_Hexagon_TPREL_32",       0,      32,     0 },
163       { "fixup_Hexagon_TPREL_16",       0,      32,     0 },
164       { "fixup_Hexagon_6_PCREL_X",      0,      32,     MCFixupKindInfo::FKF_IsPCRel },
165       { "fixup_Hexagon_GOTREL_32_6_X",  0,      32,     0 },
166       { "fixup_Hexagon_GOTREL_16_X",    0,      32,     0 },
167       { "fixup_Hexagon_GOTREL_11_X",    0,      32,     0 },
168       { "fixup_Hexagon_GOT_32_6_X",     0,      32,     0 },
169       { "fixup_Hexagon_GOT_16_X",       0,      32,     0 },
170       { "fixup_Hexagon_GOT_11_X",       0,      32,     0 },
171       { "fixup_Hexagon_DTPREL_32_6_X",  0,      32,     0 },
172       { "fixup_Hexagon_DTPREL_16_X",    0,      32,     0 },
173       { "fixup_Hexagon_DTPREL_11_X",    0,      32,     0 },
174       { "fixup_Hexagon_GD_GOT_32_6_X",  0,      32,     0 },
175       { "fixup_Hexagon_GD_GOT_16_X",    0,      32,     0 },
176       { "fixup_Hexagon_GD_GOT_11_X",    0,      32,     0 },
177       { "fixup_Hexagon_LD_GOT_32_6_X",  0,      32,     0 },
178       { "fixup_Hexagon_LD_GOT_16_X",    0,      32,     0 },
179       { "fixup_Hexagon_LD_GOT_11_X",    0,      32,     0 },
180       { "fixup_Hexagon_IE_32_6_X",      0,      32,     0 },
181       { "fixup_Hexagon_IE_16_X",        0,      32,     0 },
182       { "fixup_Hexagon_IE_GOT_32_6_X",  0,      32,     0 },
183       { "fixup_Hexagon_IE_GOT_16_X",    0,      32,     0 },
184       { "fixup_Hexagon_IE_GOT_11_X",    0,      32,     0 },
185       { "fixup_Hexagon_TPREL_32_6_X",   0,      32,     0 },
186       { "fixup_Hexagon_TPREL_16_X",     0,      32,     0 },
187       { "fixup_Hexagon_TPREL_11_X",     0,      32,     0 },
188       { "fixup_Hexagon_GD_PLT_B22_PCREL_X",0,     32,     MCFixupKindInfo::FKF_IsPCRel },
189       { "fixup_Hexagon_GD_PLT_B32_PCREL_X",0,     32,     MCFixupKindInfo::FKF_IsPCRel },
190       { "fixup_Hexagon_LD_PLT_B22_PCREL_X",0,     32,     MCFixupKindInfo::FKF_IsPCRel },
191       { "fixup_Hexagon_LD_PLT_B32_PCREL_X",0,     32,     MCFixupKindInfo::FKF_IsPCRel }
192     };
193 
194     if (Kind < FirstTargetFixupKind)
195       return MCAsmBackend::getFixupKindInfo(Kind);
196 
197     assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
198            "Invalid kind!");
199     return Infos[Kind - FirstTargetFixupKind];
200   }
201 
202   bool shouldForceRelocation(const MCAssembler &Asm, const MCFixup &Fixup,
203                              const MCValue &Target) override {
204     switch(Fixup.getTargetKind()) {
205       default:
206         llvm_unreachable("Unknown Fixup Kind!");
207 
208       case fixup_Hexagon_LO16:
209       case fixup_Hexagon_HI16:
210       case fixup_Hexagon_16:
211       case fixup_Hexagon_8:
212       case fixup_Hexagon_GPREL16_0:
213       case fixup_Hexagon_GPREL16_1:
214       case fixup_Hexagon_GPREL16_2:
215       case fixup_Hexagon_GPREL16_3:
216       case fixup_Hexagon_HL16:
217       case fixup_Hexagon_32_6_X:
218       case fixup_Hexagon_16_X:
219       case fixup_Hexagon_12_X:
220       case fixup_Hexagon_11_X:
221       case fixup_Hexagon_10_X:
222       case fixup_Hexagon_9_X:
223       case fixup_Hexagon_8_X:
224       case fixup_Hexagon_7_X:
225       case fixup_Hexagon_6_X:
226       case fixup_Hexagon_COPY:
227       case fixup_Hexagon_GLOB_DAT:
228       case fixup_Hexagon_JMP_SLOT:
229       case fixup_Hexagon_RELATIVE:
230       case fixup_Hexagon_PLT_B22_PCREL:
231       case fixup_Hexagon_GOTREL_LO16:
232       case fixup_Hexagon_GOTREL_HI16:
233       case fixup_Hexagon_GOTREL_32:
234       case fixup_Hexagon_GOT_LO16:
235       case fixup_Hexagon_GOT_HI16:
236       case fixup_Hexagon_GOT_32:
237       case fixup_Hexagon_GOT_16:
238       case fixup_Hexagon_DTPMOD_32:
239       case fixup_Hexagon_DTPREL_LO16:
240       case fixup_Hexagon_DTPREL_HI16:
241       case fixup_Hexagon_DTPREL_32:
242       case fixup_Hexagon_DTPREL_16:
243       case fixup_Hexagon_GD_PLT_B22_PCREL:
244       case fixup_Hexagon_LD_PLT_B22_PCREL:
245       case fixup_Hexagon_GD_GOT_LO16:
246       case fixup_Hexagon_GD_GOT_HI16:
247       case fixup_Hexagon_GD_GOT_32:
248       case fixup_Hexagon_GD_GOT_16:
249       case fixup_Hexagon_LD_GOT_LO16:
250       case fixup_Hexagon_LD_GOT_HI16:
251       case fixup_Hexagon_LD_GOT_32:
252       case fixup_Hexagon_LD_GOT_16:
253       case fixup_Hexagon_IE_LO16:
254       case fixup_Hexagon_IE_HI16:
255       case fixup_Hexagon_IE_32:
256       case fixup_Hexagon_IE_16:
257       case fixup_Hexagon_IE_GOT_LO16:
258       case fixup_Hexagon_IE_GOT_HI16:
259       case fixup_Hexagon_IE_GOT_32:
260       case fixup_Hexagon_IE_GOT_16:
261       case fixup_Hexagon_TPREL_LO16:
262       case fixup_Hexagon_TPREL_HI16:
263       case fixup_Hexagon_TPREL_32:
264       case fixup_Hexagon_TPREL_16:
265       case fixup_Hexagon_GOTREL_32_6_X:
266       case fixup_Hexagon_GOTREL_16_X:
267       case fixup_Hexagon_GOTREL_11_X:
268       case fixup_Hexagon_GOT_32_6_X:
269       case fixup_Hexagon_GOT_16_X:
270       case fixup_Hexagon_GOT_11_X:
271       case fixup_Hexagon_DTPREL_32_6_X:
272       case fixup_Hexagon_DTPREL_16_X:
273       case fixup_Hexagon_DTPREL_11_X:
274       case fixup_Hexagon_GD_GOT_32_6_X:
275       case fixup_Hexagon_GD_GOT_16_X:
276       case fixup_Hexagon_GD_GOT_11_X:
277       case fixup_Hexagon_LD_GOT_32_6_X:
278       case fixup_Hexagon_LD_GOT_16_X:
279       case fixup_Hexagon_LD_GOT_11_X:
280       case fixup_Hexagon_IE_32_6_X:
281       case fixup_Hexagon_IE_16_X:
282       case fixup_Hexagon_IE_GOT_32_6_X:
283       case fixup_Hexagon_IE_GOT_16_X:
284       case fixup_Hexagon_IE_GOT_11_X:
285       case fixup_Hexagon_TPREL_32_6_X:
286       case fixup_Hexagon_TPREL_16_X:
287       case fixup_Hexagon_TPREL_11_X:
288       case fixup_Hexagon_32_PCREL:
289       case fixup_Hexagon_6_PCREL_X:
290       case fixup_Hexagon_23_REG:
291       case fixup_Hexagon_27_REG:
292       case fixup_Hexagon_GD_PLT_B22_PCREL_X:
293       case fixup_Hexagon_GD_PLT_B32_PCREL_X:
294       case fixup_Hexagon_LD_PLT_B22_PCREL_X:
295       case fixup_Hexagon_LD_PLT_B32_PCREL_X:
296         // These relocations should always have a relocation recorded
297         return true;
298 
299       case fixup_Hexagon_B22_PCREL:
300         //IsResolved = false;
301         break;
302 
303       case fixup_Hexagon_B13_PCREL:
304       case fixup_Hexagon_B13_PCREL_X:
305       case fixup_Hexagon_B32_PCREL_X:
306       case fixup_Hexagon_B22_PCREL_X:
307       case fixup_Hexagon_B15_PCREL:
308       case fixup_Hexagon_B15_PCREL_X:
309       case fixup_Hexagon_B9_PCREL:
310       case fixup_Hexagon_B9_PCREL_X:
311       case fixup_Hexagon_B7_PCREL:
312       case fixup_Hexagon_B7_PCREL_X:
313         if (DisableFixup)
314           return true;
315         break;
316 
317       case FK_Data_1:
318       case FK_Data_2:
319       case FK_Data_4:
320       case FK_PCRel_4:
321       case fixup_Hexagon_32:
322         // Leave these relocations alone as they are used for EH.
323         return false;
324     }
325     return false;
326   }
327 
328   /// getFixupKindNumBytes - The number of bytes the fixup may change.
329   static unsigned getFixupKindNumBytes(unsigned Kind) {
330     switch (Kind) {
331     default:
332         return 0;
333 
334       case FK_Data_1:
335         return 1;
336       case FK_Data_2:
337         return 2;
338       case FK_Data_4:         // this later gets mapped to R_HEX_32
339       case FK_PCRel_4:        // this later gets mapped to R_HEX_32_PCREL
340       case fixup_Hexagon_32:
341       case fixup_Hexagon_B32_PCREL_X:
342       case fixup_Hexagon_B22_PCREL:
343       case fixup_Hexagon_B22_PCREL_X:
344       case fixup_Hexagon_B15_PCREL:
345       case fixup_Hexagon_B15_PCREL_X:
346       case fixup_Hexagon_B13_PCREL:
347       case fixup_Hexagon_B13_PCREL_X:
348       case fixup_Hexagon_B9_PCREL:
349       case fixup_Hexagon_B9_PCREL_X:
350       case fixup_Hexagon_B7_PCREL:
351       case fixup_Hexagon_B7_PCREL_X:
352       case fixup_Hexagon_GD_PLT_B32_PCREL_X:
353       case fixup_Hexagon_LD_PLT_B32_PCREL_X:
354         return 4;
355     }
356   }
357 
358   // Make up for left shift when encoding the operand.
359   static uint64_t adjustFixupValue(MCFixupKind Kind, uint64_t Value) {
360     switch((unsigned)Kind) {
361       default:
362         break;
363 
364       case fixup_Hexagon_B7_PCREL:
365       case fixup_Hexagon_B9_PCREL:
366       case fixup_Hexagon_B13_PCREL:
367       case fixup_Hexagon_B15_PCREL:
368       case fixup_Hexagon_B22_PCREL:
369         Value >>= 2;
370         break;
371 
372       case fixup_Hexagon_B7_PCREL_X:
373       case fixup_Hexagon_B9_PCREL_X:
374       case fixup_Hexagon_B13_PCREL_X:
375       case fixup_Hexagon_B15_PCREL_X:
376       case fixup_Hexagon_B22_PCREL_X:
377         Value &= 0x3f;
378         break;
379 
380       case fixup_Hexagon_B32_PCREL_X:
381       case fixup_Hexagon_GD_PLT_B32_PCREL_X:
382       case fixup_Hexagon_LD_PLT_B32_PCREL_X:
383         Value >>= 6;
384         break;
385     }
386     return (Value);
387   }
388 
389   void HandleFixupError(const int bits, const int align_bits,
390     const int64_t FixupValue, const char *fixupStr) const {
391     // Error: value 1124 out of range: -1024-1023 when resolving
392     // symbol in file xprtsock.S
393     const APInt IntMin = APInt::getSignedMinValue(bits+align_bits);
394     const APInt IntMax = APInt::getSignedMaxValue(bits+align_bits);
395     std::stringstream errStr;
396     errStr << "\nError: value " <<
397       FixupValue <<
398       " out of range: " <<
399       IntMin.getSExtValue() <<
400       "-" <<
401       IntMax.getSExtValue() <<
402       " when resolving " <<
403       fixupStr <<
404       " fixup\n";
405     llvm_unreachable(errStr.str().c_str());
406   }
407 
408   /// ApplyFixup - Apply the \arg Value for given \arg Fixup into the provided
409   /// data fragment, at the offset specified by the fixup and following the
410   /// fixup kind as appropriate.
411   void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
412                   const MCValue &Target, MutableArrayRef<char> Data,
413                   uint64_t FixupValue, bool IsResolved,
414                   const MCSubtargetInfo *STI) const override {
415 
416     // When FixupValue is 0 the relocation is external and there
417     // is nothing for us to do.
418     if (!FixupValue) return;
419 
420     MCFixupKind Kind = Fixup.getKind();
421     uint64_t Value;
422     uint32_t InstMask;
423     uint32_t Reloc;
424 
425     // LLVM gives us an encoded value, we have to convert it back
426     // to a real offset before we can use it.
427     uint32_t Offset = Fixup.getOffset();
428     unsigned NumBytes = getFixupKindNumBytes(Kind);
429     assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
430     char *InstAddr = Data.data() + Offset;
431 
432     Value = adjustFixupValue(Kind, FixupValue);
433     if(!Value)
434       return;
435     int sValue = (int)Value;
436 
437     switch((unsigned)Kind) {
438       default:
439         return;
440 
441       case fixup_Hexagon_B7_PCREL:
442         if (!(isIntN(7, sValue)))
443           HandleFixupError(7, 2, (int64_t)FixupValue, "B7_PCREL");
444         LLVM_FALLTHROUGH;
445       case fixup_Hexagon_B7_PCREL_X:
446         InstMask = 0x00001f18;  // Word32_B7
447         Reloc = (((Value >> 2) & 0x1f) << 8) |    // Value 6-2 = Target 12-8
448                 ((Value & 0x3) << 3);             // Value 1-0 = Target 4-3
449         break;
450 
451       case fixup_Hexagon_B9_PCREL:
452         if (!(isIntN(9, sValue)))
453           HandleFixupError(9, 2, (int64_t)FixupValue, "B9_PCREL");
454         LLVM_FALLTHROUGH;
455       case fixup_Hexagon_B9_PCREL_X:
456         InstMask = 0x003000fe;  // Word32_B9
457         Reloc = (((Value >> 7) & 0x3) << 20) |    // Value 8-7 = Target 21-20
458                 ((Value & 0x7f) << 1);            // Value 6-0 = Target 7-1
459         break;
460 
461         // Since the existing branches that use this relocation cannot be
462         // extended, they should only be fixed up if the target is within range.
463       case fixup_Hexagon_B13_PCREL:
464         if (!(isIntN(13, sValue)))
465           HandleFixupError(13, 2, (int64_t)FixupValue, "B13_PCREL");
466         LLVM_FALLTHROUGH;
467       case fixup_Hexagon_B13_PCREL_X:
468         InstMask = 0x00202ffe;  // Word32_B13
469         Reloc = (((Value >> 12) & 0x1) << 21) |    // Value 12   = Target 21
470                 (((Value >> 11) & 0x1) << 13) |    // Value 11   = Target 13
471                 ((Value & 0x7ff) << 1);            // Value 10-0 = Target 11-1
472         break;
473 
474       case fixup_Hexagon_B15_PCREL:
475         if (!(isIntN(15, sValue)))
476           HandleFixupError(15, 2, (int64_t)FixupValue, "B15_PCREL");
477         LLVM_FALLTHROUGH;
478       case fixup_Hexagon_B15_PCREL_X:
479         InstMask = 0x00df20fe;  // Word32_B15
480         Reloc = (((Value >> 13) & 0x3) << 22) |    // Value 14-13 = Target 23-22
481                 (((Value >> 8) & 0x1f) << 16) |    // Value 12-8  = Target 20-16
482                 (((Value >> 7) & 0x1)  << 13) |    // Value 7     = Target 13
483                 ((Value & 0x7f) << 1);             // Value 6-0   = Target 7-1
484         break;
485 
486       case fixup_Hexagon_B22_PCREL:
487         if (!(isIntN(22, sValue)))
488           HandleFixupError(22, 2, (int64_t)FixupValue, "B22_PCREL");
489         LLVM_FALLTHROUGH;
490       case fixup_Hexagon_B22_PCREL_X:
491         InstMask = 0x01ff3ffe;  // Word32_B22
492         Reloc = (((Value >> 13) & 0x1ff) << 16) |  // Value 21-13 = Target 24-16
493                 ((Value & 0x1fff) << 1);           // Value 12-0  = Target 13-1
494         break;
495 
496       case fixup_Hexagon_B32_PCREL_X:
497         InstMask = 0x0fff3fff;  // Word32_X26
498         Reloc = (((Value >> 14) & 0xfff) << 16) |  // Value 25-14 = Target 27-16
499                 (Value & 0x3fff);                  // Value 13-0  = Target 13-0
500         break;
501 
502       case FK_Data_1:
503       case FK_Data_2:
504       case FK_Data_4:
505       case fixup_Hexagon_32:
506         InstMask = 0xffffffff;  // Word32
507         Reloc = Value;
508         break;
509     }
510 
511     LLVM_DEBUG(dbgs() << "Name=" << getFixupKindInfo(Kind).Name << "("
512                       << (unsigned)Kind << ")\n");
513     LLVM_DEBUG(
514         uint32_t OldData = 0; for (unsigned i = 0; i < NumBytes; i++) OldData |=
515                               (InstAddr[i] << (i * 8)) & (0xff << (i * 8));
516         dbgs() << "\tBValue=0x"; dbgs().write_hex(Value) << ": AValue=0x";
517         dbgs().write_hex(FixupValue)
518         << ": Offset=" << Offset << ": Size=" << Data.size() << ": OInst=0x";
519         dbgs().write_hex(OldData) << ": Reloc=0x"; dbgs().write_hex(Reloc););
520 
521     // For each byte of the fragment that the fixup touches, mask in the
522     // bits from the fixup value. The Value has been "split up" into the
523     // appropriate bitfields above.
524     for (unsigned i = 0; i < NumBytes; i++){
525       InstAddr[i] &= uint8_t(~InstMask >> (i * 8)) & 0xff; // Clear reloc bits
526       InstAddr[i] |= uint8_t(Reloc >> (i * 8)) & 0xff;     // Apply new reloc
527     }
528 
529     LLVM_DEBUG(uint32_t NewData = 0;
530                for (unsigned i = 0; i < NumBytes; i++) NewData |=
531                (InstAddr[i] << (i * 8)) & (0xff << (i * 8));
532                dbgs() << ": NInst=0x"; dbgs().write_hex(NewData) << "\n";);
533   }
534 
535   bool isInstRelaxable(MCInst const &HMI) const {
536     const MCInstrDesc &MCID = HexagonMCInstrInfo::getDesc(*MCII, HMI);
537     bool Relaxable = false;
538     // Branches and loop-setup insns are handled as necessary by relaxation.
539     if (llvm::HexagonMCInstrInfo::getType(*MCII, HMI) == HexagonII::TypeJ ||
540         (llvm::HexagonMCInstrInfo::getType(*MCII, HMI) == HexagonII::TypeCJ &&
541          MCID.isBranch()) ||
542         (llvm::HexagonMCInstrInfo::getType(*MCII, HMI) == HexagonII::TypeNCJ &&
543          MCID.isBranch()) ||
544         (llvm::HexagonMCInstrInfo::getType(*MCII, HMI) == HexagonII::TypeCR &&
545          HMI.getOpcode() != Hexagon::C4_addipc))
546       if (HexagonMCInstrInfo::isExtendable(*MCII, HMI)) {
547         Relaxable = true;
548         MCOperand const &Operand =
549             HMI.getOperand(HexagonMCInstrInfo::getExtendableOp(*MCII, HMI));
550         if (HexagonMCInstrInfo::mustNotExtend(*Operand.getExpr()))
551           Relaxable = false;
552       }
553 
554     return Relaxable;
555   }
556 
557   /// MayNeedRelaxation - Check whether the given instruction may need
558   /// relaxation.
559   ///
560   /// \param Inst - The instruction to test.
561   bool mayNeedRelaxation(MCInst const &Inst,
562                          const MCSubtargetInfo &STI) const override {
563     return true;
564   }
565 
566   /// fixupNeedsRelaxation - Target specific predicate for whether a given
567   /// fixup requires the associated instruction to be relaxed.
568   bool fixupNeedsRelaxationAdvanced(const MCFixup &Fixup, bool Resolved,
569                                     uint64_t Value,
570                                     const MCRelaxableFragment *DF,
571                                     const MCAsmLayout &Layout,
572                                     const bool WasForced) const override {
573     MCInst const &MCB = DF->getInst();
574     assert(HexagonMCInstrInfo::isBundle(MCB));
575 
576     *RelaxTarget = nullptr;
577     MCInst &MCI = const_cast<MCInst &>(HexagonMCInstrInfo::instruction(
578         MCB, Fixup.getOffset() / HEXAGON_INSTR_SIZE));
579     bool Relaxable = isInstRelaxable(MCI);
580     if (Relaxable == false)
581       return false;
582     // If we cannot resolve the fixup value, it requires relaxation.
583     if (!Resolved) {
584       switch (Fixup.getTargetKind()) {
585       case fixup_Hexagon_B22_PCREL:
586         // GetFixupCount assumes B22 won't relax
587         LLVM_FALLTHROUGH;
588       default:
589         return false;
590         break;
591       case fixup_Hexagon_B13_PCREL:
592       case fixup_Hexagon_B15_PCREL:
593       case fixup_Hexagon_B9_PCREL:
594       case fixup_Hexagon_B7_PCREL: {
595         if (HexagonMCInstrInfo::bundleSize(MCB) < HEXAGON_PACKET_SIZE) {
596           ++relaxedCnt;
597           *RelaxTarget = &MCI;
598           setExtender(Layout.getAssembler().getContext());
599           return true;
600         } else {
601           return false;
602         }
603         break;
604       }
605       }
606     }
607 
608     MCFixupKind Kind = Fixup.getKind();
609     int64_t sValue = Value;
610     int64_t maxValue;
611 
612     switch ((unsigned)Kind) {
613     case fixup_Hexagon_B7_PCREL:
614       maxValue = 1 << 8;
615       break;
616     case fixup_Hexagon_B9_PCREL:
617       maxValue = 1 << 10;
618       break;
619     case fixup_Hexagon_B15_PCREL:
620       maxValue = 1 << 16;
621       break;
622     case fixup_Hexagon_B22_PCREL:
623       maxValue = 1 << 23;
624       break;
625     default:
626       maxValue = INT64_MAX;
627       break;
628     }
629 
630     bool isFarAway = -maxValue > sValue || sValue > maxValue - 1;
631 
632     if (isFarAway) {
633       if (HexagonMCInstrInfo::bundleSize(MCB) < HEXAGON_PACKET_SIZE) {
634         ++relaxedCnt;
635         *RelaxTarget = &MCI;
636         setExtender(Layout.getAssembler().getContext());
637         return true;
638       }
639     }
640 
641     return false;
642   }
643 
644   /// Simple predicate for targets where !Resolved implies requiring relaxation
645   bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
646                             const MCRelaxableFragment *DF,
647                             const MCAsmLayout &Layout) const override {
648     llvm_unreachable("Handled by fixupNeedsRelaxationAdvanced");
649   }
650 
651   void relaxInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
652                         MCInst &Res) const override {
653     assert(HexagonMCInstrInfo::isBundle(Inst) &&
654            "Hexagon relaxInstruction only works on bundles");
655 
656     Res.setOpcode(Hexagon::BUNDLE);
657     Res.addOperand(MCOperand::createImm(Inst.getOperand(0).getImm()));
658     // Copy the results into the bundle.
659     bool Update = false;
660     for (auto &I : HexagonMCInstrInfo::bundleInstructions(Inst)) {
661       MCInst &CrntHMI = const_cast<MCInst &>(*I.getInst());
662 
663       // if immediate extender needed, add it in
664       if (*RelaxTarget == &CrntHMI) {
665         Update = true;
666         assert((HexagonMCInstrInfo::bundleSize(Res) < HEXAGON_PACKET_SIZE) &&
667                "No room to insert extender for relaxation");
668 
669         MCInst *HMIx = takeExtender();
670         *HMIx = HexagonMCInstrInfo::deriveExtender(
671                 *MCII, CrntHMI,
672                 HexagonMCInstrInfo::getExtendableOperand(*MCII, CrntHMI));
673         Res.addOperand(MCOperand::createInst(HMIx));
674         *RelaxTarget = nullptr;
675       }
676       // now copy over the original instruction(the one we may have extended)
677       Res.addOperand(MCOperand::createInst(I.getInst()));
678     }
679     (void)Update;
680     assert(Update && "Didn't find relaxation target");
681   }
682 
683   bool writeNopData(raw_ostream &OS, uint64_t Count) const override {
684     static const uint32_t Nopcode  = 0x7f000000, // Hard-coded NOP.
685                           ParseIn  = 0x00004000, // In packet parse-bits.
686                           ParseEnd = 0x0000c000; // End of packet parse-bits.
687 
688     while(Count % HEXAGON_INSTR_SIZE) {
689       LLVM_DEBUG(dbgs() << "Alignment not a multiple of the instruction size:"
690                         << Count % HEXAGON_INSTR_SIZE << "/"
691                         << HEXAGON_INSTR_SIZE << "\n");
692       --Count;
693       OS << '\0';
694     }
695 
696     while(Count) {
697       Count -= HEXAGON_INSTR_SIZE;
698       // Close the packet whenever a multiple of the maximum packet size remains
699       uint32_t ParseBits = (Count % (HEXAGON_PACKET_SIZE * HEXAGON_INSTR_SIZE))?
700                            ParseIn: ParseEnd;
701       support::endian::write<uint32_t>(OS, Nopcode | ParseBits, Endian);
702     }
703     return true;
704   }
705 
706   void finishLayout(MCAssembler const &Asm,
707                     MCAsmLayout &Layout) const override {
708     for (auto I : Layout.getSectionOrder()) {
709       auto &Fragments = I->getFragmentList();
710       for (auto &J : Fragments) {
711         switch (J.getKind()) {
712         default:
713           break;
714         case MCFragment::FT_Align: {
715           auto Size = Asm.computeFragmentSize(Layout, J);
716           for (auto K = J.getIterator();
717                K != Fragments.begin() && Size >= HEXAGON_PACKET_SIZE;) {
718             --K;
719             switch (K->getKind()) {
720             default:
721               break;
722             case MCFragment::FT_Align: {
723               // Don't pad before other alignments
724               Size = 0;
725               break;
726             }
727             case MCFragment::FT_Relaxable: {
728               MCContext &Context = Asm.getContext();
729               auto &RF = cast<MCRelaxableFragment>(*K);
730               auto &Inst = const_cast<MCInst &>(RF.getInst());
731               while (Size > 0 && HexagonMCInstrInfo::bundleSize(Inst) < 4) {
732                 MCInst *Nop = new (Context) MCInst;
733                 Nop->setOpcode(Hexagon::A2_nop);
734                 Inst.addOperand(MCOperand::createInst(Nop));
735                 Size -= 4;
736                 if (!HexagonMCChecker(
737                          Context, *MCII, *RF.getSubtargetInfo(), Inst,
738                          *Context.getRegisterInfo(), false)
739                          .check()) {
740                   Inst.erase(Inst.end() - 1);
741                   Size = 0;
742                 }
743               }
744               bool Error = HexagonMCShuffle(Context, true, *MCII,
745                                             *RF.getSubtargetInfo(), Inst);
746               //assert(!Error);
747               (void)Error;
748               ReplaceInstruction(Asm.getEmitter(), RF, Inst);
749               Layout.invalidateFragmentsFrom(&RF);
750               Size = 0; // Only look back one instruction
751               break;
752             }
753             }
754           }
755         }
756         }
757       }
758     }
759   }
760 }; // class HexagonAsmBackend
761 
762 } // namespace
763 
764 // MCAsmBackend
765 MCAsmBackend *llvm::createHexagonAsmBackend(Target const &T,
766                                             const MCSubtargetInfo &STI,
767                                             MCRegisterInfo const & /*MRI*/,
768                                             const MCTargetOptions &Options) {
769   const Triple &TT = STI.getTargetTriple();
770   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
771 
772   StringRef CPUString = Hexagon_MC::selectHexagonCPU(STI.getCPU());
773   return new HexagonAsmBackend(T, TT, OSABI, CPUString);
774 }
775