1 //===-- PPCMCTargetDesc.cpp - PowerPC Target Descriptions -----------------===//
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 provides PowerPC specific target descriptions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "MCTargetDesc/PPCMCTargetDesc.h"
14 #include "MCTargetDesc/PPCInstPrinter.h"
15 #include "MCTargetDesc/PPCMCAsmInfo.h"
16 #include "PPCELFStreamer.h"
17 #include "PPCTargetStreamer.h"
18 #include "TargetInfo/PowerPCTargetInfo.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/BinaryFormat/ELF.h"
23 #include "llvm/MC/MCAssembler.h"
24 #include "llvm/MC/MCAsmBackend.h"
25 #include "llvm/MC/MCCodeEmitter.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCDwarf.h"
28 #include "llvm/MC/MCELFStreamer.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCInstrInfo.h"
31 #include "llvm/MC/MCObjectWriter.h"
32 #include "llvm/MC/MCRegisterInfo.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSubtargetInfo.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/MC/MCSymbolELF.h"
37 #include "llvm/MC/MCSymbolXCOFF.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/CodeGen.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/raw_ostream.h"
44 
45 using namespace llvm;
46 
47 #define GET_INSTRINFO_MC_DESC
48 #include "PPCGenInstrInfo.inc"
49 
50 #define GET_SUBTARGETINFO_MC_DESC
51 #include "PPCGenSubtargetInfo.inc"
52 
53 #define GET_REGINFO_MC_DESC
54 #include "PPCGenRegisterInfo.inc"
55 
56 PPCTargetStreamer::PPCTargetStreamer(MCStreamer &S) : MCTargetStreamer(S) {}
57 
58 // Pin the vtable to this file.
59 PPCTargetStreamer::~PPCTargetStreamer() = default;
60 
61 static MCInstrInfo *createPPCMCInstrInfo() {
62   MCInstrInfo *X = new MCInstrInfo();
63   InitPPCMCInstrInfo(X);
64   return X;
65 }
66 
67 static MCRegisterInfo *createPPCMCRegisterInfo(const Triple &TT) {
68   bool isPPC64 =
69       (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le);
70   unsigned Flavour = isPPC64 ? 0 : 1;
71   unsigned RA = isPPC64 ? PPC::LR8 : PPC::LR;
72 
73   MCRegisterInfo *X = new MCRegisterInfo();
74   InitPPCMCRegisterInfo(X, RA, Flavour, Flavour);
75   return X;
76 }
77 
78 static MCSubtargetInfo *createPPCMCSubtargetInfo(const Triple &TT,
79                                                  StringRef CPU, StringRef FS) {
80   return createPPCMCSubtargetInfoImpl(TT, CPU, FS);
81 }
82 
83 static MCAsmInfo *createPPCMCAsmInfo(const MCRegisterInfo &MRI,
84                                      const Triple &TheTriple,
85                                      const MCTargetOptions &Options) {
86   bool isPPC64 = (TheTriple.getArch() == Triple::ppc64 ||
87                   TheTriple.getArch() == Triple::ppc64le);
88 
89   MCAsmInfo *MAI;
90   if (TheTriple.isOSBinFormatXCOFF())
91     MAI = new PPCXCOFFMCAsmInfo(isPPC64, TheTriple);
92   else
93     MAI = new PPCELFMCAsmInfo(isPPC64, TheTriple);
94 
95   // Initial state of the frame pointer is R1.
96   unsigned Reg = isPPC64 ? PPC::X1 : PPC::R1;
97   MCCFIInstruction Inst =
98       MCCFIInstruction::cfiDefCfa(nullptr, MRI.getDwarfRegNum(Reg, true), 0);
99   MAI->addInitialFrameState(Inst);
100 
101   return MAI;
102 }
103 
104 static MCStreamer *createPPCMCStreamer(const Triple &T, MCContext &Context,
105                                        std::unique_ptr<MCAsmBackend> &&MAB,
106                                        std::unique_ptr<MCObjectWriter> &&OW,
107                                        std::unique_ptr<MCCodeEmitter> &&Emitter,
108                                        bool RelaxAll) {
109   return createPPCELFStreamer(Context, std::move(MAB), std::move(OW),
110                               std::move(Emitter));
111 }
112 
113 namespace {
114 
115 class PPCTargetAsmStreamer : public PPCTargetStreamer {
116   formatted_raw_ostream &OS;
117 
118 public:
119   PPCTargetAsmStreamer(MCStreamer &S, formatted_raw_ostream &OS)
120       : PPCTargetStreamer(S), OS(OS) {}
121 
122   void emitTCEntry(const MCSymbol &S) override {
123     const MCAsmInfo *MAI = Streamer.getContext().getAsmInfo();
124     OS << "\t.tc ";
125     OS << (MAI->getSymbolsHaveSMC()
126                ? cast<MCSymbolXCOFF>(S).getUnqualifiedName()
127                : S.getName());
128     OS << "[TC],";
129     OS << S.getName();
130     OS << '\n';
131   }
132 
133   void emitMachine(StringRef CPU) override {
134     OS << "\t.machine " << CPU << '\n';
135   }
136 
137   void emitAbiVersion(int AbiVersion) override {
138     OS << "\t.abiversion " << AbiVersion << '\n';
139   }
140 
141   void emitLocalEntry(MCSymbolELF *S, const MCExpr *LocalOffset) override {
142     const MCAsmInfo *MAI = Streamer.getContext().getAsmInfo();
143 
144     OS << "\t.localentry\t";
145     S->print(OS, MAI);
146     OS << ", ";
147     LocalOffset->print(OS, MAI);
148     OS << '\n';
149   }
150 };
151 
152 class PPCTargetELFStreamer : public PPCTargetStreamer {
153 public:
154   PPCTargetELFStreamer(MCStreamer &S) : PPCTargetStreamer(S) {}
155 
156   MCELFStreamer &getStreamer() {
157     return static_cast<MCELFStreamer &>(Streamer);
158   }
159 
160   void emitTCEntry(const MCSymbol &S) override {
161     // Creates a R_PPC64_TOC relocation
162     Streamer.emitValueToAlignment(8);
163     Streamer.emitSymbolValue(&S, 8);
164   }
165 
166   void emitMachine(StringRef CPU) override {
167     // FIXME: Is there anything to do in here or does this directive only
168     // limit the parser?
169   }
170 
171   void emitAbiVersion(int AbiVersion) override {
172     MCAssembler &MCA = getStreamer().getAssembler();
173     unsigned Flags = MCA.getELFHeaderEFlags();
174     Flags &= ~ELF::EF_PPC64_ABI;
175     Flags |= (AbiVersion & ELF::EF_PPC64_ABI);
176     MCA.setELFHeaderEFlags(Flags);
177   }
178 
179   void emitLocalEntry(MCSymbolELF *S, const MCExpr *LocalOffset) override {
180     MCAssembler &MCA = getStreamer().getAssembler();
181 
182     // encodePPC64LocalEntryOffset will report an error if it cannot
183     // encode LocalOffset.
184     unsigned Encoded = encodePPC64LocalEntryOffset(LocalOffset);
185 
186     unsigned Other = S->getOther();
187     Other &= ~ELF::STO_PPC64_LOCAL_MASK;
188     Other |= Encoded;
189     S->setOther(Other);
190 
191     // For GAS compatibility, unless we already saw a .abiversion directive,
192     // set e_flags to indicate ELFv2 ABI.
193     unsigned Flags = MCA.getELFHeaderEFlags();
194     if ((Flags & ELF::EF_PPC64_ABI) == 0)
195       MCA.setELFHeaderEFlags(Flags | 2);
196   }
197 
198   void emitAssignment(MCSymbol *S, const MCExpr *Value) override {
199     auto *Symbol = cast<MCSymbolELF>(S);
200 
201     // When encoding an assignment to set symbol A to symbol B, also copy
202     // the st_other bits encoding the local entry point offset.
203     if (copyLocalEntry(Symbol, Value))
204       UpdateOther.insert(Symbol);
205     else
206       UpdateOther.erase(Symbol);
207   }
208 
209   void finish() override {
210     for (auto *Sym : UpdateOther)
211       if (Sym->isVariable())
212         copyLocalEntry(Sym, Sym->getVariableValue());
213 
214     // Clear the set of symbols that needs to be updated so the streamer can
215     // be reused without issues.
216     UpdateOther.clear();
217   }
218 
219 private:
220   SmallPtrSet<MCSymbolELF *, 32> UpdateOther;
221 
222   bool copyLocalEntry(MCSymbolELF *D, const MCExpr *S) {
223     auto *Ref = dyn_cast<const MCSymbolRefExpr>(S);
224     if (!Ref)
225       return false;
226     const auto &RhsSym = cast<MCSymbolELF>(Ref->getSymbol());
227     unsigned Other = D->getOther();
228     Other &= ~ELF::STO_PPC64_LOCAL_MASK;
229     Other |= RhsSym.getOther() & ELF::STO_PPC64_LOCAL_MASK;
230     D->setOther(Other);
231     return true;
232   }
233 
234   unsigned encodePPC64LocalEntryOffset(const MCExpr *LocalOffset) {
235     MCAssembler &MCA = getStreamer().getAssembler();
236     int64_t Offset;
237     if (!LocalOffset->evaluateAsAbsolute(Offset, MCA))
238       MCA.getContext().reportFatalError(
239           LocalOffset->getLoc(), ".localentry expression must be absolute.");
240 
241     switch (Offset) {
242     default:
243       MCA.getContext().reportFatalError(
244           LocalOffset->getLoc(),
245           ".localentry expression is not a valid power of 2.");
246     case 0:
247       return 0;
248     case 1:
249       return 1 << ELF::STO_PPC64_LOCAL_BIT;
250     case 4:
251     case 8:
252     case 16:
253     case 32:
254     case 64:
255       return (int)Log2(Offset) << (int)ELF::STO_PPC64_LOCAL_BIT;
256     }
257   }
258 };
259 
260 class PPCTargetMachOStreamer : public PPCTargetStreamer {
261 public:
262   PPCTargetMachOStreamer(MCStreamer &S) : PPCTargetStreamer(S) {}
263 
264   void emitTCEntry(const MCSymbol &S) override {
265     llvm_unreachable("Unknown pseudo-op: .tc");
266   }
267 
268   void emitMachine(StringRef CPU) override {
269     // FIXME: We should update the CPUType, CPUSubType in the Object file if
270     // the new values are different from the defaults.
271   }
272 
273   void emitAbiVersion(int AbiVersion) override {
274     llvm_unreachable("Unknown pseudo-op: .abiversion");
275   }
276 
277   void emitLocalEntry(MCSymbolELF *S, const MCExpr *LocalOffset) override {
278     llvm_unreachable("Unknown pseudo-op: .localentry");
279   }
280 };
281 
282 class PPCTargetXCOFFStreamer : public PPCTargetStreamer {
283 public:
284   PPCTargetXCOFFStreamer(MCStreamer &S) : PPCTargetStreamer(S) {}
285 
286   void emitTCEntry(const MCSymbol &S) override {
287     const MCAsmInfo *MAI = Streamer.getContext().getAsmInfo();
288     const unsigned PointerSize = MAI->getCodePointerSize();
289     Streamer.emitValueToAlignment(PointerSize);
290     Streamer.emitSymbolValue(&S, PointerSize);
291   }
292 
293   void emitMachine(StringRef CPU) override {
294     llvm_unreachable("Machine pseudo-ops are invalid for XCOFF.");
295   }
296 
297   void emitAbiVersion(int AbiVersion) override {
298     llvm_unreachable("ABI-version pseudo-ops are invalid for XCOFF.");
299   }
300 
301   void emitLocalEntry(MCSymbolELF *S, const MCExpr *LocalOffset) override {
302     llvm_unreachable("Local-entry pseudo-ops are invalid for XCOFF.");
303   }
304 };
305 
306 } // end anonymous namespace
307 
308 static MCTargetStreamer *createAsmTargetStreamer(MCStreamer &S,
309                                                  formatted_raw_ostream &OS,
310                                                  MCInstPrinter *InstPrint,
311                                                  bool isVerboseAsm) {
312   return new PPCTargetAsmStreamer(S, OS);
313 }
314 
315 static MCTargetStreamer *
316 createObjectTargetStreamer(MCStreamer &S, const MCSubtargetInfo &STI) {
317   const Triple &TT = STI.getTargetTriple();
318   if (TT.isOSBinFormatELF())
319     return new PPCTargetELFStreamer(S);
320   if (TT.isOSBinFormatXCOFF())
321     return new PPCTargetXCOFFStreamer(S);
322   return new PPCTargetMachOStreamer(S);
323 }
324 
325 static MCInstPrinter *createPPCMCInstPrinter(const Triple &T,
326                                              unsigned SyntaxVariant,
327                                              const MCAsmInfo &MAI,
328                                              const MCInstrInfo &MII,
329                                              const MCRegisterInfo &MRI) {
330   return new PPCInstPrinter(MAI, MII, MRI, T);
331 }
332 
333 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCTargetMC() {
334   for (Target *T :
335        {&getThePPC32Target(), &getThePPC64Target(), &getThePPC64LETarget()}) {
336     // Register the MC asm info.
337     RegisterMCAsmInfoFn C(*T, createPPCMCAsmInfo);
338 
339     // Register the MC instruction info.
340     TargetRegistry::RegisterMCInstrInfo(*T, createPPCMCInstrInfo);
341 
342     // Register the MC register info.
343     TargetRegistry::RegisterMCRegInfo(*T, createPPCMCRegisterInfo);
344 
345     // Register the MC subtarget info.
346     TargetRegistry::RegisterMCSubtargetInfo(*T, createPPCMCSubtargetInfo);
347 
348     // Register the MC Code Emitter
349     TargetRegistry::RegisterMCCodeEmitter(*T, createPPCMCCodeEmitter);
350 
351     // Register the asm backend.
352     TargetRegistry::RegisterMCAsmBackend(*T, createPPCAsmBackend);
353 
354     // Register the elf streamer.
355     TargetRegistry::RegisterELFStreamer(*T, createPPCMCStreamer);
356 
357     // Register the object target streamer.
358     TargetRegistry::RegisterObjectTargetStreamer(*T,
359                                                  createObjectTargetStreamer);
360 
361     // Register the asm target streamer.
362     TargetRegistry::RegisterAsmTargetStreamer(*T, createAsmTargetStreamer);
363 
364     // Register the MCInstPrinter.
365     TargetRegistry::RegisterMCInstPrinter(*T, createPPCMCInstPrinter);
366   }
367 }
368