1 //===-- RISCVAsmBackend.cpp - RISCV 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 "RISCVAsmBackend.h"
10 #include "RISCVMCExpr.h"
11 #include "llvm/ADT/APInt.h"
12 #include "llvm/MC/MCAsmInfo.h"
13 #include "llvm/MC/MCAsmLayout.h"
14 #include "llvm/MC/MCAssembler.h"
15 #include "llvm/MC/MCContext.h"
16 #include "llvm/MC/MCDirectives.h"
17 #include "llvm/MC/MCELFObjectWriter.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCObjectWriter.h"
20 #include "llvm/MC/MCSymbol.h"
21 #include "llvm/MC/MCValue.h"
22 #include "llvm/Support/Endian.h"
23 #include "llvm/Support/EndianStream.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/LEB128.h"
26 #include "llvm/Support/raw_ostream.h"
27 
28 using namespace llvm;
29 
30 Optional<MCFixupKind> RISCVAsmBackend::getFixupKind(StringRef Name) const {
31   if (STI.getTargetTriple().isOSBinFormatELF()) {
32     unsigned Type;
33     Type = llvm::StringSwitch<unsigned>(Name)
34 #define ELF_RELOC(X, Y) .Case(#X, Y)
35 #include "llvm/BinaryFormat/ELFRelocs/RISCV.def"
36 #undef ELF_RELOC
37                .Case("BFD_RELOC_NONE", ELF::R_RISCV_NONE)
38                .Case("BFD_RELOC_32", ELF::R_RISCV_32)
39                .Case("BFD_RELOC_64", ELF::R_RISCV_64)
40                .Default(-1u);
41     if (Type != -1u)
42       return static_cast<MCFixupKind>(FirstLiteralRelocationKind + Type);
43   }
44   return None;
45 }
46 
47 const MCFixupKindInfo &
48 RISCVAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
49   const static MCFixupKindInfo Infos[] = {
50       // This table *must* be in the order that the fixup_* kinds are defined in
51       // RISCVFixupKinds.h.
52       //
53       // name                      offset bits  flags
54       {"fixup_riscv_hi20", 12, 20, 0},
55       {"fixup_riscv_lo12_i", 20, 12, 0},
56       {"fixup_riscv_lo12_s", 0, 32, 0},
57       {"fixup_riscv_pcrel_hi20", 12, 20,
58        MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
59       {"fixup_riscv_pcrel_lo12_i", 20, 12,
60        MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
61       {"fixup_riscv_pcrel_lo12_s", 0, 32,
62        MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
63       {"fixup_riscv_got_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
64       {"fixup_riscv_tprel_hi20", 12, 20, 0},
65       {"fixup_riscv_tprel_lo12_i", 20, 12, 0},
66       {"fixup_riscv_tprel_lo12_s", 0, 32, 0},
67       {"fixup_riscv_tprel_add", 0, 0, 0},
68       {"fixup_riscv_tls_got_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
69       {"fixup_riscv_tls_gd_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
70       {"fixup_riscv_jal", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
71       {"fixup_riscv_branch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
72       {"fixup_riscv_rvc_jump", 2, 11, MCFixupKindInfo::FKF_IsPCRel},
73       {"fixup_riscv_rvc_branch", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
74       {"fixup_riscv_call", 0, 64, MCFixupKindInfo::FKF_IsPCRel},
75       {"fixup_riscv_call_plt", 0, 64, MCFixupKindInfo::FKF_IsPCRel},
76       {"fixup_riscv_relax", 0, 0, 0},
77       {"fixup_riscv_align", 0, 0, 0},
78 
79       {"fixup_riscv_set_8", 0, 8, 0},
80       {"fixup_riscv_add_8", 0, 8, 0},
81       {"fixup_riscv_sub_8", 0, 8, 0},
82 
83       {"fixup_riscv_set_16", 0, 16, 0},
84       {"fixup_riscv_add_16", 0, 16, 0},
85       {"fixup_riscv_sub_16", 0, 16, 0},
86 
87       {"fixup_riscv_set_32", 0, 32, 0},
88       {"fixup_riscv_add_32", 0, 32, 0},
89       {"fixup_riscv_sub_32", 0, 32, 0},
90 
91       {"fixup_riscv_add_64", 0, 64, 0},
92       {"fixup_riscv_sub_64", 0, 64, 0},
93 
94       {"fixup_riscv_set_6b", 2, 6, 0},
95       {"fixup_riscv_sub_6b", 2, 6, 0},
96   };
97   static_assert((array_lengthof(Infos)) == RISCV::NumTargetFixupKinds,
98                 "Not all fixup kinds added to Infos array");
99 
100   // Fixup kinds from .reloc directive are like R_RISCV_NONE. They
101   // do not require any extra processing.
102   if (Kind >= FirstLiteralRelocationKind)
103     return MCAsmBackend::getFixupKindInfo(FK_NONE);
104 
105   if (Kind < FirstTargetFixupKind)
106     return MCAsmBackend::getFixupKindInfo(Kind);
107 
108   assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
109          "Invalid kind!");
110   return Infos[Kind - FirstTargetFixupKind];
111 }
112 
113 // If linker relaxation is enabled, or the relax option had previously been
114 // enabled, always emit relocations even if the fixup can be resolved. This is
115 // necessary for correctness as offsets may change during relaxation.
116 bool RISCVAsmBackend::shouldForceRelocation(const MCAssembler &Asm,
117                                             const MCFixup &Fixup,
118                                             const MCValue &Target) {
119   if (Fixup.getKind() >= FirstLiteralRelocationKind)
120     return true;
121   switch (Fixup.getTargetKind()) {
122   default:
123     break;
124   case FK_Data_1:
125   case FK_Data_2:
126   case FK_Data_4:
127   case FK_Data_8:
128     if (Target.isAbsolute())
129       return false;
130     break;
131   case RISCV::fixup_riscv_got_hi20:
132   case RISCV::fixup_riscv_tls_got_hi20:
133   case RISCV::fixup_riscv_tls_gd_hi20:
134     return true;
135   }
136 
137   return STI.getFeatureBits()[RISCV::FeatureRelax] || ForceRelocs;
138 }
139 
140 bool RISCVAsmBackend::fixupNeedsRelaxationAdvanced(const MCFixup &Fixup,
141                                                    bool Resolved,
142                                                    uint64_t Value,
143                                                    const MCRelaxableFragment *DF,
144                                                    const MCAsmLayout &Layout,
145                                                    const bool WasForced) const {
146   // Return true if the symbol is actually unresolved.
147   // Resolved could be always false when shouldForceRelocation return true.
148   // We use !WasForced to indicate that the symbol is unresolved and not forced
149   // by shouldForceRelocation.
150   if (!Resolved && !WasForced)
151     return true;
152 
153   int64_t Offset = int64_t(Value);
154   switch (Fixup.getTargetKind()) {
155   default:
156     return false;
157   case RISCV::fixup_riscv_rvc_branch:
158     // For compressed branch instructions the immediate must be
159     // in the range [-256, 254].
160     return Offset > 254 || Offset < -256;
161   case RISCV::fixup_riscv_rvc_jump:
162     // For compressed jump instructions the immediate must be
163     // in the range [-2048, 2046].
164     return Offset > 2046 || Offset < -2048;
165   }
166 }
167 
168 void RISCVAsmBackend::relaxInstruction(MCInst &Inst,
169                                        const MCSubtargetInfo &STI) const {
170   // TODO: replace this with call to auto generated uncompressinstr() function.
171   MCInst Res;
172   switch (Inst.getOpcode()) {
173   default:
174     llvm_unreachable("Opcode not expected!");
175   case RISCV::C_BEQZ:
176     // c.beqz $rs1, $imm -> beq $rs1, X0, $imm.
177     Res.setOpcode(RISCV::BEQ);
178     Res.addOperand(Inst.getOperand(0));
179     Res.addOperand(MCOperand::createReg(RISCV::X0));
180     Res.addOperand(Inst.getOperand(1));
181     break;
182   case RISCV::C_BNEZ:
183     // c.bnez $rs1, $imm -> bne $rs1, X0, $imm.
184     Res.setOpcode(RISCV::BNE);
185     Res.addOperand(Inst.getOperand(0));
186     Res.addOperand(MCOperand::createReg(RISCV::X0));
187     Res.addOperand(Inst.getOperand(1));
188     break;
189   case RISCV::C_J:
190     // c.j $imm -> jal X0, $imm.
191     Res.setOpcode(RISCV::JAL);
192     Res.addOperand(MCOperand::createReg(RISCV::X0));
193     Res.addOperand(Inst.getOperand(0));
194     break;
195   case RISCV::C_JAL:
196     // c.jal $imm -> jal X1, $imm.
197     Res.setOpcode(RISCV::JAL);
198     Res.addOperand(MCOperand::createReg(RISCV::X1));
199     Res.addOperand(Inst.getOperand(0));
200     break;
201   }
202   Inst = std::move(Res);
203 }
204 
205 bool RISCVAsmBackend::relaxDwarfLineAddr(MCDwarfLineAddrFragment &DF,
206                                          MCAsmLayout &Layout,
207                                          bool &WasRelaxed) const {
208   MCContext &C = Layout.getAssembler().getContext();
209 
210   int64_t LineDelta = DF.getLineDelta();
211   const MCExpr &AddrDelta = DF.getAddrDelta();
212   SmallVectorImpl<char> &Data = DF.getContents();
213   SmallVectorImpl<MCFixup> &Fixups = DF.getFixups();
214   size_t OldSize = Data.size();
215 
216   int64_t Value;
217   bool IsAbsolute = AddrDelta.evaluateKnownAbsolute(Value, Layout);
218   assert(IsAbsolute && "CFA with invalid expression");
219   (void)IsAbsolute;
220 
221   Data.clear();
222   Fixups.clear();
223   raw_svector_ostream OS(Data);
224 
225   // INT64_MAX is a signal that this is actually a DW_LNE_end_sequence.
226   if (LineDelta != INT64_MAX) {
227     OS << uint8_t(dwarf::DW_LNS_advance_line);
228     encodeSLEB128(LineDelta, OS);
229   }
230 
231   unsigned Offset;
232   std::pair<unsigned, unsigned> Fixup;
233 
234   // According to the DWARF specification, the `DW_LNS_fixed_advance_pc` opcode
235   // takes a single unsigned half (unencoded) operand. The maximum encodable
236   // value is therefore 65535.  Set a conservative upper bound for relaxation.
237   if (Value > 60000) {
238     unsigned PtrSize = C.getAsmInfo()->getCodePointerSize();
239 
240     OS << uint8_t(dwarf::DW_LNS_extended_op);
241     encodeULEB128(PtrSize + 1, OS);
242 
243     OS << uint8_t(dwarf::DW_LNE_set_address);
244     Offset = OS.tell();
245     Fixup = PtrSize == 4 ? std::make_pair(RISCV::fixup_riscv_add_32,
246                                           RISCV::fixup_riscv_sub_32)
247                          : std::make_pair(RISCV::fixup_riscv_add_64,
248                                           RISCV::fixup_riscv_sub_64);
249     OS.write_zeros(PtrSize);
250   } else {
251     OS << uint8_t(dwarf::DW_LNS_fixed_advance_pc);
252     Offset = OS.tell();
253     Fixup = {RISCV::fixup_riscv_add_16, RISCV::fixup_riscv_sub_16};
254     support::endian::write<uint16_t>(OS, 0, support::little);
255   }
256 
257   const MCBinaryExpr &MBE = cast<MCBinaryExpr>(AddrDelta);
258   Fixups.push_back(MCFixup::create(
259       Offset, MBE.getLHS(), static_cast<MCFixupKind>(std::get<0>(Fixup))));
260   Fixups.push_back(MCFixup::create(
261       Offset, MBE.getRHS(), static_cast<MCFixupKind>(std::get<1>(Fixup))));
262 
263   if (LineDelta == INT64_MAX) {
264     OS << uint8_t(dwarf::DW_LNS_extended_op);
265     OS << uint8_t(1);
266     OS << uint8_t(dwarf::DW_LNE_end_sequence);
267   } else {
268     OS << uint8_t(dwarf::DW_LNS_copy);
269   }
270 
271   WasRelaxed = OldSize != Data.size();
272   return true;
273 }
274 
275 bool RISCVAsmBackend::relaxDwarfCFA(MCDwarfCallFrameFragment &DF,
276                                     MCAsmLayout &Layout,
277                                     bool &WasRelaxed) const {
278   MCContext &C = Layout.getAssembler().getContext();
279 
280   const MCExpr &AddrDelta = DF.getAddrDelta();
281   SmallVectorImpl<char> &Data = DF.getContents();
282   SmallVectorImpl<MCFixup> &Fixups = DF.getFixups();
283   size_t OldSize = Data.size();
284 
285   int64_t Value;
286   bool IsAbsolute = AddrDelta.evaluateKnownAbsolute(Value, Layout);
287   assert(IsAbsolute && "CFA with invalid expression");
288   (void)IsAbsolute;
289 
290   Data.clear();
291   Fixups.clear();
292   raw_svector_ostream OS(Data);
293 
294   assert(C.getAsmInfo()->getMinInstAlignment() == 1 &&
295          "expected 1-byte alignment");
296   if (Value == 0) {
297     WasRelaxed = OldSize != Data.size();
298     return true;
299   }
300 
301   auto AddFixups = [&Fixups, &AddrDelta](unsigned Offset,
302                                          std::pair<unsigned, unsigned> Fixup) {
303     const MCBinaryExpr &MBE = cast<MCBinaryExpr>(AddrDelta);
304     Fixups.push_back(MCFixup::create(
305         Offset, MBE.getLHS(), static_cast<MCFixupKind>(std::get<0>(Fixup))));
306     Fixups.push_back(MCFixup::create(
307         Offset, MBE.getRHS(), static_cast<MCFixupKind>(std::get<1>(Fixup))));
308   };
309 
310   if (isUIntN(6, Value)) {
311     OS << uint8_t(dwarf::DW_CFA_advance_loc);
312     AddFixups(0, {RISCV::fixup_riscv_set_6b, RISCV::fixup_riscv_sub_6b});
313   } else if (isUInt<8>(Value)) {
314     OS << uint8_t(dwarf::DW_CFA_advance_loc1);
315     support::endian::write<uint8_t>(OS, 0, support::little);
316     AddFixups(1, {RISCV::fixup_riscv_set_8, RISCV::fixup_riscv_sub_8});
317   } else if (isUInt<16>(Value)) {
318     OS << uint8_t(dwarf::DW_CFA_advance_loc2);
319     support::endian::write<uint16_t>(OS, 0, support::little);
320     AddFixups(1, {RISCV::fixup_riscv_set_16, RISCV::fixup_riscv_sub_16});
321   } else if (isUInt<32>(Value)) {
322     OS << uint8_t(dwarf::DW_CFA_advance_loc4);
323     support::endian::write<uint32_t>(OS, 0, support::little);
324     AddFixups(1, {RISCV::fixup_riscv_set_32, RISCV::fixup_riscv_sub_32});
325   } else {
326     llvm_unreachable("unsupported CFA encoding");
327   }
328 
329   WasRelaxed = OldSize != Data.size();
330   return true;
331 }
332 
333 // Given a compressed control flow instruction this function returns
334 // the expanded instruction.
335 unsigned RISCVAsmBackend::getRelaxedOpcode(unsigned Op) const {
336   switch (Op) {
337   default:
338     return Op;
339   case RISCV::C_BEQZ:
340     return RISCV::BEQ;
341   case RISCV::C_BNEZ:
342     return RISCV::BNE;
343   case RISCV::C_J:
344   case RISCV::C_JAL: // fall through.
345     return RISCV::JAL;
346   }
347 }
348 
349 bool RISCVAsmBackend::mayNeedRelaxation(const MCInst &Inst,
350                                         const MCSubtargetInfo &STI) const {
351   return getRelaxedOpcode(Inst.getOpcode()) != Inst.getOpcode();
352 }
353 
354 bool RISCVAsmBackend::writeNopData(raw_ostream &OS, uint64_t Count) const {
355   bool HasStdExtC = STI.getFeatureBits()[RISCV::FeatureStdExtC];
356   unsigned MinNopLen = HasStdExtC ? 2 : 4;
357 
358   if ((Count % MinNopLen) != 0)
359     return false;
360 
361   // The canonical nop on RISC-V is addi x0, x0, 0.
362   for (; Count >= 4; Count -= 4)
363     OS.write("\x13\0\0\0", 4);
364 
365   // The canonical nop on RVC is c.nop.
366   if (Count && HasStdExtC)
367     OS.write("\x01\0", 2);
368 
369   return true;
370 }
371 
372 static uint64_t adjustFixupValue(const MCFixup &Fixup, uint64_t Value,
373                                  MCContext &Ctx) {
374   switch (Fixup.getTargetKind()) {
375   default:
376     llvm_unreachable("Unknown fixup kind!");
377   case RISCV::fixup_riscv_got_hi20:
378   case RISCV::fixup_riscv_tls_got_hi20:
379   case RISCV::fixup_riscv_tls_gd_hi20:
380     llvm_unreachable("Relocation should be unconditionally forced\n");
381   case RISCV::fixup_riscv_set_8:
382   case RISCV::fixup_riscv_add_8:
383   case RISCV::fixup_riscv_sub_8:
384   case RISCV::fixup_riscv_set_16:
385   case RISCV::fixup_riscv_add_16:
386   case RISCV::fixup_riscv_sub_16:
387   case RISCV::fixup_riscv_set_32:
388   case RISCV::fixup_riscv_add_32:
389   case RISCV::fixup_riscv_sub_32:
390   case RISCV::fixup_riscv_add_64:
391   case RISCV::fixup_riscv_sub_64:
392   case FK_Data_1:
393   case FK_Data_2:
394   case FK_Data_4:
395   case FK_Data_8:
396   case FK_Data_6b:
397     return Value;
398   case RISCV::fixup_riscv_set_6b:
399     return Value & 0x03;
400   case RISCV::fixup_riscv_lo12_i:
401   case RISCV::fixup_riscv_pcrel_lo12_i:
402   case RISCV::fixup_riscv_tprel_lo12_i:
403     return Value & 0xfff;
404   case RISCV::fixup_riscv_lo12_s:
405   case RISCV::fixup_riscv_pcrel_lo12_s:
406   case RISCV::fixup_riscv_tprel_lo12_s:
407     return (((Value >> 5) & 0x7f) << 25) | ((Value & 0x1f) << 7);
408   case RISCV::fixup_riscv_hi20:
409   case RISCV::fixup_riscv_pcrel_hi20:
410   case RISCV::fixup_riscv_tprel_hi20:
411     // Add 1 if bit 11 is 1, to compensate for low 12 bits being negative.
412     return ((Value + 0x800) >> 12) & 0xfffff;
413   case RISCV::fixup_riscv_jal: {
414     if (!isInt<21>(Value))
415       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
416     if (Value & 0x1)
417       Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
418     // Need to produce imm[19|10:1|11|19:12] from the 21-bit Value.
419     unsigned Sbit = (Value >> 20) & 0x1;
420     unsigned Hi8 = (Value >> 12) & 0xff;
421     unsigned Mid1 = (Value >> 11) & 0x1;
422     unsigned Lo10 = (Value >> 1) & 0x3ff;
423     // Inst{31} = Sbit;
424     // Inst{30-21} = Lo10;
425     // Inst{20} = Mid1;
426     // Inst{19-12} = Hi8;
427     Value = (Sbit << 19) | (Lo10 << 9) | (Mid1 << 8) | Hi8;
428     return Value;
429   }
430   case RISCV::fixup_riscv_branch: {
431     if (!isInt<13>(Value))
432       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
433     if (Value & 0x1)
434       Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
435     // Need to extract imm[12], imm[10:5], imm[4:1], imm[11] from the 13-bit
436     // Value.
437     unsigned Sbit = (Value >> 12) & 0x1;
438     unsigned Hi1 = (Value >> 11) & 0x1;
439     unsigned Mid6 = (Value >> 5) & 0x3f;
440     unsigned Lo4 = (Value >> 1) & 0xf;
441     // Inst{31} = Sbit;
442     // Inst{30-25} = Mid6;
443     // Inst{11-8} = Lo4;
444     // Inst{7} = Hi1;
445     Value = (Sbit << 31) | (Mid6 << 25) | (Lo4 << 8) | (Hi1 << 7);
446     return Value;
447   }
448   case RISCV::fixup_riscv_call:
449   case RISCV::fixup_riscv_call_plt: {
450     // Jalr will add UpperImm with the sign-extended 12-bit LowerImm,
451     // we need to add 0x800ULL before extract upper bits to reflect the
452     // effect of the sign extension.
453     uint64_t UpperImm = (Value + 0x800ULL) & 0xfffff000ULL;
454     uint64_t LowerImm = Value & 0xfffULL;
455     return UpperImm | ((LowerImm << 20) << 32);
456   }
457   case RISCV::fixup_riscv_rvc_jump: {
458     // Need to produce offset[11|4|9:8|10|6|7|3:1|5] from the 11-bit Value.
459     unsigned Bit11  = (Value >> 11) & 0x1;
460     unsigned Bit4   = (Value >> 4) & 0x1;
461     unsigned Bit9_8 = (Value >> 8) & 0x3;
462     unsigned Bit10  = (Value >> 10) & 0x1;
463     unsigned Bit6   = (Value >> 6) & 0x1;
464     unsigned Bit7   = (Value >> 7) & 0x1;
465     unsigned Bit3_1 = (Value >> 1) & 0x7;
466     unsigned Bit5   = (Value >> 5) & 0x1;
467     Value = (Bit11 << 10) | (Bit4 << 9) | (Bit9_8 << 7) | (Bit10 << 6) |
468             (Bit6 << 5) | (Bit7 << 4) | (Bit3_1 << 1) | Bit5;
469     return Value;
470   }
471   case RISCV::fixup_riscv_rvc_branch: {
472     // Need to produce offset[8|4:3], [reg 3 bit], offset[7:6|2:1|5]
473     unsigned Bit8   = (Value >> 8) & 0x1;
474     unsigned Bit7_6 = (Value >> 6) & 0x3;
475     unsigned Bit5   = (Value >> 5) & 0x1;
476     unsigned Bit4_3 = (Value >> 3) & 0x3;
477     unsigned Bit2_1 = (Value >> 1) & 0x3;
478     Value = (Bit8 << 12) | (Bit4_3 << 10) | (Bit7_6 << 5) | (Bit2_1 << 3) |
479             (Bit5 << 2);
480     return Value;
481   }
482 
483   }
484 }
485 
486 bool RISCVAsmBackend::evaluateTargetFixup(
487     const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFixup &Fixup,
488     const MCFragment *DF, const MCValue &Target, uint64_t &Value,
489     bool &WasForced) {
490   const MCFixup *AUIPCFixup;
491   const MCFragment *AUIPCDF;
492   MCValue AUIPCTarget;
493   switch (Fixup.getTargetKind()) {
494   default:
495     llvm_unreachable("Unexpected fixup kind!");
496   case RISCV::fixup_riscv_pcrel_hi20:
497     AUIPCFixup = &Fixup;
498     AUIPCDF = DF;
499     AUIPCTarget = Target;
500     break;
501   case RISCV::fixup_riscv_pcrel_lo12_i:
502   case RISCV::fixup_riscv_pcrel_lo12_s: {
503     AUIPCFixup = cast<RISCVMCExpr>(Fixup.getValue())->getPCRelHiFixup(&AUIPCDF);
504     if (!AUIPCFixup) {
505       Asm.getContext().reportError(Fixup.getLoc(),
506                                    "could not find corresponding %pcrel_hi");
507       return true;
508     }
509 
510     // MCAssembler::evaluateFixup will emit an error for this case when it sees
511     // the %pcrel_hi, so don't duplicate it when also seeing the %pcrel_lo.
512     const MCExpr *AUIPCExpr = AUIPCFixup->getValue();
513     if (!AUIPCExpr->evaluateAsRelocatable(AUIPCTarget, &Layout, AUIPCFixup))
514       return true;
515     break;
516   }
517   }
518 
519   if (!AUIPCTarget.getSymA() || AUIPCTarget.getSymB())
520     return false;
521 
522   const MCSymbolRefExpr *A = AUIPCTarget.getSymA();
523   const MCSymbol &SA = A->getSymbol();
524   if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined())
525     return false;
526 
527   auto *Writer = Asm.getWriterPtr();
528   if (!Writer)
529     return false;
530 
531   bool IsResolved = Writer->isSymbolRefDifferenceFullyResolvedImpl(
532       Asm, SA, *AUIPCDF, false, true);
533   if (!IsResolved)
534     return false;
535 
536   Value = Layout.getSymbolOffset(SA) + AUIPCTarget.getConstant();
537   Value -= Layout.getFragmentOffset(AUIPCDF) + AUIPCFixup->getOffset();
538 
539   if (shouldForceRelocation(Asm, *AUIPCFixup, AUIPCTarget)) {
540     WasForced = true;
541     return false;
542   }
543 
544   return true;
545 }
546 
547 void RISCVAsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
548                                  const MCValue &Target,
549                                  MutableArrayRef<char> Data, uint64_t Value,
550                                  bool IsResolved,
551                                  const MCSubtargetInfo *STI) const {
552   MCFixupKind Kind = Fixup.getKind();
553   if (Kind >= FirstLiteralRelocationKind)
554     return;
555   MCContext &Ctx = Asm.getContext();
556   MCFixupKindInfo Info = getFixupKindInfo(Kind);
557   if (!Value)
558     return; // Doesn't change encoding.
559   // Apply any target-specific value adjustments.
560   Value = adjustFixupValue(Fixup, Value, Ctx);
561 
562   // Shift the value into position.
563   Value <<= Info.TargetOffset;
564 
565   unsigned Offset = Fixup.getOffset();
566   unsigned NumBytes = alignTo(Info.TargetSize + Info.TargetOffset, 8) / 8;
567 
568   assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
569 
570   // For each byte of the fragment that the fixup touches, mask in the
571   // bits from the fixup value.
572   for (unsigned i = 0; i != NumBytes; ++i) {
573     Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
574   }
575 }
576 
577 // Linker relaxation may change code size. We have to insert Nops
578 // for .align directive when linker relaxation enabled. So then Linker
579 // could satisfy alignment by removing Nops.
580 // The function return the total Nops Size we need to insert.
581 bool RISCVAsmBackend::shouldInsertExtraNopBytesForCodeAlign(
582     const MCAlignFragment &AF, unsigned &Size) {
583   // Calculate Nops Size only when linker relaxation enabled.
584   if (!STI.getFeatureBits()[RISCV::FeatureRelax])
585     return false;
586 
587   bool HasStdExtC = STI.getFeatureBits()[RISCV::FeatureStdExtC];
588   unsigned MinNopLen = HasStdExtC ? 2 : 4;
589 
590   if (AF.getAlignment() <= MinNopLen) {
591     return false;
592   } else {
593     Size = AF.getAlignment() - MinNopLen;
594     return true;
595   }
596 }
597 
598 // We need to insert R_RISCV_ALIGN relocation type to indicate the
599 // position of Nops and the total bytes of the Nops have been inserted
600 // when linker relaxation enabled.
601 // The function insert fixup_riscv_align fixup which eventually will
602 // transfer to R_RISCV_ALIGN relocation type.
603 bool RISCVAsmBackend::shouldInsertFixupForCodeAlign(MCAssembler &Asm,
604                                                     const MCAsmLayout &Layout,
605                                                     MCAlignFragment &AF) {
606   // Insert the fixup only when linker relaxation enabled.
607   if (!STI.getFeatureBits()[RISCV::FeatureRelax])
608     return false;
609 
610   // Calculate total Nops we need to insert. If there are none to insert
611   // then simply return.
612   unsigned Count;
613   if (!shouldInsertExtraNopBytesForCodeAlign(AF, Count) || (Count == 0))
614     return false;
615 
616   MCContext &Ctx = Asm.getContext();
617   const MCExpr *Dummy = MCConstantExpr::create(0, Ctx);
618   // Create fixup_riscv_align fixup.
619   MCFixup Fixup =
620       MCFixup::create(0, Dummy, MCFixupKind(RISCV::fixup_riscv_align), SMLoc());
621 
622   uint64_t FixedValue = 0;
623   MCValue NopBytes = MCValue::get(Count);
624 
625   Asm.getWriter().recordRelocation(Asm, Layout, &AF, Fixup, NopBytes,
626                                    FixedValue);
627 
628   return true;
629 }
630 
631 std::unique_ptr<MCObjectTargetWriter>
632 RISCVAsmBackend::createObjectTargetWriter() const {
633   return createRISCVELFObjectWriter(OSABI, Is64Bit);
634 }
635 
636 MCAsmBackend *llvm::createRISCVAsmBackend(const Target &T,
637                                           const MCSubtargetInfo &STI,
638                                           const MCRegisterInfo &MRI,
639                                           const MCTargetOptions &Options) {
640   const Triple &TT = STI.getTargetTriple();
641   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
642   return new RISCVAsmBackend(STI, OSABI, TT.isArch64Bit(), Options);
643 }
644