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/Constants.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Module.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/MC/MCSymbol.h"
25 #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"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/raw_ostream.h"
38 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
39 void AsmPrinter::EmitInlineAsm(StringRef Str, unsigned LocCookie) const {
40 assert(!Str.empty() && "Can't emit empty inline asm block");
42 // Remember if the buffer is nul terminated or not so we can avoid a copy.
43 bool isNullTerminated = Str.back() == 0;
45 Str = Str.substr(0, Str.size()-1);
47 // 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);
57 // Ensure the buffer is newline terminated.
59 if (Str.back() != '\n') {
60 TmpString = new char[Str.size() + 2];
61 memcpy(TmpString, Str.data(), Str.size());
62 TmpString[Str.size()] = '\n';
63 TmpString[Str.size() + 1] = 0;
64 isNullTerminated = true;
68 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
69 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
70 bool HasDiagHandler = false;
71 if (void *DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler()) {
72 SrcMgr.setDiagHandler((SourceMgr::DiagHandlerTy)(intptr_t)DiagHandler,
73 LLVMCtx.getInlineAsmDiagnosticContext(), LocCookie);
74 HasDiagHandler = true;
79 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
81 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
83 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
84 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
86 AsmParser Parser(TM.getTarget(), SrcMgr, OutContext, OutStreamer, *MAI);
87 OwningPtr<TargetAsmParser> TAP(TM.getTarget().createAsmParser(Parser));
89 report_fatal_error("Inline asm not supported by this streamer because"
90 " we don't have an asm parser for this target\n");
91 Parser.setTargetParser(*TAP.get());
93 // Don't implicitly switch to the text section before the asm.
94 int Res = Parser.Run(/*NoInitialTextSection*/ true,
96 if (Res && !HasDiagHandler)
97 report_fatal_error("Error parsing inline asm\n");
104 /// EmitInlineAsm - This method formats and emits the specified machine
105 /// instruction that is an inline asm.
106 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
107 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
109 unsigned NumOperands = MI->getNumOperands();
111 // Count the number of register definitions to find the asm string.
112 unsigned NumDefs = 0;
113 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
115 assert(NumDefs != NumOperands-2 && "No asm string?");
117 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
119 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
120 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
122 // If this asmstr is empty, just print the #APP/#NOAPP markers.
123 // These are useful to see where empty asm's wound up.
124 if (AsmStr[0] == 0) {
125 // Don't emit the comments if writing to a .o file.
126 if (!OutStreamer.hasRawTextSupport()) return;
128 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
129 MAI->getInlineAsmStart());
130 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
131 MAI->getInlineAsmEnd());
135 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
136 // enabled, so we use EmitRawText.
137 if (OutStreamer.hasRawTextSupport())
138 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
139 MAI->getInlineAsmStart());
141 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
143 unsigned LocCookie = 0;
144 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
145 if (MI->getOperand(i-1).isMetadata())
146 if (const MDNode *SrcLoc = MI->getOperand(i-1).getMetadata())
147 if (SrcLoc->getNumOperands() != 0)
148 if (const ConstantInt *CI =
149 dyn_cast<ConstantInt>(SrcLoc->getOperand(0))) {
150 LocCookie = CI->getZExtValue();
155 // Emit the inline asm to a temporary string so we can emit it through
157 SmallString<256> StringData;
158 raw_svector_ostream OS(StringData);
162 // The variant of the current asmprinter.
163 int AsmPrinterVariant = MAI->getAssemblerDialect();
165 int CurVariant = -1; // The number of the {.|.|.} region we are in.
166 const char *LastEmitted = AsmStr; // One past the last character emitted.
168 while (*LastEmitted) {
169 switch (*LastEmitted) {
171 // Not a special case, emit the string section literally.
172 const char *LiteralEnd = LastEmitted+1;
173 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
174 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
176 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
177 OS.write(LastEmitted, LiteralEnd-LastEmitted);
178 LastEmitted = LiteralEnd;
182 ++LastEmitted; // Consume newline character.
183 OS << '\n'; // Indent code with newline.
186 ++LastEmitted; // Consume '$' character.
190 switch (*LastEmitted) {
191 default: Done = false; break;
193 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
195 ++LastEmitted; // Consume second '$' character.
197 case '(': // $( -> same as GCC's { character.
198 ++LastEmitted; // Consume '(' character.
199 if (CurVariant != -1)
200 report_fatal_error("Nested variants found in inline asm string: '" +
201 Twine(AsmStr) + "'");
202 CurVariant = 0; // We're in the first variant now.
205 ++LastEmitted; // consume '|' character.
206 if (CurVariant == -1)
207 OS << '|'; // this is gcc's behavior for | outside a variant
209 ++CurVariant; // We're in the next variant.
211 case ')': // $) -> same as GCC's } char.
212 ++LastEmitted; // consume ')' character.
213 if (CurVariant == -1)
214 OS << '}'; // this is gcc's behavior for } outside a variant
221 bool HasCurlyBraces = false;
222 if (*LastEmitted == '{') { // ${variable}
223 ++LastEmitted; // Consume '{' character.
224 HasCurlyBraces = true;
227 // If we have ${:foo}, then this is not a real operand reference, it is a
228 // "magic" string reference, just like in .td files. Arrange to call
230 if (HasCurlyBraces && *LastEmitted == ':') {
232 const char *StrStart = LastEmitted;
233 const char *StrEnd = strchr(StrStart, '}');
235 report_fatal_error("Unterminated ${:foo} operand in inline asm"
236 " string: '" + Twine(AsmStr) + "'");
238 std::string Val(StrStart, StrEnd);
239 PrintSpecial(MI, OS, Val.c_str());
240 LastEmitted = StrEnd+1;
244 const char *IDStart = LastEmitted;
245 const char *IDEnd = IDStart;
246 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
249 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
250 report_fatal_error("Bad $ operand number in inline asm string: '" +
251 Twine(AsmStr) + "'");
254 char Modifier[2] = { 0, 0 };
256 if (HasCurlyBraces) {
257 // If we have curly braces, check for a modifier character. This
258 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
259 if (*LastEmitted == ':') {
260 ++LastEmitted; // Consume ':' character.
261 if (*LastEmitted == 0)
262 report_fatal_error("Bad ${:} expression in inline asm string: '" +
263 Twine(AsmStr) + "'");
265 Modifier[0] = *LastEmitted;
266 ++LastEmitted; // Consume modifier character.
269 if (*LastEmitted != '}')
270 report_fatal_error("Bad ${} expression in inline asm string: '" +
271 Twine(AsmStr) + "'");
272 ++LastEmitted; // Consume '}' character.
275 if (Val >= NumOperands-1)
276 report_fatal_error("Invalid $ operand number in inline asm string: '" +
277 Twine(AsmStr) + "'");
279 // Okay, we finally have a value number. Ask the target to print this
281 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
286 // Scan to find the machine operand number for the operand.
288 if (OpNo >= MI->getNumOperands()) break;
289 unsigned OpFlags = MI->getOperand(OpNo).getImm();
290 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
293 if (OpNo >= MI->getNumOperands()) {
296 unsigned OpFlags = MI->getOperand(OpNo).getImm();
297 ++OpNo; // Skip over the ID number.
299 if (Modifier[0] == 'l') // labels are target independent
300 // FIXME: What if the operand isn't an MBB, report error?
301 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
303 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
304 if (InlineAsm::isMemKind(OpFlags)) {
305 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
306 Modifier[0] ? Modifier : 0,
309 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
310 Modifier[0] ? Modifier : 0, OS);
316 raw_string_ostream Msg(msg);
317 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
318 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
325 OS << '\n' << (char)0; // null terminate string.
326 EmitInlineAsm(OS.str(), LocCookie);
328 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
329 // enabled, so we use EmitRawText.
330 if (OutStreamer.hasRawTextSupport())
331 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
332 MAI->getInlineAsmEnd());
336 /// PrintSpecial - Print information related to the specified machine instr
337 /// that is independent of the operand, and may be independent of the instr
338 /// itself. This can be useful for portably encoding the comment character
339 /// or other bits of target-specific knowledge into the asmstrings. The
340 /// syntax used is ${:comment}. Targets can override this to add support
341 /// for their own strange codes.
342 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
343 const char *Code) const {
344 if (!strcmp(Code, "private")) {
345 OS << MAI->getPrivateGlobalPrefix();
346 } else if (!strcmp(Code, "comment")) {
347 OS << MAI->getCommentString();
348 } else if (!strcmp(Code, "uid")) {
349 // Comparing the address of MI isn't sufficient, because machineinstrs may
350 // be allocated to the same address across functions.
352 // If this is a new LastFn instruction, bump the counter.
353 if (LastMI != MI || LastFn != getFunctionNumber()) {
356 LastFn = getFunctionNumber();
361 raw_string_ostream Msg(msg);
362 Msg << "Unknown special formatter '" << Code
363 << "' for machine instr: " << *MI;
364 report_fatal_error(Msg.str());
368 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
369 /// instruction, using the specified assembler variant. Targets should
370 /// override this to format as appropriate.
371 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
372 unsigned AsmVariant, const char *ExtraCode,
374 // Target doesn't support this yet!
378 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
380 const char *ExtraCode, raw_ostream &O) {
381 // Target doesn't support this yet!