1 //===-- PPCAsmBackend.cpp - PPC 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 "MCTargetDesc/PPCFixupKinds.h"
10 #include "MCTargetDesc/PPCMCTargetDesc.h"
11 #include "llvm/BinaryFormat/ELF.h"
12 #include "llvm/BinaryFormat/MachO.h"
13 #include "llvm/MC/MCAsmBackend.h"
14 #include "llvm/MC/MCAssembler.h"
15 #include "llvm/MC/MCELFObjectWriter.h"
16 #include "llvm/MC/MCFixupKindInfo.h"
17 #include "llvm/MC/MCMachObjectWriter.h"
18 #include "llvm/MC/MCObjectWriter.h"
19 #include "llvm/MC/MCSectionMachO.h"
20 #include "llvm/MC/MCSubtargetInfo.h"
21 #include "llvm/MC/MCSymbolELF.h"
22 #include "llvm/MC/MCSymbolXCOFF.h"
23 #include "llvm/MC/MCValue.h"
24 #include "llvm/MC/TargetRegistry.h"
25 #include "llvm/Support/ErrorHandling.h"
26 using namespace llvm;
27 
28 static uint64_t adjustFixupValue(unsigned Kind, uint64_t Value) {
29   switch (Kind) {
30   default:
31     llvm_unreachable("Unknown fixup kind!");
32   case FK_Data_1:
33   case FK_Data_2:
34   case FK_Data_4:
35   case FK_Data_8:
36   case PPC::fixup_ppc_nofixup:
37     return Value;
38   case PPC::fixup_ppc_brcond14:
39   case PPC::fixup_ppc_brcond14abs:
40     return Value & 0xfffc;
41   case PPC::fixup_ppc_br24:
42   case PPC::fixup_ppc_br24abs:
43   case PPC::fixup_ppc_br24_notoc:
44     return Value & 0x3fffffc;
45   case PPC::fixup_ppc_half16:
46     return Value & 0xffff;
47   case PPC::fixup_ppc_half16ds:
48   case PPC::fixup_ppc_half16dq:
49     return Value & 0xfffc;
50   case PPC::fixup_ppc_pcrel34:
51   case PPC::fixup_ppc_imm34:
52     return Value & 0x3ffffffff;
53   }
54 }
55 
56 static unsigned getFixupKindNumBytes(unsigned Kind) {
57   switch (Kind) {
58   default:
59     llvm_unreachable("Unknown fixup kind!");
60   case FK_Data_1:
61     return 1;
62   case FK_Data_2:
63   case PPC::fixup_ppc_half16:
64   case PPC::fixup_ppc_half16ds:
65   case PPC::fixup_ppc_half16dq:
66     return 2;
67   case FK_Data_4:
68   case PPC::fixup_ppc_brcond14:
69   case PPC::fixup_ppc_brcond14abs:
70   case PPC::fixup_ppc_br24:
71   case PPC::fixup_ppc_br24abs:
72   case PPC::fixup_ppc_br24_notoc:
73     return 4;
74   case PPC::fixup_ppc_pcrel34:
75   case PPC::fixup_ppc_imm34:
76   case FK_Data_8:
77     return 8;
78   case PPC::fixup_ppc_nofixup:
79     return 0;
80   }
81 }
82 
83 namespace {
84 
85 class PPCAsmBackend : public MCAsmBackend {
86 protected:
87   Triple TT;
88 public:
89   PPCAsmBackend(const Target &T, const Triple &TT)
90       : MCAsmBackend(TT.isLittleEndian() ? support::little : support::big),
91         TT(TT) {}
92 
93   unsigned getNumFixupKinds() const override {
94     return PPC::NumTargetFixupKinds;
95   }
96 
97   const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override {
98     const static MCFixupKindInfo InfosBE[PPC::NumTargetFixupKinds] = {
99       // name                    offset  bits  flags
100       { "fixup_ppc_br24",        6,      24,   MCFixupKindInfo::FKF_IsPCRel },
101       { "fixup_ppc_br24_notoc",  6,      24,   MCFixupKindInfo::FKF_IsPCRel },
102       { "fixup_ppc_brcond14",    16,     14,   MCFixupKindInfo::FKF_IsPCRel },
103       { "fixup_ppc_br24abs",     6,      24,   0 },
104       { "fixup_ppc_brcond14abs", 16,     14,   0 },
105       { "fixup_ppc_half16",       0,     16,   0 },
106       { "fixup_ppc_half16ds",     0,     14,   0 },
107       { "fixup_ppc_pcrel34",     0,      34,   MCFixupKindInfo::FKF_IsPCRel },
108       { "fixup_ppc_imm34",       0,      34,   0 },
109       { "fixup_ppc_nofixup",      0,      0,   0 }
110     };
111     const static MCFixupKindInfo InfosLE[PPC::NumTargetFixupKinds] = {
112       // name                    offset  bits  flags
113       { "fixup_ppc_br24",        2,      24,   MCFixupKindInfo::FKF_IsPCRel },
114       { "fixup_ppc_br24_notoc",  2,      24,   MCFixupKindInfo::FKF_IsPCRel },
115       { "fixup_ppc_brcond14",    2,      14,   MCFixupKindInfo::FKF_IsPCRel },
116       { "fixup_ppc_br24abs",     2,      24,   0 },
117       { "fixup_ppc_brcond14abs", 2,      14,   0 },
118       { "fixup_ppc_half16",      0,      16,   0 },
119       { "fixup_ppc_half16ds",    2,      14,   0 },
120       { "fixup_ppc_pcrel34",     0,      34,   MCFixupKindInfo::FKF_IsPCRel },
121       { "fixup_ppc_imm34",       0,      34,   0 },
122       { "fixup_ppc_nofixup",     0,       0,   0 }
123     };
124 
125     // Fixup kinds from .reloc directive are like R_PPC_NONE/R_PPC64_NONE. They
126     // do not require any extra processing.
127     if (Kind >= FirstLiteralRelocationKind)
128       return MCAsmBackend::getFixupKindInfo(FK_NONE);
129 
130     if (Kind < FirstTargetFixupKind)
131       return MCAsmBackend::getFixupKindInfo(Kind);
132 
133     assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
134            "Invalid kind!");
135     return (Endian == support::little
136                 ? InfosLE
137                 : InfosBE)[Kind - FirstTargetFixupKind];
138   }
139 
140   void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
141                   const MCValue &Target, MutableArrayRef<char> Data,
142                   uint64_t Value, bool IsResolved,
143                   const MCSubtargetInfo *STI) const override {
144     MCFixupKind Kind = Fixup.getKind();
145     if (Kind >= FirstLiteralRelocationKind)
146       return;
147     Value = adjustFixupValue(Kind, Value);
148     if (!Value) return;           // Doesn't change encoding.
149 
150     unsigned Offset = Fixup.getOffset();
151     unsigned NumBytes = getFixupKindNumBytes(Kind);
152 
153     // For each byte of the fragment that the fixup touches, mask in the bits
154     // from the fixup value. The Value has been "split up" into the appropriate
155     // bitfields above.
156     for (unsigned i = 0; i != NumBytes; ++i) {
157       unsigned Idx = Endian == support::little ? i : (NumBytes - 1 - i);
158       Data[Offset + i] |= uint8_t((Value >> (Idx * 8)) & 0xff);
159     }
160   }
161 
162   bool shouldForceRelocation(const MCAssembler &Asm, const MCFixup &Fixup,
163                              const MCValue &Target) override {
164     MCFixupKind Kind = Fixup.getKind();
165     switch ((unsigned)Kind) {
166     default:
167       return Kind >= FirstLiteralRelocationKind;
168     case PPC::fixup_ppc_br24:
169     case PPC::fixup_ppc_br24abs:
170     case PPC::fixup_ppc_br24_notoc:
171       // If the target symbol has a local entry point we must not attempt
172       // to resolve the fixup directly.  Emit a relocation and leave
173       // resolution of the final target address to the linker.
174       if (const MCSymbolRefExpr *A = Target.getSymA()) {
175         if (const auto *S = dyn_cast<MCSymbolELF>(&A->getSymbol())) {
176           // The "other" values are stored in the last 6 bits of the second
177           // byte. The traditional defines for STO values assume the full byte
178           // and thus the shift to pack it.
179           unsigned Other = S->getOther() << 2;
180           if ((Other & ELF::STO_PPC64_LOCAL_MASK) != 0)
181             return true;
182         } else if (const auto *S = dyn_cast<MCSymbolXCOFF>(&A->getSymbol())) {
183           return !Target.isAbsolute() && S->isExternal() &&
184                  S->getStorageClass() == XCOFF::C_WEAKEXT;
185        }
186       }
187       return false;
188     }
189   }
190 
191   bool fixupNeedsRelaxation(const MCFixup &Fixup,
192                             uint64_t Value,
193                             const MCRelaxableFragment *DF,
194                             const MCAsmLayout &Layout) const override {
195     // FIXME.
196     llvm_unreachable("relaxInstruction() unimplemented");
197   }
198 
199   void relaxInstruction(MCInst &Inst,
200                         const MCSubtargetInfo &STI) const override {
201     // FIXME.
202     llvm_unreachable("relaxInstruction() unimplemented");
203   }
204 
205   bool writeNopData(raw_ostream &OS, uint64_t Count,
206                     const MCSubtargetInfo *STI) const override {
207     uint64_t NumNops = Count / 4;
208     for (uint64_t i = 0; i != NumNops; ++i)
209       support::endian::write<uint32_t>(OS, 0x60000000, Endian);
210 
211     OS.write_zeros(Count % 4);
212 
213     return true;
214   }
215 };
216 } // end anonymous namespace
217 
218 
219 // FIXME: This should be in a separate file.
220 namespace {
221 
222 class ELFPPCAsmBackend : public PPCAsmBackend {
223 public:
224   ELFPPCAsmBackend(const Target &T, const Triple &TT) : PPCAsmBackend(T, TT) {}
225 
226   std::unique_ptr<MCObjectTargetWriter>
227   createObjectTargetWriter() const override {
228     uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
229     bool Is64 = TT.isPPC64();
230     return createPPCELFObjectWriter(Is64, OSABI);
231   }
232 
233   std::optional<MCFixupKind> getFixupKind(StringRef Name) const override;
234 };
235 
236 class XCOFFPPCAsmBackend : public PPCAsmBackend {
237 public:
238   XCOFFPPCAsmBackend(const Target &T, const Triple &TT)
239       : PPCAsmBackend(T, TT) {}
240 
241   std::unique_ptr<MCObjectTargetWriter>
242   createObjectTargetWriter() const override {
243     return createPPCXCOFFObjectWriter(TT.isArch64Bit());
244   }
245 
246   std::optional<MCFixupKind> getFixupKind(StringRef Name) const override;
247 };
248 
249 } // end anonymous namespace
250 
251 std::optional<MCFixupKind>
252 ELFPPCAsmBackend::getFixupKind(StringRef Name) const {
253   if (TT.isOSBinFormatELF()) {
254     unsigned Type;
255     if (TT.isPPC64()) {
256       Type = llvm::StringSwitch<unsigned>(Name)
257 #define ELF_RELOC(X, Y) .Case(#X, Y)
258 #include "llvm/BinaryFormat/ELFRelocs/PowerPC64.def"
259 #undef ELF_RELOC
260                  .Case("BFD_RELOC_NONE", ELF::R_PPC64_NONE)
261                  .Case("BFD_RELOC_16", ELF::R_PPC64_ADDR16)
262                  .Case("BFD_RELOC_32", ELF::R_PPC64_ADDR32)
263                  .Case("BFD_RELOC_64", ELF::R_PPC64_ADDR64)
264                  .Default(-1u);
265     } else {
266       Type = llvm::StringSwitch<unsigned>(Name)
267 #define ELF_RELOC(X, Y) .Case(#X, Y)
268 #include "llvm/BinaryFormat/ELFRelocs/PowerPC.def"
269 #undef ELF_RELOC
270                  .Case("BFD_RELOC_NONE", ELF::R_PPC_NONE)
271                  .Case("BFD_RELOC_16", ELF::R_PPC_ADDR16)
272                  .Case("BFD_RELOC_32", ELF::R_PPC_ADDR32)
273                  .Default(-1u);
274     }
275     if (Type != -1u)
276       return static_cast<MCFixupKind>(FirstLiteralRelocationKind + Type);
277   }
278   return std::nullopt;
279 }
280 
281 std::optional<MCFixupKind>
282 XCOFFPPCAsmBackend::getFixupKind(StringRef Name) const {
283   return StringSwitch<std::optional<MCFixupKind>>(Name)
284       .Case("R_REF", (MCFixupKind)PPC::fixup_ppc_nofixup)
285       .Default(std::nullopt);
286 }
287 
288 MCAsmBackend *llvm::createPPCAsmBackend(const Target &T,
289                                         const MCSubtargetInfo &STI,
290                                         const MCRegisterInfo &MRI,
291                                         const MCTargetOptions &Options) {
292   const Triple &TT = STI.getTargetTriple();
293   if (TT.isOSBinFormatXCOFF())
294     return new XCOFFPPCAsmBackend(T, TT);
295 
296   return new ELFPPCAsmBackend(T, TT);
297 }
298