blob: 37d10e5c4ccd71bdc4cc3a9f31f3b6cd0c29835f [file] [log] [blame]
Chris Lattner7e1a8f82010-04-04 19:09:29 +00001//===-- AsmPrinterInlineAsm.cpp - AsmPrinter Inline Asm Handling ----------===//
Chris Lattner736e31d2010-04-04 18:34:07 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner7e1a8f82010-04-04 19:09:29 +000010// This file implements the inline assembler pieces of the AsmPrinter class.
Chris Lattner736e31d2010-04-04 18:34:07 +000011//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "asm-printer"
Chris Lattner736e31d2010-04-04 18:34:07 +000015#include "llvm/CodeGen/AsmPrinter.h"
Chris Lattnercf9a4152010-04-07 05:38:05 +000016#include "llvm/Constants.h"
Chris Lattner7e1a8f82010-04-04 19:09:29 +000017#include "llvm/InlineAsm.h"
Chris Lattner6eb78062010-04-06 00:55:39 +000018#include "llvm/LLVMContext.h"
19#include "llvm/Module.h"
Chris Lattner736e31d2010-04-04 18:34:07 +000020#include "llvm/CodeGen/MachineBasicBlock.h"
Chris Lattner6eb78062010-04-06 00:55:39 +000021#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner736e31d2010-04-04 18:34:07 +000022#include "llvm/MC/MCAsmInfo.h"
23#include "llvm/MC/MCStreamer.h"
24#include "llvm/MC/MCSymbol.h"
Chris Lattneraf632c92010-04-05 23:11:24 +000025#include "llvm/MC/MCParser/AsmParser.h"
26#include "llvm/Target/TargetAsmParser.h"
27#include "llvm/Target/TargetMachine.h"
28#include "llvm/Target/TargetRegistry.h"
29#include "llvm/ADT/OwningPtr.h"
Chris Lattner736e31d2010-04-04 18:34:07 +000030#include "llvm/ADT/SmallString.h"
31#include "llvm/ADT/Twine.h"
32#include "llvm/Support/ErrorHandling.h"
Chris Lattneraf632c92010-04-05 23:11:24 +000033#include "llvm/Support/MemoryBuffer.h"
34#include "llvm/Support/SourceMgr.h"
Chris Lattner736e31d2010-04-04 18:34:07 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner736e31d2010-04-04 18:34:07 +000036using namespace llvm;
37
38/// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
Chris Lattner885d9412010-04-06 00:58:50 +000039void AsmPrinter::EmitInlineAsm(StringRef Str, unsigned LocCookie) const {
Chris Lattner736e31d2010-04-04 18:34:07 +000040 assert(!Str.empty() && "Can't emit empty inline asm block");
41
Chris Lattneraf632c92010-04-05 23:11:24 +000042 // Remember if the buffer is nul terminated or not so we can avoid a copy.
43 bool isNullTerminated = Str.back() == 0;
44 if (isNullTerminated)
45 Str = Str.substr(0, Str.size()-1);
46
Chris Lattner736e31d2010-04-04 18:34:07 +000047 // If the output streamer is actually a .s file, just emit the blob textually.
48 // This is useful in case the asm parser doesn't handle something but the
49 // system assembler does.
50 if (OutStreamer.hasRawTextSupport()) {
51 OutStreamer.EmitRawText(Str);
52 return;
53 }
54
Chris Lattneraf632c92010-04-05 23:11:24 +000055 SourceMgr SrcMgr;
Chris Lattner6eb78062010-04-06 00:55:39 +000056
57 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
58 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
59 bool HasDiagHandler = false;
60 if (void *DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler()) {
Chris Lattner6eb78062010-04-06 00:55:39 +000061 SrcMgr.setDiagHandler((SourceMgr::DiagHandlerTy)(intptr_t)DiagHandler,
Chris Lattner885d9412010-04-06 00:58:50 +000062 LLVMCtx.getInlineAsmDiagnosticContext(), LocCookie);
Chris Lattner6eb78062010-04-06 00:55:39 +000063 HasDiagHandler = true;
64 }
65
Chris Lattneraf632c92010-04-05 23:11:24 +000066 MemoryBuffer *Buffer;
67 if (isNullTerminated)
68 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
69 else
70 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
71
72 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
73 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
74
75 AsmParser Parser(SrcMgr, OutContext, OutStreamer, *MAI);
76 OwningPtr<TargetAsmParser> TAP(TM.getTarget().createAsmParser(Parser));
77 if (!TAP)
Chris Lattner75361b62010-04-07 22:58:41 +000078 report_fatal_error("Inline asm not supported by this streamer because"
Benjamin Kramer1bd73352010-04-08 10:44:28 +000079 " we don't have an asm parser for this target\n");
Chris Lattneraf632c92010-04-05 23:11:24 +000080 Parser.setTargetParser(*TAP.get());
81
82 // Don't implicitly switch to the text section before the asm.
Chris Lattner79180e22010-04-05 23:15:42 +000083 int Res = Parser.Run(/*NoInitialTextSection*/ true,
84 /*NoFinalize*/ true);
Chris Lattner6eb78062010-04-06 00:55:39 +000085 if (Res && !HasDiagHandler)
Chris Lattner75361b62010-04-07 22:58:41 +000086 report_fatal_error("Error parsing inline asm\n");
Chris Lattner736e31d2010-04-04 18:34:07 +000087}
88
89
90/// EmitInlineAsm - This method formats and emits the specified machine
91/// instruction that is an inline asm.
92void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
93 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
94
95 unsigned NumOperands = MI->getNumOperands();
96
97 // Count the number of register definitions to find the asm string.
98 unsigned NumDefs = 0;
99 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
100 ++NumDefs)
Chris Lattnercf9a4152010-04-07 05:38:05 +0000101 assert(NumDefs != NumOperands-2 && "No asm string?");
Chris Lattner736e31d2010-04-04 18:34:07 +0000102
103 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
104
105 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
106 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
107
108 // If this asmstr is empty, just print the #APP/#NOAPP markers.
109 // These are useful to see where empty asm's wound up.
110 if (AsmStr[0] == 0) {
Chris Lattner4c842dd2010-04-05 22:42:30 +0000111 // Don't emit the comments if writing to a .o file.
Chris Lattner736e31d2010-04-04 18:34:07 +0000112 if (!OutStreamer.hasRawTextSupport()) return;
113
114 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
115 MAI->getInlineAsmStart());
116 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
117 MAI->getInlineAsmEnd());
118 return;
119 }
120
121 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
122 // enabled, so we use EmitRawText.
123 if (OutStreamer.hasRawTextSupport())
124 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
125 MAI->getInlineAsmStart());
126
Chris Lattnercf9a4152010-04-07 05:38:05 +0000127 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
128 // it.
129 unsigned LocCookie = 0;
Chris Lattnerd0024fe2010-04-08 18:20:52 +0000130 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
131 if (MI->getOperand(i-1).isMetadata())
132 if (const MDNode *SrcLoc = MI->getOperand(i-1).getMetadata())
133 if (SrcLoc->getNumOperands() != 0)
134 if (const ConstantInt *CI =
135 dyn_cast<ConstantInt>(SrcLoc->getOperand(0))) {
136 LocCookie = CI->getZExtValue();
137 break;
138 }
Chris Lattnercf9a4152010-04-07 05:38:05 +0000139 }
140
Chris Lattner736e31d2010-04-04 18:34:07 +0000141 // Emit the inline asm to a temporary string so we can emit it through
142 // EmitInlineAsm.
143 SmallString<256> StringData;
144 raw_svector_ostream OS(StringData);
145
146 OS << '\t';
147
148 // The variant of the current asmprinter.
149 int AsmPrinterVariant = MAI->getAssemblerDialect();
150
151 int CurVariant = -1; // The number of the {.|.|.} region we are in.
152 const char *LastEmitted = AsmStr; // One past the last character emitted.
153
154 while (*LastEmitted) {
155 switch (*LastEmitted) {
156 default: {
157 // Not a special case, emit the string section literally.
158 const char *LiteralEnd = LastEmitted+1;
159 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
160 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
161 ++LiteralEnd;
162 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
163 OS.write(LastEmitted, LiteralEnd-LastEmitted);
164 LastEmitted = LiteralEnd;
165 break;
166 }
167 case '\n':
168 ++LastEmitted; // Consume newline character.
Chris Lattner4c842dd2010-04-05 22:42:30 +0000169 OS << '\n'; // Indent code with newline.
Chris Lattner736e31d2010-04-04 18:34:07 +0000170 break;
171 case '$': {
172 ++LastEmitted; // Consume '$' character.
173 bool Done = true;
174
175 // Handle escapes.
176 switch (*LastEmitted) {
177 default: Done = false; break;
178 case '$': // $$ -> $
179 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
180 OS << '$';
181 ++LastEmitted; // Consume second '$' character.
182 break;
183 case '(': // $( -> same as GCC's { character.
184 ++LastEmitted; // Consume '(' character.
Chris Lattnerfee455e2010-04-07 05:27:36 +0000185 if (CurVariant != -1)
Benjamin Kramer1bd73352010-04-08 10:44:28 +0000186 report_fatal_error("Nested variants found in inline asm string: '" +
187 Twine(AsmStr) + "'");
Chris Lattner736e31d2010-04-04 18:34:07 +0000188 CurVariant = 0; // We're in the first variant now.
189 break;
190 case '|':
191 ++LastEmitted; // consume '|' character.
192 if (CurVariant == -1)
193 OS << '|'; // this is gcc's behavior for | outside a variant
194 else
195 ++CurVariant; // We're in the next variant.
196 break;
197 case ')': // $) -> same as GCC's } char.
198 ++LastEmitted; // consume ')' character.
199 if (CurVariant == -1)
200 OS << '}'; // this is gcc's behavior for } outside a variant
201 else
202 CurVariant = -1;
203 break;
204 }
205 if (Done) break;
206
207 bool HasCurlyBraces = false;
208 if (*LastEmitted == '{') { // ${variable}
209 ++LastEmitted; // Consume '{' character.
210 HasCurlyBraces = true;
211 }
212
213 // If we have ${:foo}, then this is not a real operand reference, it is a
214 // "magic" string reference, just like in .td files. Arrange to call
215 // PrintSpecial.
216 if (HasCurlyBraces && *LastEmitted == ':') {
217 ++LastEmitted;
218 const char *StrStart = LastEmitted;
219 const char *StrEnd = strchr(StrStart, '}');
220 if (StrEnd == 0)
Benjamin Kramer1bd73352010-04-08 10:44:28 +0000221 report_fatal_error("Unterminated ${:foo} operand in inline asm"
222 " string: '" + Twine(AsmStr) + "'");
Chris Lattner736e31d2010-04-04 18:34:07 +0000223
224 std::string Val(StrStart, StrEnd);
225 PrintSpecial(MI, OS, Val.c_str());
226 LastEmitted = StrEnd+1;
227 break;
228 }
229
230 const char *IDStart = LastEmitted;
Chris Lattner65eeaad2010-04-04 18:42:18 +0000231 const char *IDEnd = IDStart;
232 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
233
234 unsigned Val;
235 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
Benjamin Kramer1bd73352010-04-08 10:44:28 +0000236 report_fatal_error("Bad $ operand number in inline asm string: '" +
237 Twine(AsmStr) + "'");
Chris Lattner736e31d2010-04-04 18:34:07 +0000238 LastEmitted = IDEnd;
239
240 char Modifier[2] = { 0, 0 };
241
242 if (HasCurlyBraces) {
243 // If we have curly braces, check for a modifier character. This
244 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
245 if (*LastEmitted == ':') {
246 ++LastEmitted; // Consume ':' character.
Chris Lattner4c842dd2010-04-05 22:42:30 +0000247 if (*LastEmitted == 0)
Chris Lattner75361b62010-04-07 22:58:41 +0000248 report_fatal_error("Bad ${:} expression in inline asm string: '" +
Benjamin Kramer1bd73352010-04-08 10:44:28 +0000249 Twine(AsmStr) + "'");
Chris Lattner736e31d2010-04-04 18:34:07 +0000250
251 Modifier[0] = *LastEmitted;
252 ++LastEmitted; // Consume modifier character.
253 }
254
Chris Lattner4c842dd2010-04-05 22:42:30 +0000255 if (*LastEmitted != '}')
Benjamin Kramer1bd73352010-04-08 10:44:28 +0000256 report_fatal_error("Bad ${} expression in inline asm string: '" +
257 Twine(AsmStr) + "'");
Chris Lattner736e31d2010-04-04 18:34:07 +0000258 ++LastEmitted; // Consume '}' character.
259 }
260
Chris Lattner4c842dd2010-04-05 22:42:30 +0000261 if (Val >= NumOperands-1)
Benjamin Kramer1bd73352010-04-08 10:44:28 +0000262 report_fatal_error("Invalid $ operand number in inline asm string: '" +
263 Twine(AsmStr) + "'");
Chris Lattner736e31d2010-04-04 18:34:07 +0000264
265 // Okay, we finally have a value number. Ask the target to print this
266 // operand!
267 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
268 unsigned OpNo = 1;
269
270 bool Error = false;
271
272 // Scan to find the machine operand number for the operand.
273 for (; Val; --Val) {
274 if (OpNo >= MI->getNumOperands()) break;
275 unsigned OpFlags = MI->getOperand(OpNo).getImm();
276 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
277 }
278
279 if (OpNo >= MI->getNumOperands()) {
280 Error = true;
281 } else {
282 unsigned OpFlags = MI->getOperand(OpNo).getImm();
283 ++OpNo; // Skip over the ID number.
284
285 if (Modifier[0] == 'l') // labels are target independent
286 // FIXME: What if the operand isn't an MBB, report error?
287 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
288 else {
289 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
Chris Lattnerfee455e2010-04-07 05:27:36 +0000290 if (InlineAsm::isMemKind(OpFlags)) {
Chris Lattner736e31d2010-04-04 18:34:07 +0000291 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
292 Modifier[0] ? Modifier : 0,
293 OS);
294 } else {
295 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
296 Modifier[0] ? Modifier : 0, OS);
297 }
298 }
299 }
300 if (Error) {
301 std::string msg;
302 raw_string_ostream Msg(msg);
Chris Lattner38686bd2010-04-07 23:40:44 +0000303 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
304 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
Chris Lattner736e31d2010-04-04 18:34:07 +0000305 }
306 }
307 break;
308 }
309 }
310 }
Chris Lattneraf632c92010-04-05 23:11:24 +0000311 OS << '\n' << (char)0; // null terminate string.
Chris Lattnercf9a4152010-04-07 05:38:05 +0000312 EmitInlineAsm(OS.str(), LocCookie);
Chris Lattner736e31d2010-04-04 18:34:07 +0000313
314 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
315 // enabled, so we use EmitRawText.
316 if (OutStreamer.hasRawTextSupport())
317 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
318 MAI->getInlineAsmEnd());
319}
320
321
322/// PrintSpecial - Print information related to the specified machine instr
323/// that is independent of the operand, and may be independent of the instr
324/// itself. This can be useful for portably encoding the comment character
325/// or other bits of target-specific knowledge into the asmstrings. The
326/// syntax used is ${:comment}. Targets can override this to add support
327/// for their own strange codes.
328void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
329 const char *Code) const {
330 if (!strcmp(Code, "private")) {
331 OS << MAI->getPrivateGlobalPrefix();
332 } else if (!strcmp(Code, "comment")) {
333 OS << MAI->getCommentString();
334 } else if (!strcmp(Code, "uid")) {
335 // Comparing the address of MI isn't sufficient, because machineinstrs may
336 // be allocated to the same address across functions.
337
338 // If this is a new LastFn instruction, bump the counter.
339 if (LastMI != MI || LastFn != getFunctionNumber()) {
340 ++Counter;
341 LastMI = MI;
342 LastFn = getFunctionNumber();
343 }
344 OS << Counter;
345 } else {
346 std::string msg;
347 raw_string_ostream Msg(msg);
348 Msg << "Unknown special formatter '" << Code
349 << "' for machine instr: " << *MI;
Chris Lattner75361b62010-04-07 22:58:41 +0000350 report_fatal_error(Msg.str());
Chris Lattner736e31d2010-04-04 18:34:07 +0000351 }
352}
353
354/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
355/// instruction, using the specified assembler variant. Targets should
356/// override this to format as appropriate.
357bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
358 unsigned AsmVariant, const char *ExtraCode,
359 raw_ostream &O) {
360 // Target doesn't support this yet!
361 return true;
362}
363
364bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
365 unsigned AsmVariant,
366 const char *ExtraCode, raw_ostream &O) {
367 // Target doesn't support this yet!
368 return true;
369}
370