1 //===-- AsmPrinterInlineAsm.cpp - AsmPrinter Inline Asm Handling ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the inline assembler pieces of the AsmPrinter class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "asm-printer"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #include "llvm/InlineAsm.h"
17 #include "llvm/LLVMContext.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/MC/MCParser/AsmParser.h"
25 #include "llvm/Target/TargetAsmParser.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetRegistry.h"
28 #include "llvm/ADT/OwningPtr.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/raw_ostream.h"
37 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
38 void AsmPrinter::EmitInlineAsm(StringRef Str, unsigned LocCookie) const {
39 assert(!Str.empty() && "Can't emit empty inline asm block");
41 // Remember if the buffer is nul terminated or not so we can avoid a copy.
42 bool isNullTerminated = Str.back() == 0;
44 Str = Str.substr(0, Str.size()-1);
46 // If the output streamer is actually a .s file, just emit the blob textually.
47 // This is useful in case the asm parser doesn't handle something but the
48 // system assembler does.
49 if (OutStreamer.hasRawTextSupport()) {
50 OutStreamer.EmitRawText(Str);
56 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
57 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
58 bool HasDiagHandler = false;
59 if (void *DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler()) {
60 SrcMgr.setDiagHandler((SourceMgr::DiagHandlerTy)(intptr_t)DiagHandler,
61 LLVMCtx.getInlineAsmDiagnosticContext(), LocCookie);
62 HasDiagHandler = true;
67 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
69 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
71 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
72 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
74 AsmParser Parser(SrcMgr, OutContext, OutStreamer, *MAI);
75 OwningPtr<TargetAsmParser> TAP(TM.getTarget().createAsmParser(Parser));
77 llvm_report_error("Inline asm not supported by this streamer because"
78 " we don't have an asm parser for this target\n");
79 Parser.setTargetParser(*TAP.get());
81 // Don't implicitly switch to the text section before the asm.
82 int Res = Parser.Run(/*NoInitialTextSection*/ true,
84 if (Res && !HasDiagHandler)
85 llvm_report_error("Error parsing inline asm\n");
89 /// EmitInlineAsm - This method formats and emits the specified machine
90 /// instruction that is an inline asm.
91 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
92 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
94 unsigned NumOperands = MI->getNumOperands();
96 // Count the number of register definitions to find the asm string.
98 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
100 assert(NumDefs != NumOperands-1 && "No asm string?");
102 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
104 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
105 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
107 // If this asmstr is empty, just print the #APP/#NOAPP markers.
108 // These are useful to see where empty asm's wound up.
109 if (AsmStr[0] == 0) {
110 // Don't emit the comments if writing to a .o file.
111 if (!OutStreamer.hasRawTextSupport()) return;
113 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
114 MAI->getInlineAsmStart());
115 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
116 MAI->getInlineAsmEnd());
120 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
121 // enabled, so we use EmitRawText.
122 if (OutStreamer.hasRawTextSupport())
123 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
124 MAI->getInlineAsmStart());
126 // Emit the inline asm to a temporary string so we can emit it through
128 SmallString<256> StringData;
129 raw_svector_ostream OS(StringData);
133 // The variant of the current asmprinter.
134 int AsmPrinterVariant = MAI->getAssemblerDialect();
136 int CurVariant = -1; // The number of the {.|.|.} region we are in.
137 const char *LastEmitted = AsmStr; // One past the last character emitted.
139 while (*LastEmitted) {
140 switch (*LastEmitted) {
142 // Not a special case, emit the string section literally.
143 const char *LiteralEnd = LastEmitted+1;
144 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
145 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
147 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
148 OS.write(LastEmitted, LiteralEnd-LastEmitted);
149 LastEmitted = LiteralEnd;
153 ++LastEmitted; // Consume newline character.
154 OS << '\n'; // Indent code with newline.
157 ++LastEmitted; // Consume '$' character.
161 switch (*LastEmitted) {
162 default: Done = false; break;
164 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
166 ++LastEmitted; // Consume second '$' character.
168 case '(': // $( -> same as GCC's { character.
169 ++LastEmitted; // Consume '(' character.
170 if (CurVariant != -1)
171 llvm_report_error("Nested variants found in inline asm string: '"
172 + std::string(AsmStr) + "'");
173 CurVariant = 0; // We're in the first variant now.
176 ++LastEmitted; // consume '|' character.
177 if (CurVariant == -1)
178 OS << '|'; // this is gcc's behavior for | outside a variant
180 ++CurVariant; // We're in the next variant.
182 case ')': // $) -> same as GCC's } char.
183 ++LastEmitted; // consume ')' character.
184 if (CurVariant == -1)
185 OS << '}'; // this is gcc's behavior for } outside a variant
192 bool HasCurlyBraces = false;
193 if (*LastEmitted == '{') { // ${variable}
194 ++LastEmitted; // Consume '{' character.
195 HasCurlyBraces = true;
198 // If we have ${:foo}, then this is not a real operand reference, it is a
199 // "magic" string reference, just like in .td files. Arrange to call
201 if (HasCurlyBraces && *LastEmitted == ':') {
203 const char *StrStart = LastEmitted;
204 const char *StrEnd = strchr(StrStart, '}');
206 llvm_report_error(Twine("Unterminated ${:foo} operand in inline asm"
207 " string: '") + Twine(AsmStr) + "'");
209 std::string Val(StrStart, StrEnd);
210 PrintSpecial(MI, OS, Val.c_str());
211 LastEmitted = StrEnd+1;
215 const char *IDStart = LastEmitted;
216 const char *IDEnd = IDStart;
217 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
220 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
221 llvm_report_error("Bad $ operand number in inline asm string: '"
222 + std::string(AsmStr) + "'");
225 char Modifier[2] = { 0, 0 };
227 if (HasCurlyBraces) {
228 // If we have curly braces, check for a modifier character. This
229 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
230 if (*LastEmitted == ':') {
231 ++LastEmitted; // Consume ':' character.
232 if (*LastEmitted == 0)
233 llvm_report_error("Bad ${:} expression in inline asm string: '" +
234 std::string(AsmStr) + "'");
236 Modifier[0] = *LastEmitted;
237 ++LastEmitted; // Consume modifier character.
240 if (*LastEmitted != '}')
241 llvm_report_error("Bad ${} expression in inline asm string: '"
242 + std::string(AsmStr) + "'");
243 ++LastEmitted; // Consume '}' character.
246 if (Val >= NumOperands-1)
247 llvm_report_error("Invalid $ operand number in inline asm string: '"
248 + std::string(AsmStr) + "'");
250 // Okay, we finally have a value number. Ask the target to print this
252 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
257 // Scan to find the machine operand number for the operand.
259 if (OpNo >= MI->getNumOperands()) break;
260 unsigned OpFlags = MI->getOperand(OpNo).getImm();
261 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
264 if (OpNo >= MI->getNumOperands()) {
267 unsigned OpFlags = MI->getOperand(OpNo).getImm();
268 ++OpNo; // Skip over the ID number.
270 if (Modifier[0] == 'l') // labels are target independent
271 // FIXME: What if the operand isn't an MBB, report error?
272 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
274 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
275 if (InlineAsm::isMemKind(OpFlags)) {
276 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
277 Modifier[0] ? Modifier : 0,
280 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
281 Modifier[0] ? Modifier : 0, OS);
287 raw_string_ostream Msg(msg);
288 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
290 llvm_report_error(Msg.str());
297 OS << '\n' << (char)0; // null terminate string.
298 EmitInlineAsm(OS.str(), 0/*no loc cookie*/);
300 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
301 // enabled, so we use EmitRawText.
302 if (OutStreamer.hasRawTextSupport())
303 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
304 MAI->getInlineAsmEnd());
308 /// PrintSpecial - Print information related to the specified machine instr
309 /// that is independent of the operand, and may be independent of the instr
310 /// itself. This can be useful for portably encoding the comment character
311 /// or other bits of target-specific knowledge into the asmstrings. The
312 /// syntax used is ${:comment}. Targets can override this to add support
313 /// for their own strange codes.
314 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
315 const char *Code) const {
316 if (!strcmp(Code, "private")) {
317 OS << MAI->getPrivateGlobalPrefix();
318 } else if (!strcmp(Code, "comment")) {
319 OS << MAI->getCommentString();
320 } else if (!strcmp(Code, "uid")) {
321 // Comparing the address of MI isn't sufficient, because machineinstrs may
322 // be allocated to the same address across functions.
324 // If this is a new LastFn instruction, bump the counter.
325 if (LastMI != MI || LastFn != getFunctionNumber()) {
328 LastFn = getFunctionNumber();
333 raw_string_ostream Msg(msg);
334 Msg << "Unknown special formatter '" << Code
335 << "' for machine instr: " << *MI;
336 llvm_report_error(Msg.str());
340 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
341 /// instruction, using the specified assembler variant. Targets should
342 /// override this to format as appropriate.
343 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
344 unsigned AsmVariant, const char *ExtraCode,
346 // Target doesn't support this yet!
350 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
352 const char *ExtraCode, raw_ostream &O) {
353 // Target doesn't support this yet!