1 //===-- AVRAsmBackend.cpp - AVR Asm 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 // This file implements the AVRAsmBackend class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "MCTargetDesc/AVRAsmBackend.h"
14 #include "MCTargetDesc/AVRFixupKinds.h"
15 #include "MCTargetDesc/AVRMCTargetDesc.h"
16 
17 #include "llvm/MC/MCAsmBackend.h"
18 #include "llvm/MC/MCAssembler.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDirectives.h"
21 #include "llvm/MC/MCELFObjectWriter.h"
22 #include "llvm/MC/MCFixupKindInfo.h"
23 #include "llvm/MC/MCObjectWriter.h"
24 #include "llvm/MC/MCSubtargetInfo.h"
25 #include "llvm/MC/MCValue.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/raw_ostream.h"
29 
30 // FIXME: we should be doing checks to make sure asm operands
31 // are not out of bounds.
32 
33 namespace adjust {
34 
35 using namespace llvm;
36 
37 static void signed_width(unsigned Width, uint64_t Value,
38                          std::string Description, const MCFixup &Fixup,
39                          MCContext *Ctx = nullptr) {
40   if (!isIntN(Width, Value)) {
41     std::string Diagnostic = "out of range " + Description;
42 
43     int64_t Min = minIntN(Width);
44     int64_t Max = maxIntN(Width);
45 
46     Diagnostic += " (expected an integer in the range " + std::to_string(Min) +
47       " to " + std::to_string(Max) + ")";
48 
49     if (Ctx) {
50       Ctx->reportFatalError(Fixup.getLoc(), Diagnostic);
51     } else {
52       llvm_unreachable(Diagnostic.c_str());
53     }
54   }
55 }
56 
57 static void unsigned_width(unsigned Width, uint64_t Value,
58                            std::string Description, const MCFixup &Fixup,
59                            MCContext *Ctx = nullptr) {
60   if (!isUIntN(Width, Value)) {
61     std::string Diagnostic = "out of range " + Description;
62 
63     int64_t Max = maxUIntN(Width);
64 
65     Diagnostic += " (expected an integer in the range 0 to " +
66       std::to_string(Max) + ")";
67 
68     if (Ctx) {
69       Ctx->reportFatalError(Fixup.getLoc(), Diagnostic);
70     } else {
71       llvm_unreachable(Diagnostic.c_str());
72     }
73   }
74 }
75 
76 /// Adjusts the value of a branch target before fixup application.
77 static void adjustBranch(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
78                          MCContext *Ctx = nullptr) {
79   // We have one extra bit of precision because the value is rightshifted by
80   // one.
81   unsigned_width(Size + 1, Value, std::string("branch target"), Fixup, Ctx);
82 
83   // Rightshifts the value by one.
84   AVR::fixups::adjustBranchTarget(Value);
85 }
86 
87 /// Adjusts the value of a relative branch target before fixup application.
88 static void adjustRelativeBranch(unsigned Size, const MCFixup &Fixup,
89                                  uint64_t &Value, MCContext *Ctx = nullptr) {
90   // We have one extra bit of precision because the value is rightshifted by
91   // one.
92   signed_width(Size + 1, Value, std::string("branch target"), Fixup, Ctx);
93 
94   Value -= 2;
95 
96   // Rightshifts the value by one.
97   AVR::fixups::adjustBranchTarget(Value);
98 }
99 
100 /// 22-bit absolute fixup.
101 ///
102 /// Resolves to:
103 /// 1001 kkkk 010k kkkk kkkk kkkk 111k kkkk
104 ///
105 /// Offset of 0 (so the result is left shifted by 3 bits before application).
106 static void fixup_call(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
107                        MCContext *Ctx = nullptr) {
108   adjustBranch(Size, Fixup, Value, Ctx);
109 
110   auto top = Value & (0xf00000 << 6);   // the top four bits
111   auto middle = Value & (0x1ffff << 5); // the middle 13 bits
112   auto bottom = Value & 0x1f;           // end bottom 5 bits
113 
114   Value = (top << 6) | (middle << 3) | (bottom << 0);
115 }
116 
117 /// 7-bit PC-relative fixup.
118 ///
119 /// Resolves to:
120 /// 0000 00kk kkkk k000
121 /// Offset of 0 (so the result is left shifted by 3 bits before application).
122 static void fixup_7_pcrel(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
123                           MCContext *Ctx = nullptr) {
124   adjustRelativeBranch(Size, Fixup, Value, Ctx);
125 
126   // Because the value may be negative, we must mask out the sign bits
127   Value &= 0x7f;
128 }
129 
130 /// 12-bit PC-relative fixup.
131 /// Yes, the fixup is 12 bits even though the name says otherwise.
132 ///
133 /// Resolves to:
134 /// 0000 kkkk kkkk kkkk
135 /// Offset of 0 (so the result isn't left-shifted before application).
136 static void fixup_13_pcrel(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
137                            MCContext *Ctx = nullptr) {
138   adjustRelativeBranch(Size, Fixup, Value, Ctx);
139 
140   // Because the value may be negative, we must mask out the sign bits
141   Value &= 0xfff;
142 }
143 
144 /// 6-bit fixup for the immediate operand of the STD/LDD family of
145 /// instructions.
146 ///
147 /// Resolves to:
148 /// 10q0 qq10 0000 1qqq
149 static void fixup_6(const MCFixup &Fixup, uint64_t &Value,
150                     MCContext *Ctx = nullptr) {
151   unsigned_width(6, Value, std::string("immediate"), Fixup, Ctx);
152 
153   Value = ((Value & 0x20) << 8) | ((Value & 0x18) << 7) | (Value & 0x07);
154 }
155 
156 /// 6-bit fixup for the immediate operand of the ADIW family of
157 /// instructions.
158 ///
159 /// Resolves to:
160 /// 0000 0000 kk00 kkkk
161 static void fixup_6_adiw(const MCFixup &Fixup, uint64_t &Value,
162                          MCContext *Ctx = nullptr) {
163   unsigned_width(6, Value, std::string("immediate"), Fixup, Ctx);
164 
165   Value = ((Value & 0x30) << 2) | (Value & 0x0f);
166 }
167 
168 /// 5-bit port number fixup on the SBIC family of instructions.
169 ///
170 /// Resolves to:
171 /// 0000 0000 AAAA A000
172 static void fixup_port5(const MCFixup &Fixup, uint64_t &Value,
173                         MCContext *Ctx = nullptr) {
174   unsigned_width(5, Value, std::string("port number"), Fixup, Ctx);
175 
176   Value &= 0x1f;
177 
178   Value <<= 3;
179 }
180 
181 /// 6-bit port number fixup on the `IN` family of instructions.
182 ///
183 /// Resolves to:
184 /// 1011 0AAd dddd AAAA
185 static void fixup_port6(const MCFixup &Fixup, uint64_t &Value,
186                         MCContext *Ctx = nullptr) {
187   unsigned_width(6, Value, std::string("port number"), Fixup, Ctx);
188 
189   Value = ((Value & 0x30) << 5) | (Value & 0x0f);
190 }
191 
192 /// Adjusts a program memory address.
193 /// This is a simple right-shift.
194 static void pm(uint64_t &Value) { Value >>= 1; }
195 
196 /// Fixups relating to the LDI instruction.
197 namespace ldi {
198 
199 /// Adjusts a value to fix up the immediate of an `LDI Rd, K` instruction.
200 ///
201 /// Resolves to:
202 /// 0000 KKKK 0000 KKKK
203 /// Offset of 0 (so the result isn't left-shifted before application).
204 static void fixup(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
205                   MCContext *Ctx = nullptr) {
206   uint64_t upper = Value & 0xf0;
207   uint64_t lower = Value & 0x0f;
208 
209   Value = (upper << 4) | lower;
210 }
211 
212 static void neg(uint64_t &Value) { Value *= -1; }
213 
214 static void lo8(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
215                 MCContext *Ctx = nullptr) {
216   Value &= 0xff;
217   ldi::fixup(Size, Fixup, Value, Ctx);
218 }
219 
220 static void hi8(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
221                 MCContext *Ctx = nullptr) {
222   Value = (Value & 0xff00) >> 8;
223   ldi::fixup(Size, Fixup, Value, Ctx);
224 }
225 
226 static void hh8(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
227                 MCContext *Ctx = nullptr) {
228   Value = (Value & 0xff0000) >> 16;
229   ldi::fixup(Size, Fixup, Value, Ctx);
230 }
231 
232 static void ms8(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
233                 MCContext *Ctx = nullptr) {
234   Value = (Value & 0xff000000) >> 24;
235   ldi::fixup(Size, Fixup, Value, Ctx);
236 }
237 
238 } // end of ldi namespace
239 } // end of adjust namespace
240 
241 namespace llvm {
242 
243 // Prepare value for the target space for it
244 void AVRAsmBackend::adjustFixupValue(const MCFixup &Fixup,
245                                      const MCValue &Target,
246                                      uint64_t &Value,
247                                      MCContext *Ctx) const {
248   // The size of the fixup in bits.
249   uint64_t Size = AVRAsmBackend::getFixupKindInfo(Fixup.getKind()).TargetSize;
250 
251   unsigned Kind = Fixup.getKind();
252 
253   // Parsed LLVM-generated temporary labels are already
254   // adjusted for instruction size, but normal labels aren't.
255   //
256   // To handle both cases, we simply un-adjust the temporary label
257   // case so it acts like all other labels.
258   if (const MCSymbolRefExpr *A = Target.getSymA()) {
259     if (A->getSymbol().isTemporary()) {
260       switch (Kind) {
261       case FK_Data_1:
262       case FK_Data_2:
263       case FK_Data_4:
264       case FK_Data_8:
265         // Don't shift value for absolute addresses.
266         break;
267       default:
268         Value += 2;
269       }
270     }
271   }
272 
273   switch (Kind) {
274   default:
275     llvm_unreachable("unhandled fixup");
276   case AVR::fixup_7_pcrel:
277     adjust::fixup_7_pcrel(Size, Fixup, Value, Ctx);
278     break;
279   case AVR::fixup_13_pcrel:
280     adjust::fixup_13_pcrel(Size, Fixup, Value, Ctx);
281     break;
282   case AVR::fixup_call:
283     adjust::fixup_call(Size, Fixup, Value, Ctx);
284     break;
285   case AVR::fixup_ldi:
286     adjust::ldi::fixup(Size, Fixup, Value, Ctx);
287     break;
288   case AVR::fixup_lo8_ldi:
289     adjust::ldi::lo8(Size, Fixup, Value, Ctx);
290     break;
291   case AVR::fixup_lo8_ldi_pm:
292   case AVR::fixup_lo8_ldi_gs:
293     adjust::pm(Value);
294     adjust::ldi::lo8(Size, Fixup, Value, Ctx);
295     break;
296   case AVR::fixup_hi8_ldi:
297     adjust::ldi::hi8(Size, Fixup, Value, Ctx);
298     break;
299   case AVR::fixup_hi8_ldi_pm:
300   case AVR::fixup_hi8_ldi_gs:
301     adjust::pm(Value);
302     adjust::ldi::hi8(Size, Fixup, Value, Ctx);
303     break;
304   case AVR::fixup_hh8_ldi:
305   case AVR::fixup_hh8_ldi_pm:
306     if (Kind == AVR::fixup_hh8_ldi_pm) adjust::pm(Value);
307 
308     adjust::ldi::hh8(Size, Fixup, Value, Ctx);
309     break;
310   case AVR::fixup_ms8_ldi:
311     adjust::ldi::ms8(Size, Fixup, Value, Ctx);
312     break;
313 
314   case AVR::fixup_lo8_ldi_neg:
315   case AVR::fixup_lo8_ldi_pm_neg:
316     if (Kind == AVR::fixup_lo8_ldi_pm_neg) adjust::pm(Value);
317 
318     adjust::ldi::neg(Value);
319     adjust::ldi::lo8(Size, Fixup, Value, Ctx);
320     break;
321   case AVR::fixup_hi8_ldi_neg:
322   case AVR::fixup_hi8_ldi_pm_neg:
323     if (Kind == AVR::fixup_hi8_ldi_pm_neg) adjust::pm(Value);
324 
325     adjust::ldi::neg(Value);
326     adjust::ldi::hi8(Size, Fixup, Value, Ctx);
327     break;
328   case AVR::fixup_hh8_ldi_neg:
329   case AVR::fixup_hh8_ldi_pm_neg:
330     if (Kind == AVR::fixup_hh8_ldi_pm_neg) adjust::pm(Value);
331 
332     adjust::ldi::neg(Value);
333     adjust::ldi::hh8(Size, Fixup, Value, Ctx);
334     break;
335   case AVR::fixup_ms8_ldi_neg:
336     adjust::ldi::neg(Value);
337     adjust::ldi::ms8(Size, Fixup, Value, Ctx);
338     break;
339   case AVR::fixup_16:
340     adjust::unsigned_width(16, Value, std::string("port number"), Fixup, Ctx);
341 
342     Value &= 0xffff;
343     break;
344   case AVR::fixup_16_pm:
345     Value >>= 1; // Flash addresses are always shifted.
346     adjust::unsigned_width(16, Value, std::string("port number"), Fixup, Ctx);
347 
348     Value &= 0xffff;
349     break;
350 
351   case AVR::fixup_6:
352     adjust::fixup_6(Fixup, Value, Ctx);
353     break;
354   case AVR::fixup_6_adiw:
355     adjust::fixup_6_adiw(Fixup, Value, Ctx);
356     break;
357 
358   case AVR::fixup_port5:
359     adjust::fixup_port5(Fixup, Value, Ctx);
360     break;
361 
362   case AVR::fixup_port6:
363     adjust::fixup_port6(Fixup, Value, Ctx);
364     break;
365 
366   // Fixups which do not require adjustments.
367   case FK_Data_1:
368   case FK_Data_2:
369   case FK_Data_4:
370   case FK_Data_8:
371     break;
372 
373   case FK_GPRel_4:
374     llvm_unreachable("don't know how to adjust this fixup");
375     break;
376   }
377 }
378 
379 std::unique_ptr<MCObjectTargetWriter>
380 AVRAsmBackend::createObjectTargetWriter() const {
381   return createAVRELFObjectWriter(MCELFObjectTargetWriter::getOSABI(OSType));
382 }
383 
384 void AVRAsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
385                                const MCValue &Target,
386                                MutableArrayRef<char> Data, uint64_t Value,
387                                bool IsResolved,
388                                const MCSubtargetInfo *STI) const {
389   adjustFixupValue(Fixup, Target, Value, &Asm.getContext());
390   if (Value == 0)
391     return; // Doesn't change encoding.
392 
393   MCFixupKindInfo Info = getFixupKindInfo(Fixup.getKind());
394 
395   // The number of bits in the fixup mask
396   auto NumBits = Info.TargetSize + Info.TargetOffset;
397   auto NumBytes = (NumBits / 8) + ((NumBits % 8) == 0 ? 0 : 1);
398 
399   // Shift the value into position.
400   Value <<= Info.TargetOffset;
401 
402   unsigned Offset = Fixup.getOffset();
403   assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
404 
405   // For each byte of the fragment that the fixup touches, mask in the
406   // bits from the fixup value.
407   for (unsigned i = 0; i < NumBytes; ++i) {
408     uint8_t mask = (((Value >> (i * 8)) & 0xff));
409     Data[Offset + i] |= mask;
410   }
411 }
412 
413 MCFixupKindInfo const &AVRAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
414   // NOTE: Many AVR fixups work on sets of non-contignous bits. We work around
415   // this by saying that the fixup is the size of the entire instruction.
416   const static MCFixupKindInfo Infos[AVR::NumTargetFixupKinds] = {
417       // This table *must* be in same the order of fixup_* kinds in
418       // AVRFixupKinds.h.
419       //
420       // name                    offset  bits  flags
421       {"fixup_32", 0, 32, 0},
422 
423       {"fixup_7_pcrel", 3, 7, MCFixupKindInfo::FKF_IsPCRel},
424       {"fixup_13_pcrel", 0, 12, MCFixupKindInfo::FKF_IsPCRel},
425 
426       {"fixup_16", 0, 16, 0},
427       {"fixup_16_pm", 0, 16, 0},
428 
429       {"fixup_ldi", 0, 8, 0},
430 
431       {"fixup_lo8_ldi", 0, 8, 0},
432       {"fixup_hi8_ldi", 0, 8, 0},
433       {"fixup_hh8_ldi", 0, 8, 0},
434       {"fixup_ms8_ldi", 0, 8, 0},
435 
436       {"fixup_lo8_ldi_neg", 0, 8, 0},
437       {"fixup_hi8_ldi_neg", 0, 8, 0},
438       {"fixup_hh8_ldi_neg", 0, 8, 0},
439       {"fixup_ms8_ldi_neg", 0, 8, 0},
440 
441       {"fixup_lo8_ldi_pm", 0, 8, 0},
442       {"fixup_hi8_ldi_pm", 0, 8, 0},
443       {"fixup_hh8_ldi_pm", 0, 8, 0},
444 
445       {"fixup_lo8_ldi_pm_neg", 0, 8, 0},
446       {"fixup_hi8_ldi_pm_neg", 0, 8, 0},
447       {"fixup_hh8_ldi_pm_neg", 0, 8, 0},
448 
449       {"fixup_call", 0, 22, 0},
450 
451       {"fixup_6", 0, 16, 0}, // non-contiguous
452       {"fixup_6_adiw", 0, 6, 0},
453 
454       {"fixup_lo8_ldi_gs", 0, 8, 0},
455       {"fixup_hi8_ldi_gs", 0, 8, 0},
456 
457       {"fixup_8", 0, 8, 0},
458       {"fixup_8_lo8", 0, 8, 0},
459       {"fixup_8_hi8", 0, 8, 0},
460       {"fixup_8_hlo8", 0, 8, 0},
461 
462       {"fixup_diff8", 0, 8, 0},
463       {"fixup_diff16", 0, 16, 0},
464       {"fixup_diff32", 0, 32, 0},
465 
466       {"fixup_lds_sts_16", 0, 16, 0},
467 
468       {"fixup_port6", 0, 16, 0}, // non-contiguous
469       {"fixup_port5", 3, 5, 0},
470   };
471 
472   if (Kind < FirstTargetFixupKind)
473     return MCAsmBackend::getFixupKindInfo(Kind);
474 
475   assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
476          "Invalid kind!");
477 
478   return Infos[Kind - FirstTargetFixupKind];
479 }
480 
481 bool AVRAsmBackend::writeNopData(raw_ostream &OS, uint64_t Count) const {
482   // If the count is not 2-byte aligned, we must be writing data into the text
483   // section (otherwise we have unaligned instructions, and thus have far
484   // bigger problems), so just write zeros instead.
485   assert((Count % 2) == 0 && "NOP instructions must be 2 bytes");
486 
487   OS.write_zeros(Count);
488   return true;
489 }
490 
491 bool AVRAsmBackend::shouldForceRelocation(const MCAssembler &Asm,
492                                           const MCFixup &Fixup,
493                                           const MCValue &Target) {
494   switch ((unsigned) Fixup.getKind()) {
495   default: return false;
496   // Fixups which should always be recorded as relocations.
497   case AVR::fixup_7_pcrel:
498   case AVR::fixup_13_pcrel:
499   case AVR::fixup_call:
500     return true;
501   }
502 }
503 
504 MCAsmBackend *createAVRAsmBackend(const Target &T, const MCSubtargetInfo &STI,
505                                   const MCRegisterInfo &MRI,
506                                   const llvm::MCTargetOptions &TO) {
507   return new AVRAsmBackend(STI.getTargetTriple().getOS());
508 }
509 
510 } // end of namespace llvm
511 
512