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/MCSubtargetInfo.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/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"
39 struct SrcMgrDiagInfo {
40 const MDNode *LocInfo;
41 LLVMContext::InlineAsmDiagHandlerTy DiagHandler;
46 /// SrcMgrDiagHandler - This callback is invoked when the SourceMgr for an
47 /// inline asm has an error in it. diagInfo is a pointer to the SrcMgrDiagInfo
49 static void SrcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
50 SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
51 assert(DiagInfo && "Diagnostic context not passed down?");
53 // If the inline asm had metadata associated with it, pull out a location
54 // cookie corresponding to which line the error occurred on.
55 unsigned LocCookie = 0;
56 if (const MDNode *LocInfo = DiagInfo->LocInfo) {
57 unsigned ErrorLine = Diag.getLineNo()-1;
58 if (ErrorLine >= LocInfo->getNumOperands())
61 if (LocInfo->getNumOperands() != 0)
62 if (const ConstantInt *CI =
63 dyn_cast<ConstantInt>(LocInfo->getOperand(ErrorLine)))
64 LocCookie = CI->getZExtValue();
67 DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
70 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
71 void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode) const {
72 assert(!Str.empty() && "Can't emit empty inline asm block");
74 // Remember if the buffer is nul terminated or not so we can avoid a copy.
75 bool isNullTerminated = Str.back() == 0;
77 Str = Str.substr(0, Str.size()-1);
79 // If the output streamer is actually a .s file, just emit the blob textually.
80 // This is useful in case the asm parser doesn't handle something but the
81 // system assembler does.
82 if (OutStreamer.hasRawTextSupport()) {
83 OutStreamer.EmitRawText(Str);
88 SrcMgrDiagInfo DiagInfo;
90 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
91 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
92 bool HasDiagHandler = false;
93 if (LLVMCtx.getInlineAsmDiagnosticHandler() != 0) {
94 // If the source manager has an issue, we arrange for SrcMgrDiagHandler
95 // to be invoked, getting DiagInfo passed into it.
96 DiagInfo.LocInfo = LocMDNode;
97 DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
98 DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
99 SrcMgr.setDiagHandler(SrcMgrDiagHandler, &DiagInfo);
100 HasDiagHandler = true;
103 MemoryBuffer *Buffer;
104 if (isNullTerminated)
105 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
107 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
109 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
110 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
112 OwningPtr<MCAsmParser> Parser(createMCAsmParser(TM.getTarget(), SrcMgr,
113 OutContext, OutStreamer,
116 // FIXME: It would be nice if we can avoid createing a new instance of
117 // MCSubtargetInfo here given TargetSubtargetInfo is available. However,
118 // we have to watch out for asm directives which can change subtarget
119 // state. e.g. .code 16, .code 32.
120 OwningPtr<MCSubtargetInfo>
121 STI(TM.getTarget().createMCSubtargetInfo(TM.getTargetTriple(),
123 TM.getTargetFeatureString()));
124 OwningPtr<TargetAsmParser> TAP(TM.getTarget().createAsmParser(*STI, *Parser));
126 report_fatal_error("Inline asm not supported by this streamer because"
127 " we don't have an asm parser for this target\n");
128 Parser->setTargetParser(*TAP.get());
130 // Don't implicitly switch to the text section before the asm.
131 int Res = Parser->Run(/*NoInitialTextSection*/ true,
132 /*NoFinalize*/ true);
133 if (Res && !HasDiagHandler)
134 report_fatal_error("Error parsing inline asm\n");
138 /// EmitInlineAsm - This method formats and emits the specified machine
139 /// instruction that is an inline asm.
140 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
141 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
143 unsigned NumOperands = MI->getNumOperands();
145 // Count the number of register definitions to find the asm string.
146 unsigned NumDefs = 0;
147 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
149 assert(NumDefs != NumOperands-2 && "No asm string?");
151 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
153 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
154 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
156 // If this asmstr is empty, just print the #APP/#NOAPP markers.
157 // These are useful to see where empty asm's wound up.
158 if (AsmStr[0] == 0) {
159 // Don't emit the comments if writing to a .o file.
160 if (!OutStreamer.hasRawTextSupport()) return;
162 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
163 MAI->getInlineAsmStart());
164 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
165 MAI->getInlineAsmEnd());
169 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
170 // enabled, so we use EmitRawText.
171 if (OutStreamer.hasRawTextSupport())
172 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
173 MAI->getInlineAsmStart());
175 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
177 unsigned LocCookie = 0;
178 const MDNode *LocMD = 0;
179 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
180 if (MI->getOperand(i-1).isMetadata() &&
181 (LocMD = MI->getOperand(i-1).getMetadata()) &&
182 LocMD->getNumOperands() != 0) {
183 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
184 LocCookie = CI->getZExtValue();
190 // Emit the inline asm to a temporary string so we can emit it through
192 SmallString<256> StringData;
193 raw_svector_ostream OS(StringData);
197 // The variant of the current asmprinter.
198 int AsmPrinterVariant = MAI->getAssemblerDialect();
200 int CurVariant = -1; // The number of the {.|.|.} region we are in.
201 const char *LastEmitted = AsmStr; // One past the last character emitted.
203 while (*LastEmitted) {
204 switch (*LastEmitted) {
206 // Not a special case, emit the string section literally.
207 const char *LiteralEnd = LastEmitted+1;
208 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
209 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
211 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
212 OS.write(LastEmitted, LiteralEnd-LastEmitted);
213 LastEmitted = LiteralEnd;
217 ++LastEmitted; // Consume newline character.
218 OS << '\n'; // Indent code with newline.
221 ++LastEmitted; // Consume '$' character.
225 switch (*LastEmitted) {
226 default: Done = false; break;
228 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
230 ++LastEmitted; // Consume second '$' character.
232 case '(': // $( -> same as GCC's { character.
233 ++LastEmitted; // Consume '(' character.
234 if (CurVariant != -1)
235 report_fatal_error("Nested variants found in inline asm string: '" +
236 Twine(AsmStr) + "'");
237 CurVariant = 0; // We're in the first variant now.
240 ++LastEmitted; // consume '|' character.
241 if (CurVariant == -1)
242 OS << '|'; // this is gcc's behavior for | outside a variant
244 ++CurVariant; // We're in the next variant.
246 case ')': // $) -> same as GCC's } char.
247 ++LastEmitted; // consume ')' character.
248 if (CurVariant == -1)
249 OS << '}'; // this is gcc's behavior for } outside a variant
256 bool HasCurlyBraces = false;
257 if (*LastEmitted == '{') { // ${variable}
258 ++LastEmitted; // Consume '{' character.
259 HasCurlyBraces = true;
262 // If we have ${:foo}, then this is not a real operand reference, it is a
263 // "magic" string reference, just like in .td files. Arrange to call
265 if (HasCurlyBraces && *LastEmitted == ':') {
267 const char *StrStart = LastEmitted;
268 const char *StrEnd = strchr(StrStart, '}');
270 report_fatal_error("Unterminated ${:foo} operand in inline asm"
271 " string: '" + Twine(AsmStr) + "'");
273 std::string Val(StrStart, StrEnd);
274 PrintSpecial(MI, OS, Val.c_str());
275 LastEmitted = StrEnd+1;
279 const char *IDStart = LastEmitted;
280 const char *IDEnd = IDStart;
281 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
284 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
285 report_fatal_error("Bad $ operand number in inline asm string: '" +
286 Twine(AsmStr) + "'");
289 char Modifier[2] = { 0, 0 };
291 if (HasCurlyBraces) {
292 // If we have curly braces, check for a modifier character. This
293 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
294 if (*LastEmitted == ':') {
295 ++LastEmitted; // Consume ':' character.
296 if (*LastEmitted == 0)
297 report_fatal_error("Bad ${:} expression in inline asm string: '" +
298 Twine(AsmStr) + "'");
300 Modifier[0] = *LastEmitted;
301 ++LastEmitted; // Consume modifier character.
304 if (*LastEmitted != '}')
305 report_fatal_error("Bad ${} expression in inline asm string: '" +
306 Twine(AsmStr) + "'");
307 ++LastEmitted; // Consume '}' character.
310 if (Val >= NumOperands-1)
311 report_fatal_error("Invalid $ operand number in inline asm string: '" +
312 Twine(AsmStr) + "'");
314 // Okay, we finally have a value number. Ask the target to print this
316 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
317 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
321 // Scan to find the machine operand number for the operand.
323 if (OpNo >= MI->getNumOperands()) break;
324 unsigned OpFlags = MI->getOperand(OpNo).getImm();
325 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
328 if (OpNo >= MI->getNumOperands()) {
331 unsigned OpFlags = MI->getOperand(OpNo).getImm();
332 ++OpNo; // Skip over the ID number.
334 if (Modifier[0] == 'l') // labels are target independent
335 // FIXME: What if the operand isn't an MBB, report error?
336 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
338 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
339 if (InlineAsm::isMemKind(OpFlags)) {
340 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
341 Modifier[0] ? Modifier : 0,
344 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
345 Modifier[0] ? Modifier : 0, OS);
351 raw_string_ostream Msg(msg);
352 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
353 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
360 OS << '\n' << (char)0; // null terminate string.
361 EmitInlineAsm(OS.str(), LocMD);
363 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
364 // enabled, so we use EmitRawText.
365 if (OutStreamer.hasRawTextSupport())
366 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
367 MAI->getInlineAsmEnd());
371 /// PrintSpecial - Print information related to the specified machine instr
372 /// that is independent of the operand, and may be independent of the instr
373 /// itself. This can be useful for portably encoding the comment character
374 /// or other bits of target-specific knowledge into the asmstrings. The
375 /// syntax used is ${:comment}. Targets can override this to add support
376 /// for their own strange codes.
377 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
378 const char *Code) const {
379 if (!strcmp(Code, "private")) {
380 OS << MAI->getPrivateGlobalPrefix();
381 } else if (!strcmp(Code, "comment")) {
382 OS << MAI->getCommentString();
383 } else if (!strcmp(Code, "uid")) {
384 // Comparing the address of MI isn't sufficient, because machineinstrs may
385 // be allocated to the same address across functions.
387 // If this is a new LastFn instruction, bump the counter.
388 if (LastMI != MI || LastFn != getFunctionNumber()) {
391 LastFn = getFunctionNumber();
396 raw_string_ostream Msg(msg);
397 Msg << "Unknown special formatter '" << Code
398 << "' for machine instr: " << *MI;
399 report_fatal_error(Msg.str());
403 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
404 /// instruction, using the specified assembler variant. Targets should
405 /// override this to format as appropriate.
406 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
407 unsigned AsmVariant, const char *ExtraCode,
409 // Target doesn't support this yet!
413 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
415 const char *ExtraCode, raw_ostream &O) {
416 // Target doesn't support this yet!