LLVM 17.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
29#include "llvm/IR/Mangler.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 unsigned OpFlags = MI->getOperand(OpNum - 1).getImm();
122 unsigned NumOpRegs = InlineAsm::getNumOperandRegisters(OpFlags);
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,
138 ByteNumber % BytesPerReg ? AVR::sub_hi : 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 unsigned OpFlags = MI->getOperand(OpNum - 1).getImm();
180 unsigned NumOpRegs = InlineAsm::getNumOperandRegisters(OpFlags);
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 // FIXME: Enable feature predicate checks once all the test pass.
193 // AVR_MC::verifyInstructionPredicates(MI->getOpcode(),
194 // getSubtargetInfo().getFeatureBits());
195
196 AVRMCInstLower MCInstLowering(OutContext, *this);
197
198 MCInst I;
199 MCInstLowering.lowerInstruction(*MI, I);
201}
202
204 MCContext &Ctx = OutContext;
205
206 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
207 bool IsProgMem = GV->getAddressSpace() == AVR::ProgramMemory;
208 if (IsProgMem) {
209 const MCExpr *Expr = MCSymbolRefExpr::create(getSymbol(GV), Ctx);
210 return AVRMCExpr::create(AVRMCExpr::VK_AVR_PM, Expr, false, Ctx);
211 }
212 }
213
214 return AsmPrinter::lowerConstant(CV);
215}
216
218 if (!EmittedStructorSymbolAttrs) {
219 OutStreamer->emitRawComment(
220 " Emitting these undefined symbol references causes us to link the"
221 " libgcc code that runs our constructors/destructors");
222 OutStreamer->emitRawComment(" This matches GCC's behavior");
223
224 MCSymbol *CtorsSym = OutContext.getOrCreateSymbol("__do_global_ctors");
225 OutStreamer->emitSymbolAttribute(CtorsSym, MCSA_Global);
226
227 MCSymbol *DtorsSym = OutContext.getOrCreateSymbol("__do_global_dtors");
228 OutStreamer->emitSymbolAttribute(DtorsSym, MCSA_Global);
229
230 EmittedStructorSymbolAttrs = true;
231 }
232
234}
235
238 const AVRTargetMachine &TM = (const AVRTargetMachine &)MMI->getTarget();
239 const AVRSubtarget *SubTM = (const AVRSubtarget *)TM.getSubtargetImpl();
240
241 bool NeedsCopyData = false;
242 bool NeedsClearBSS = false;
243 for (const auto &GO : M.globals()) {
244 if (!GO.hasInitializer() || GO.hasAvailableExternallyLinkage())
245 // These globals aren't defined in the current object file.
246 continue;
247
248 if (GO.hasCommonLinkage()) {
249 // COMMON symbols are put in .bss.
250 NeedsClearBSS = true;
251 continue;
252 }
253
254 auto *Section = cast<MCSectionELF>(TLOF.SectionForGlobal(&GO, TM));
255 if (Section->getName().startswith(".data"))
256 NeedsCopyData = true;
257 else if (Section->getName().startswith(".rodata") && SubTM->hasLPM())
258 // AVRs that have a separate program memory (that's most AVRs) store
259 // .rodata sections in RAM.
260 NeedsCopyData = true;
261 else if (Section->getName().startswith(".bss"))
262 NeedsClearBSS = true;
263 }
264
265 MCSymbol *DoCopyData = OutContext.getOrCreateSymbol("__do_copy_data");
266 MCSymbol *DoClearBss = OutContext.getOrCreateSymbol("__do_clear_bss");
267
268 if (NeedsCopyData) {
269 OutStreamer->emitRawComment(
270 " Declaring this symbol tells the CRT that it should");
271 OutStreamer->emitRawComment(
272 "copy all variables from program memory to RAM on startup");
273 OutStreamer->emitSymbolAttribute(DoCopyData, MCSA_Global);
274 }
275
276 if (NeedsClearBSS) {
277 OutStreamer->emitRawComment(
278 " Declaring this symbol tells the CRT that it should");
279 OutStreamer->emitRawComment("clear the zeroed data section on startup");
280 OutStreamer->emitSymbolAttribute(DoClearBss, MCSA_Global);
281 }
282
284}
285
287 const AVRTargetMachine &TM = (const AVRTargetMachine &)MMI->getTarget();
288 const AVRSubtarget *SubTM = (const AVRSubtarget *)TM.getSubtargetImpl();
289 if (!SubTM)
290 return;
291
292 // Emit __tmp_reg__.
293 OutStreamer->emitAssignment(
294 MMI->getContext().getOrCreateSymbol(StringRef("__tmp_reg__")),
296 // Emit __zero_reg__.
297 OutStreamer->emitAssignment(
298 MMI->getContext().getOrCreateSymbol(StringRef("__zero_reg__")),
300 // Emit __SREG__.
301 OutStreamer->emitAssignment(
304 // Emit __SP_H__ if available.
305 if (!SubTM->hasSmallStack())
306 OutStreamer->emitAssignment(
309 // Emit __SP_L__.
310 OutStreamer->emitAssignment(
313 // Emit __EIND__ if available.
314 if (SubTM->hasEIJMPCALL())
315 OutStreamer->emitAssignment(
318 // Emit __RAMPZ__ if available.
319 if (SubTM->hasELPM())
320 OutStreamer->emitAssignment(
321 MMI->getContext().getOrCreateSymbol(StringRef("__RAMPZ__")),
323}
324
325} // end of namespace llvm
326
329}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAVRAsmPrinter()
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:127
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
IRTranslator LLVM IR MI
#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(unsigned RegNo, 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:38
@ 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
bool hasSmallStack() const
Definition: AVRSubtarget.h:70
bool hasELPM() const
Definition: AVRSubtarget.h:74
int getIORegRAMPZ() const
Get I/O register addresses.
Definition: AVRSubtarget.h:96
int getIORegSPL() const
Definition: AVRSubtarget.h:98
int getRegTmpIndex() const
Get GPR aliases.
Definition: AVRSubtarget.h:103
int getIORegSREG() const
Definition: AVRSubtarget.h:100
int getIORegEIND() const
Definition: AVRSubtarget.h:97
bool hasEIJMPCALL() const
Definition: AVRSubtarget.h:68
int getRegZeroIndex() const
Definition: AVRSubtarget.h:104
bool hasLPM() const
Definition: AVRSubtarget.h:72
int getIORegSPH() const
Definition: AVRSubtarget.h:99
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:84
const TargetLoweringObjectFile & getObjFileLowering() const
Return information about object file lowering.
Definition: AsmPrinter.cpp:379
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:662
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
Definition: AsmPrinter.cpp:398
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:87
virtual void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS)
Print the MachineOperand as a symbol.
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:102
MachineModuleInfo * MMI
This is a pointer to the current MachineModuleInfo.
Definition: AsmPrinter.h:105
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition: AsmPrinter.h:94
bool doFinalization(Module &M) override
Shut down the asmprinter.
MCSymbol * GetExternalSymbolSymbol(StringRef 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:99
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:588
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:41
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
static unsigned getNumOperandRegisters(unsigned Flag)
getNumOperandRegisters - Extract the number of registers field from the inline asm operand flag.
Definition: InlineAsm.h:363
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:194
Context object for machine code objects.
Definition: MCContext.h:76
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:201
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
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:386
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:68
const MCContext & getContext() const
const LLVMTargetMachine & 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:50
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:78
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:45
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:1909
@ MCSA_Global
.type _foo, @gnu_unique_object
Definition: MCDirectives.h:30
Definition: BitVector.h:851
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...