LLVM 20.0.0git
AVRAsmPrinter.cpp
Go to the documentation of this file.
1//===-- AVRAsmPrinter.cpp - AVR LLVM assembly writer ----------------------===//
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 contains a printer that converts from our internal representation
10// of machine-dependent LLVM code to GAS-format AVR assembly language.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AVR.h"
15#include "AVRMCInstLower.h"
16#include "AVRSubtarget.h"
17#include "AVRTargetMachine.h"
21
28#include "llvm/IR/Mangler.h"
29#include "llvm/IR/Module.h"
30#include "llvm/MC/MCContext.h"
31#include "llvm/MC/MCInst.h"
33#include "llvm/MC/MCStreamer.h"
34#include "llvm/MC/MCSymbol.h"
39
40#define DEBUG_TYPE "avr-asm-printer"
41
42namespace llvm {
43
44/// An AVR assembly code printer.
45class AVRAsmPrinter : public AsmPrinter {
46public:
47 AVRAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
48 : AsmPrinter(TM, std::move(Streamer)), MRI(*TM.getMCRegisterInfo()) {}
49
50 StringRef getPassName() const override { return "AVR Assembly Printer"; }
51
52 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
53
54 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
55 const char *ExtraCode, raw_ostream &O) override;
56
57 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNum,
58 const char *ExtraCode, raw_ostream &O) override;
59
60 void emitInstruction(const MachineInstr *MI) override;
61
62 const MCExpr *lowerConstant(const Constant *CV) override;
63
64 void emitXXStructor(const DataLayout &DL, const Constant *CV) override;
65
66 bool doFinalization(Module &M) override;
67
68 void emitStartOfAsmFile(Module &M) override;
69
70private:
71 const MCRegisterInfo &MRI;
72 bool EmittedStructorSymbolAttrs = false;
73};
74
75void AVRAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
76 raw_ostream &O) {
77 const MachineOperand &MO = MI->getOperand(OpNo);
78
79 switch (MO.getType()) {
82 break;
84 O << MO.getImm();
85 break;
87 O << getSymbol(MO.getGlobal());
88 break;
91 break;
93 O << *MO.getMBB()->getSymbol();
94 break;
95 default:
96 llvm_unreachable("Not implemented yet!");
97 }
98}
99
101 const char *ExtraCode, raw_ostream &O) {
102 // Default asm printer can only deal with some extra codes,
103 // so try it first.
104 if (!AsmPrinter::PrintAsmOperand(MI, OpNum, ExtraCode, O))
105 return false;
106
107 const MachineOperand &MO = MI->getOperand(OpNum);
108
109 if (ExtraCode && ExtraCode[0]) {
110 // Unknown extra code.
111 if (ExtraCode[1] != 0 || ExtraCode[0] < 'A' || ExtraCode[0] > 'Z')
112 return true;
113
114 // Operand must be a register when using 'A' ~ 'Z' extra code.
115 if (!MO.isReg())
116 return true;
117
118 Register Reg = MO.getReg();
119
120 unsigned ByteNumber = ExtraCode[0] - 'A';
121 const InlineAsm::Flag OpFlags(MI->getOperand(OpNum - 1).getImm());
122 const unsigned NumOpRegs = OpFlags.getNumOperandRegisters();
123
124 const AVRSubtarget &STI = MF->getSubtarget<AVRSubtarget>();
125 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
126
127 const TargetRegisterClass *RC = TRI.getMinimalPhysRegClass(Reg);
128 unsigned BytesPerReg = TRI.getRegSizeInBits(*RC) / 8;
129 assert(BytesPerReg <= 2 && "Only 8 and 16 bit regs are supported.");
130
131 unsigned RegIdx = ByteNumber / BytesPerReg;
132 if (RegIdx >= NumOpRegs)
133 return true;
134 Reg = MI->getOperand(OpNum + RegIdx).getReg();
135
136 if (BytesPerReg == 2) {
137 Reg = TRI.getSubReg(Reg, (ByteNumber % BytesPerReg) ? AVR::sub_hi
138 : AVR::sub_lo);
139 }
140
142 return false;
143 }
144
146 PrintSymbolOperand(MO, O); // Print global symbols.
147 else
148 printOperand(MI, OpNum, O); // Fallback to ordinary cases.
149
150 return false;
151}
152
154 unsigned OpNum, const char *ExtraCode,
155 raw_ostream &O) {
156 if (ExtraCode && ExtraCode[0])
157 return true; // Unknown modifier
158
159 const MachineOperand &MO = MI->getOperand(OpNum);
160 (void)MO;
161 assert(MO.isReg() && "Unexpected inline asm memory operand");
162
163 // TODO: We should be able to look up the alternative name for
164 // the register if it's given.
165 // TableGen doesn't expose a way of getting retrieving names
166 // for registers.
167 if (MI->getOperand(OpNum).getReg() == AVR::R31R30) {
168 O << "Z";
169 } else if (MI->getOperand(OpNum).getReg() == AVR::R29R28) {
170 O << "Y";
171 } else if (MI->getOperand(OpNum).getReg() == AVR::R27R26) {
172 O << "X";
173 } else {
174 assert(false && "Wrong register class for memory operand.");
175 }
176
177 // If NumOpRegs == 2, then we assume it is product of a FrameIndex expansion
178 // and the second operand is an Imm.
179 const InlineAsm::Flag OpFlags(MI->getOperand(OpNum - 1).getImm());
180 const unsigned NumOpRegs = OpFlags.getNumOperandRegisters();
181
182 if (NumOpRegs == 2) {
183 assert(MI->getOperand(OpNum).getReg() != AVR::R27R26 &&
184 "Base register X can not have offset/displacement.");
185 O << '+' << MI->getOperand(OpNum + 1).getImm();
186 }
187
188 return false;
189}
190
192 AVR_MC::verifyInstructionPredicates(MI->getOpcode(),
193 getSubtargetInfo().getFeatureBits());
194
195 AVRMCInstLower MCInstLowering(OutContext, *this);
196
197 MCInst I;
198 MCInstLowering.lowerInstruction(*MI, I);
200}
201
203 MCContext &Ctx = OutContext;
204
205 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
206 bool IsProgMem = GV->getAddressSpace() == AVR::ProgramMemory;
207 if (IsProgMem) {
208 const MCExpr *Expr = MCSymbolRefExpr::create(getSymbol(GV), Ctx);
209 return AVRMCExpr::create(AVRMCExpr::VK_AVR_PM, Expr, false, Ctx);
210 }
211 }
212
213 return AsmPrinter::lowerConstant(CV);
214}
215
217 if (!EmittedStructorSymbolAttrs) {
218 OutStreamer->emitRawComment(
219 " Emitting these undefined symbol references causes us to link the"
220 " libgcc code that runs our constructors/destructors");
221 OutStreamer->emitRawComment(" This matches GCC's behavior");
222
223 MCSymbol *CtorsSym = OutContext.getOrCreateSymbol("__do_global_ctors");
224 OutStreamer->emitSymbolAttribute(CtorsSym, MCSA_Global);
225
226 MCSymbol *DtorsSym = OutContext.getOrCreateSymbol("__do_global_dtors");
227 OutStreamer->emitSymbolAttribute(DtorsSym, MCSA_Global);
228
229 EmittedStructorSymbolAttrs = true;
230 }
231
233}
234
237 const AVRTargetMachine &TM = (const AVRTargetMachine &)MMI->getTarget();
238 const AVRSubtarget *SubTM = (const AVRSubtarget *)TM.getSubtargetImpl();
239
240 bool NeedsCopyData = false;
241 bool NeedsClearBSS = false;
242 for (const auto &GO : M.globals()) {
243 if (!GO.hasInitializer() || GO.hasAvailableExternallyLinkage())
244 // These globals aren't defined in the current object file.
245 continue;
246
247 if (GO.hasCommonLinkage()) {
248 // COMMON symbols are put in .bss.
249 NeedsClearBSS = true;
250 continue;
251 }
252
253 auto *Section = cast<MCSectionELF>(TLOF.SectionForGlobal(&GO, TM));
254 if (Section->getName().starts_with(".data"))
255 NeedsCopyData = true;
256 else if (Section->getName().starts_with(".rodata") && SubTM->hasLPM())
257 // AVRs that have a separate program memory (that's most AVRs) store
258 // .rodata sections in RAM.
259 NeedsCopyData = true;
260 else if (Section->getName().starts_with(".bss"))
261 NeedsClearBSS = true;
262 }
263
264 MCSymbol *DoCopyData = OutContext.getOrCreateSymbol("__do_copy_data");
265 MCSymbol *DoClearBss = OutContext.getOrCreateSymbol("__do_clear_bss");
266
267 if (NeedsCopyData) {
268 OutStreamer->emitRawComment(
269 " Declaring this symbol tells the CRT that it should");
270 OutStreamer->emitRawComment(
271 "copy all variables from program memory to RAM on startup");
272 OutStreamer->emitSymbolAttribute(DoCopyData, MCSA_Global);
273 }
274
275 if (NeedsClearBSS) {
276 OutStreamer->emitRawComment(
277 " Declaring this symbol tells the CRT that it should");
278 OutStreamer->emitRawComment("clear the zeroed data section on startup");
279 OutStreamer->emitSymbolAttribute(DoClearBss, MCSA_Global);
280 }
281
283}
284
286 const AVRTargetMachine &TM = (const AVRTargetMachine &)MMI->getTarget();
287 const AVRSubtarget *SubTM = (const AVRSubtarget *)TM.getSubtargetImpl();
288 if (!SubTM)
289 return;
290
291 // Emit __tmp_reg__.
292 OutStreamer->emitAssignment(
293 MMI->getContext().getOrCreateSymbol(StringRef("__tmp_reg__")),
295 // Emit __zero_reg__.
296 OutStreamer->emitAssignment(
297 MMI->getContext().getOrCreateSymbol(StringRef("__zero_reg__")),
299 // Emit __SREG__.
300 OutStreamer->emitAssignment(
303 // Emit __SP_H__ if available.
304 if (!SubTM->hasSmallStack())
305 OutStreamer->emitAssignment(
308 // Emit __SP_L__.
309 OutStreamer->emitAssignment(
312 // Emit __EIND__ if available.
313 if (SubTM->hasEIJMPCALL())
314 OutStreamer->emitAssignment(
317 // Emit __RAMPZ__ if available.
318 if (SubTM->hasELPM())
319 OutStreamer->emitAssignment(
320 MMI->getContext().getOrCreateSymbol(StringRef("__RAMPZ__")),
322}
323
324} // end of namespace llvm
325
328}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAVRAsmPrinter()
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:128
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
unsigned Reg
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
An AVR assembly code printer.
void emitInstruction(const MachineInstr *MI) override
Targets should implement this to emit instructions.
StringRef getPassName() const override
getPassName - Return a nice clean name for a pass.
const MCExpr * lowerConstant(const Constant *CV) override
Lower the specified LLVM Constant to an MCExpr.
bool doFinalization(Module &M) override
Shut down the asmprinter.
void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O)
bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNum, const char *ExtraCode, raw_ostream &O) override
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant as...
void emitXXStructor(const DataLayout &DL, const Constant *CV) override
Targets can override this to change how global constants that are part of a C++ static/global constru...
bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNum, const char *ExtraCode, raw_ostream &O) override
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant.
void emitStartOfAsmFile(Module &M) override
This virtual method can be overridden by targets that want to emit something at the start of their fi...
AVRAsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > Streamer)
static const char * getPrettyRegisterName(MCRegister Reg, MCRegisterInfo const &MRI)
static const AVRMCExpr * create(VariantKind Kind, const MCExpr *Expr, bool isNegated, MCContext &Ctx)
Creates an AVR machine code expression.
Definition: AVRMCExpr.cpp:37
@ VK_AVR_PM
Corresponds to pm(), reference to program memory.
Definition: AVRMCExpr.h:30
Lowers MachineInstr objects into MCInst objects.
void lowerInstruction(const MachineInstr &MI, MCInst &OutMI) const
Lowers a MachineInstr into a MCInst.
A specific AVR target MCU.
Definition: AVRSubtarget.h:32
int getIORegRAMPZ() const
Get I/O register addresses.
Definition: AVRSubtarget.h:81
int getIORegSPL() const
Definition: AVRSubtarget.h:83
int getRegTmpIndex() const
Get GPR aliases.
Definition: AVRSubtarget.h:88
int getIORegSREG() const
Definition: AVRSubtarget.h:85
int getIORegEIND() const
Definition: AVRSubtarget.h:82
int getRegZeroIndex() const
Definition: AVRSubtarget.h:89
int getIORegSPH() const
Definition: AVRSubtarget.h:84
const AVRRegisterInfo * getRegisterInfo() const override
Definition: AVRSubtarget.h:52
A generic AVR implementation.
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:86
const TargetLoweringObjectFile & getObjFileLowering() const
Return information about object file lowering.
Definition: AsmPrinter.cpp:408
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:701
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
Definition: AsmPrinter.cpp:428
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:89
virtual void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS)
Print the MachineOperand as a symbol.
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:104
MachineModuleInfo * MMI
This is a pointer to the current MachineModuleInfo.
Definition: AsmPrinter.h:107
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition: AsmPrinter.h:96
bool doFinalization(Module &M) override
Shut down the asmprinter.
MCSymbol * GetExternalSymbolSymbol(Twine Sym) const
Return the MCSymbol for the specified ExternalSymbol.
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:101
virtual const MCExpr * lowerConstant(const Constant *CV)
Lower the specified LLVM Constant to an MCExpr.
virtual void emitXXStructor(const DataLayout &DL, const Constant *CV)
Targets can override this to change how global constants that are part of a C++ static/global constru...
Definition: AsmPrinter.h:578
const MCSubtargetInfo & getSubtargetInfo() const
Return information about subtarget.
Definition: AsmPrinter.cpp:423
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant.
This is an important base class in LLVM.
Definition: Constant.h:42
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
unsigned getNumOperandRegisters() const
getNumOperandRegisters - Extract the number of registers field from the inline asm operand flag.
Definition: InlineAsm.h:357
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:222
Context object for machine code objects.
Definition: MCContext.h:83
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:212
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:34
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:185
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:398
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Representation of each machine instruction.
Definition: MachineInstr.h:69
const MCContext & getContext() const
const TargetMachine & getTarget() const
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
Register getReg() const
getReg - Returns the register number.
@ MO_Immediate
Immediate operand.
@ MO_GlobalAddress
Address of a global value.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
MCSection * SectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const
This method computes the appropriate section to emit the specified global variable or function defini...
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:77
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ ProgramMemory
Definition: AVR.h:44
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Target & getTheAVRTarget()
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1873
@ MCSA_Global
.type _foo, @gnu_unique_object
Definition: MCDirectives.h:30
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...