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/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 OwningPtr<MCAsmParser> Parser(createMCAsmParser(TM.getTarget(), SrcMgr,
75 OutContext, OutStreamer,
77 OwningPtr<TargetAsmParser> TAP(TM.getTarget().createAsmParser(*Parser));
79 report_fatal_error("Inline asm not supported by this streamer because"
80 " we don't have an asm parser for this target\n");
81 Parser->setTargetParser(*TAP.get());
83 // Don't implicitly switch to the text section before the asm.
84 int Res = Parser->Run(/*NoInitialTextSection*/ true,
86 if (Res && !HasDiagHandler)
87 report_fatal_error("Error parsing inline asm\n");
91 /// EmitInlineAsm - This method formats and emits the specified machine
92 /// instruction that is an inline asm.
93 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
94 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
96 unsigned NumOperands = MI->getNumOperands();
98 // Count the number of register definitions to find the asm string.
100 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
102 assert(NumDefs != NumOperands-2 && "No asm string?");
104 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
106 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
107 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
109 // If this asmstr is empty, just print the #APP/#NOAPP markers.
110 // These are useful to see where empty asm's wound up.
111 if (AsmStr[0] == 0) {
112 // Don't emit the comments if writing to a .o file.
113 if (!OutStreamer.hasRawTextSupport()) return;
115 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
116 MAI->getInlineAsmStart());
117 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
118 MAI->getInlineAsmEnd());
122 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
123 // enabled, so we use EmitRawText.
124 if (OutStreamer.hasRawTextSupport())
125 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
126 MAI->getInlineAsmStart());
128 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
130 unsigned LocCookie = 0;
131 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
132 if (MI->getOperand(i-1).isMetadata())
133 if (const MDNode *SrcLoc = MI->getOperand(i-1).getMetadata())
134 if (SrcLoc->getNumOperands() != 0)
135 if (const ConstantInt *CI =
136 dyn_cast<ConstantInt>(SrcLoc->getOperand(0))) {
137 LocCookie = CI->getZExtValue();
142 // Emit the inline asm to a temporary string so we can emit it through
144 SmallString<256> StringData;
145 raw_svector_ostream OS(StringData);
149 // The variant of the current asmprinter.
150 int AsmPrinterVariant = MAI->getAssemblerDialect();
152 int CurVariant = -1; // The number of the {.|.|.} region we are in.
153 const char *LastEmitted = AsmStr; // One past the last character emitted.
155 while (*LastEmitted) {
156 switch (*LastEmitted) {
158 // Not a special case, emit the string section literally.
159 const char *LiteralEnd = LastEmitted+1;
160 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
161 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
163 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
164 OS.write(LastEmitted, LiteralEnd-LastEmitted);
165 LastEmitted = LiteralEnd;
169 ++LastEmitted; // Consume newline character.
170 OS << '\n'; // Indent code with newline.
173 ++LastEmitted; // Consume '$' character.
177 switch (*LastEmitted) {
178 default: Done = false; break;
180 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
182 ++LastEmitted; // Consume second '$' character.
184 case '(': // $( -> same as GCC's { character.
185 ++LastEmitted; // Consume '(' character.
186 if (CurVariant != -1)
187 report_fatal_error("Nested variants found in inline asm string: '" +
188 Twine(AsmStr) + "'");
189 CurVariant = 0; // We're in the first variant now.
192 ++LastEmitted; // consume '|' character.
193 if (CurVariant == -1)
194 OS << '|'; // this is gcc's behavior for | outside a variant
196 ++CurVariant; // We're in the next variant.
198 case ')': // $) -> same as GCC's } char.
199 ++LastEmitted; // consume ')' character.
200 if (CurVariant == -1)
201 OS << '}'; // this is gcc's behavior for } outside a variant
208 bool HasCurlyBraces = false;
209 if (*LastEmitted == '{') { // ${variable}
210 ++LastEmitted; // Consume '{' character.
211 HasCurlyBraces = true;
214 // If we have ${:foo}, then this is not a real operand reference, it is a
215 // "magic" string reference, just like in .td files. Arrange to call
217 if (HasCurlyBraces && *LastEmitted == ':') {
219 const char *StrStart = LastEmitted;
220 const char *StrEnd = strchr(StrStart, '}');
222 report_fatal_error("Unterminated ${:foo} operand in inline asm"
223 " string: '" + Twine(AsmStr) + "'");
225 std::string Val(StrStart, StrEnd);
226 PrintSpecial(MI, OS, Val.c_str());
227 LastEmitted = StrEnd+1;
231 const char *IDStart = LastEmitted;
232 const char *IDEnd = IDStart;
233 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
236 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
237 report_fatal_error("Bad $ operand number in inline asm string: '" +
238 Twine(AsmStr) + "'");
241 char Modifier[2] = { 0, 0 };
243 if (HasCurlyBraces) {
244 // If we have curly braces, check for a modifier character. This
245 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
246 if (*LastEmitted == ':') {
247 ++LastEmitted; // Consume ':' character.
248 if (*LastEmitted == 0)
249 report_fatal_error("Bad ${:} expression in inline asm string: '" +
250 Twine(AsmStr) + "'");
252 Modifier[0] = *LastEmitted;
253 ++LastEmitted; // Consume modifier character.
256 if (*LastEmitted != '}')
257 report_fatal_error("Bad ${} expression in inline asm string: '" +
258 Twine(AsmStr) + "'");
259 ++LastEmitted; // Consume '}' character.
262 if (Val >= NumOperands-1)
263 report_fatal_error("Invalid $ operand number in inline asm string: '" +
264 Twine(AsmStr) + "'");
266 // Okay, we finally have a value number. Ask the target to print this
268 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
273 // Scan to find the machine operand number for the operand.
275 if (OpNo >= MI->getNumOperands()) break;
276 unsigned OpFlags = MI->getOperand(OpNo).getImm();
277 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
280 if (OpNo >= MI->getNumOperands()) {
283 unsigned OpFlags = MI->getOperand(OpNo).getImm();
284 ++OpNo; // Skip over the ID number.
286 if (Modifier[0] == 'l') // labels are target independent
287 // FIXME: What if the operand isn't an MBB, report error?
288 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
290 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
291 if (InlineAsm::isMemKind(OpFlags)) {
292 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
293 Modifier[0] ? Modifier : 0,
296 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
297 Modifier[0] ? Modifier : 0, OS);
303 raw_string_ostream Msg(msg);
304 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
305 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
312 OS << '\n' << (char)0; // null terminate string.
313 EmitInlineAsm(OS.str(), LocCookie);
315 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
316 // enabled, so we use EmitRawText.
317 if (OutStreamer.hasRawTextSupport())
318 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
319 MAI->getInlineAsmEnd());
323 /// PrintSpecial - Print information related to the specified machine instr
324 /// that is independent of the operand, and may be independent of the instr
325 /// itself. This can be useful for portably encoding the comment character
326 /// or other bits of target-specific knowledge into the asmstrings. The
327 /// syntax used is ${:comment}. Targets can override this to add support
328 /// for their own strange codes.
329 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
330 const char *Code) const {
331 if (!strcmp(Code, "private")) {
332 OS << MAI->getPrivateGlobalPrefix();
333 } else if (!strcmp(Code, "comment")) {
334 OS << MAI->getCommentString();
335 } else if (!strcmp(Code, "uid")) {
336 // Comparing the address of MI isn't sufficient, because machineinstrs may
337 // be allocated to the same address across functions.
339 // If this is a new LastFn instruction, bump the counter.
340 if (LastMI != MI || LastFn != getFunctionNumber()) {
343 LastFn = getFunctionNumber();
348 raw_string_ostream Msg(msg);
349 Msg << "Unknown special formatter '" << Code
350 << "' for machine instr: " << *MI;
351 report_fatal_error(Msg.str());
355 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
356 /// instruction, using the specified assembler variant. Targets should
357 /// override this to format as appropriate.
358 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
359 unsigned AsmVariant, const char *ExtraCode,
361 // Target doesn't support this yet!
365 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
367 const char *ExtraCode, raw_ostream &O) {
368 // Target doesn't support this yet!